Associating a pair of Strings in Java 7 and looping over them - java

Given the following code:-
//setup code and import statements, including:
private static String baseURL = Environment.getTestWebsiteURL();
public static String articleOneName = ArticleCreationTest.getArticleOneName();
public static String articleTwoName = ArticleCreationTest.getArticleTwoName();
public static String articleThreeName = ArticleCreationTest.getArticleThreeName();
public static String articleOnePath = ArticleCreationTest.getArticleOnePath();
public static String articleTwoPath = ArticleCreationTest.getArticleTwoPath();
public static String articleThreePath = ArticleCreationTest.getArticleThreePath();
public static String[] articlesPathArray = {articleOnePath, articleTwoPath, articleThreePath}
#BeforeClass
public static void setup() {
driver = Driver.getURL();
for (String s : articlesArray) {
if (s == null) {
//tell me which articles could not be found
System.out.println("Could not find an article for: " + s + " , perhaps it wasn't created in the prior test");
} else {
//assuming array holds some path values, append to the baseURL
driver.get(baseURL + s);
}
}
#Test...
//run some test assertions against the baseURL + path website page that is returned
I need the code to loop through wherever the path variable holds a value and run tests. The current solution is not helpful wherever the prior ArticleCreationTest fails to generate the article, because the variable simply contains null. So the text is: "Could not find an article for: null, perhaps it wasn't created in the prior test".
What I really need is to associate the articleName with the articlePath so the message is something like: "Could not find ArticleOne: perhaps is wasn't created", and then run the tests against all that were created. Perhaps some kind of hashmap or 2D array?

Based on the code given,
public static String articleOneName = ArticleCreationTest.getArticleOneName();
public static String articleTwoName = ArticleCreationTest.getArticleTwoName();
public static String articleThreeName = ArticleCreationTest.getArticleThreeName();
public static String articleOnePath = ArticleCreationTest.getArticleOnePath();
public static String articleTwoPath = ArticleCreationTest.getArticleTwoPath();
public static String articleThreePath = ArticleCreationTest.getArticleThreePath();
public static String[] articlesPathArray = {articleOnePath, articleTwoPath, articleThreePath}
It seems like, it is a list of articleNames and articlePaths
List<String> acticleNames = new ArrayList<String>();
List<String> acticlePaths = new ArrayList<String>();
The List will contain the Strings to be checked, which can be used for the tests.
I need the code to loop through wherever the path variable holds a
value and run tests
You can check this condition by checking if (s != null), currently you are checking for
if (s == null)

Related

(Using Spring)How to stop DTO from repeating when the map appears to be fine?

In this program I have three numbers the user enters in and I am trying to get the second number in the set to display by being pulled from the DTO so that I can confirm that everything is working fine. But something is going wrong as you'll see by the output...
User Enters: 858508321,858509491,858510385
//This code is what is being executed. (Think of it as main)
private void handleSubmit(final AjaxRequestTarget target) {
List<Long> msgNums = new ArrayList<Long>();
msg_Num = Ta.getInput();
String[] Numbers = msg_Num.split(",");
for(String Number:Numbers){
msgNums.add(Long.valueOf(Number));
}
System.out.println(msgNums.get(1));
List<BulkReplayMessageDTO> brm = messageReplayDao.getMessageResults(msgNums);
System.out.println(brm.get(1).getMsgNum());
}
//This is the DAO
public class MessageReplayDao extends SimpleJdbcDaoSupport {
private final static String sql = "SELECT MSG_NBR, MSG_CPSD_DATA"
+ " FROM nti_raw_msg"
+ " WHERE THRD_NAME IS NOT null AND THRD_NAME NOT LIKE"
+ " 'out%' AND MSG_NBR IN (:messageNumbers)";
public List<BulkReplayMessageDTO> getMessageResults(final List<Long> msgNumList){
SqlParameterSource parameters = new MapSqlParameterSource()
.addValue("messageNumbers", msgNumList);
List<BulkReplayMessageDTO> result = getSimpleJdbcTemplate().query(sql, new MessageReplayMap(), parameters);
return result;
}
}
//The Map
public class MessageReplayMap implements ParameterizedRowMapper<BulkReplayMessageDTO> {
public MessageReplayMap(){
}
LobHandler lobHandler = new DefaultLobHandler();
#Override
public final BulkReplayMessageDTO mapRow(ResultSet rs, int rowNum)
throws SQLException {
final BulkReplayMessageDTO brm = new BulkReplayMessageDTO();
System.out.println(rowNum);
brm.setMsgNum(rs.getLong("MSG_NBR"));
brm.setMSG(CompressionUtils.uncompress(lobHandler.getBlobAsBytes(rs, "MSG_CPSD_DATA")));
return brm;
}
}
//And finally the DTO
public class BulkReplayMessageDTO{
private static Long msgNum;
private static String MSG;
public final Long getMsgNum() {
return msgNum;
}
public final void setMsgNum(final Long msgNumTemp) {
msgNum = msgNumTemp;
}
public final String getMSG(){
return MSG;
}
public final void setMSG(final String MSGTemp){
MSG = MSGTemp;
}
}
Notice that I have printed to the console in the handleSubmit method, and inside my map. The output I get is
858509491
0
1
2
858510385
when it should be
858509491
0
1
2
858509491
I have no clue what the problem could be since I have found other code example that are pretty much the same and mine seems to be pretty similar. I am pretty new to using Spring, so sorry if the answer is really obvious.
I have found the problem, and it was a really simple one. In the DTO the variables were made static from a previous problem I was working on. I had forgotten to get rid of it after I had fixed the issue. If I understand the meaning of static, then I had made all the instances of those variables the same. So that is why I could only print out the last number that had been entered in by the user.

How to Store objects in an ArrayList when you do not know how many object you need to create?

Back ground: I am pairing up two pieces of data, both Strings, into an ArrayList. Therefore I am storing the paired data into an object, and then storing this object into an ArrayList. I have a text file that for each word, I am assigning a number to. The paired data is then word-number (but I have typed them both as String). I do not know how many objects I will need for any given file size.
How do I set up a logic to iterate through the text file and populate my ArrayList. This is what I have done so far:
The : PredictivePrototype.wordToSignature(aWord)// converts the word into a number signature e.g "4663" for a word like "home"
public class ListDictionary {
private static ArrayList<WordSig> dictionary;
public ListDictionary() throws FileNotFoundException {
File theFile = new File("words");
Scanner src = new Scanner(theFile);
while (src.hasNext()) {
String aWord = src.next();
String sigOfWord = PredictivePrototype.wordToSignature(aWord);
// assign each word and its corresponding signature into attribute
// of an object(p) of class WordSig.
//WordSig p1 = new WordSig(aWord, sigOfWord);
//Then add this instance (object) of class Wordsig into ArrayList<WordSig>
dictionary.add(new WordSig(aWord, sigOfWord));
}
src.close();
}
Other class to which paired data is stored:
public class WordSig {
private String words;
private String signature;
public WordSig(String words, String signature) {
this.words=words;
this.signature=signature;
}
}
Your code seems to be OK. With ArrayList you can add as many elements as you want (by using add() function).
Here is an example:
import java.util.ArrayList;
public class ListDictionary {
public class WordSig {
private String words;
private String signature;
public WordSig(String words, String signature) {
this.words=words;
this.signature=signature;
}
public String getWords() {
return words;
}
public String getSignature() {
return signature;
}
}
private static ArrayList<WordSig> dictionary = new ArrayList<WordSig>();
public ListDictionary() {
// add as many as you want
for ( int i=0; i < 10; i++)
dictionary.add(new WordSig("key"+i, "value"+i));
}
public static class testListDictionary {
public static void main(String[] args) {
new ListDictionary();
// test output
for ( int i=0; i < dictionary.size(); i++ )
System.out.println( "<" + dictionary.get(i).getWords() + "|"
+ dictionary.get(i).getSignature() + ">");
}
}
}

Java: How can i persist RandomStringUUID object at runtime

Here is the scenario:
I have:
public class RandomStringUUID {
public RandomStringUUID() {
final String uuidstring = UUID.randomUUID().toString().replaceAll("-", "");
}
public String getRandomStringUUID() {
final String uuidst = UUID.randomUUID().toString().replaceAll("-", "");
return uuidst;
}
}
Where i am generating a Unique Value.
Then in :
public class AddSingleDomain {
public static RandomStringUUID RUUID = new RandomStringUUID();
#Test
public void addSingleDomain() {
AssertJUnit.assertEquals(DomainsPage.getTitle(), "View Account");
String randomUIDSeed = RUUID.getRandomStringUUID();
System.out.println("Random Domanin Name Prefix: "
+ randomUIDSeed);
System.out.println("Random Domanin Name Prefix: " + RUUID);
getDriver().findElement(By.name("vo.zoneName")).sendKeys(
randomUIDSeed + ".tv");
I use it, and then, yet in another class:
public class VerifyDBSingleDomain {
String url = "jdbc:oracle:thin:#a.b.c.d:1521:ms";
#Test
public void VerifyDBSingleDomainTest() {
Properties props = new Properties();
props.setProperty("user", "user");
props.setProperty("password", "pass");
String sql = "Select zoneid from zone where zonename =" + randomUIDSeed + ".tv";
I want to use the SAME VALUE "randomUIDSeed"
If in class VerifyDBSingleDomain i : String randomUIDSeed = RUUID.getRandomStringUUID();
would it be the same object ? How can i use this as same object, and hence guranteeing the same value across ALL classes during runtime.
You could start by making this little change:
public class RandomStringUUID {
private static final String MYUUID = UUID.randomUUID().toString().replaceAll("-", "");
public static String getRandomStringUUID() { return MYUUID; }
}
You can then use it like this:
// Anywhere in your code: vv Note that we are using the classname! The method is static.
String theCommonID = RandomStringUUID.getRandomStringUUID();
This is just a hint into the direction. This is not a "perfect" clean solution. You might want to google "Singleton Design Pattern". And I can imagine ~10 other ways to do this right now ... But anyway.
This will create one of your IDs once for the runtime of your app.
I'm not quite sure what you're trying to achieve, however;
The short answer to your question is "Yes you will get the same String instance".
The slightly longer answer is "But you're doing it wrong".
You really should use a persistence framework to help you deal with these issues.

java return string from class (linkedhashmap)

Not sure if the title makes sense, but I am trying to return a Success message from a class that receives a linkedhashmap, however eclipse is giving me error when I try to compile the files, offering
Remove arguments to match 'logFile()'
Create constructor 'logFile(Map<String, String>)'
How do set it up to send a Map and revieve a String?
thx
Art
Code corrected as per #Jeff Storey below with error suppression for eclipse
calling class
eventLog.put(stringA,stringB);
logFile logStuff = new logFile();
successRtn = logFile.Process(eventLog);
// Do Stuff with SuccessRtn
logFile class
public class logFile {
static String Success = "Fail";
public static String Process(Map<String, String> eventlog){
// Do Stuff
Success = "Yeh!"
return Success;
}
public static void main(String[] args){
#SuppressWarnings("static-access")
String result = new logFile().Procces(eventLog);
System.out.println("result = " + result);
}
The main method is a special method whose signature must public static void main(String[] args) when being used as an entry point to your application. Create a second method that does the actual work, like this:
public class LogFile {
public String process(Map<String,String> eventLog) {
// do stuff
return success;
}
public void main(String[] args) {
// eventLog will probably be read from a filepath passed into the args
String result = new LogFile().process(eventLog);
System.out.println("result = " + result);
}
}
Note that a lot of your naming conventions are also non standard. Classes should begin with a capital letter and variables should begin with a lower case.

Dynamically return a list of all class variable values in Java

I am creating a helper class in parsing XML elements, so the developer do not need to know the exact name and capitalization of the XML fields.
private static class TagNames{
public static String RESOURCE_ID = "ResourceId";
public static String RESOURCE_NAME = "ResourceName";
public static String RESOURCE_PRICE = "ResourcePrice";
}
This makes it easier to do things like:
someXMLParser.getValueByTagName(TagNames.RESOURCE_ID);
My question is this. If I want to iterate over all the fields declared in class TagNames, how do I do that? Pseudocode:
For tag in TagNames:
someXMLParser.getValueByTagName(tag)
I know I will probably have to restructure all of this. But I can't figure out a way to make the names easily accessible as well as iterable, without any duplication.
Any suggestions?
You're literally asking for a solution based on reflection, but I think a Java Enum may be a better choice in this case. Building on Frederick's example:
public class EnumTest {
public enum Tags {
RESOURCE_ID("ResourceId"),
REOURCE_NAME("ResourceName"),
RESOURCE_PRICE("ResourcePrice");
private final String tagName;
Tags(String tagName) {
this.tagName = tagName;
}
public String getTagName() {
return tagName;
}
}
public static void main(String[] args) {
for(Tags tag : Tags.values()) {
System.out.println("const:" + tag.name()
+ " tagName:" + tag.getTagName());
}
// API user might do e.g.:
// document.getValueForTag(Tags.REOURCE_NAME);
}
}
Although I agree that you should probably use enums or ResourceBundles, here's a solution to your actual question. A method that generates a Map name -> value from all public constants in a given class (the only thing that's missing should be try / catch or throws)
public static Map<String, Object> getConstantValues(Class<?> clazz){
Map<String, Object> constantValues = new LinkedHashMap<String, Object>();
for(Field field : clazz.getDeclaredFields()){
int modifiers = field.getModifiers();
if(Modifiers.isPublic(mod)
&& Modifiers.isStatic(mod) && Modifiers.isFinal(mod)){
constantValues.put(field.getName(), field.get(null));
}
}
return constantValues;
}
You may want to consider using a ResourceBundle instead of a class to store the tag names. May require a little bit of reworking of your code but it will be easier to produce a list of tags compared to what you are doing now, and adding a new tag won't require much work other then adding a line to the properties file.
You can do this quite easily using enum and an accompanying array:
public class Main {
public enum TagName { RESOURCE_ID, REOURCE_NAME, RESOURCE_PRICE }
private static String[] tags = {"ResourceID", "ResourceName", "ResourcePrice"};
public static String getValueByTagName(TagName tag) {
return tags[tag.ordinal()];
}
public static void main(String[] args) {
System.out.println("Calling by getValueByTagName:");
System.out.println(getValueByTagName(TagName.RESOURCE_ID));
System.out.println("Calling TagName.values() for loop:");
for (TagName t : TagName.values()) {
System.out.println(getValueByTagName(t));
}
}
}
Using an enum is a good fit, especially if you use a custom constructor and the built in "values" method:
public class Main {
public static enum TagName {
RESOURCE_ID("ResourceId"),
RESOURCE_NAME("ResourceName"),
RESOURCE_PRICE("ResourcePrice"),
;
private String s;
private TagName(String s) { this.s = s; }
public String toString() { return this.s; }
public static String[] strings() {
List<String> ss = new ArrayList<String>();
for (TagName tagName : TagName.values()) {
ss.add(tagName.toString());
}
return ss.toArray(new String[ss.size()]);
}
}
public static void main(String[] args) {
// Use TagName.values() for the enums, or for strings...
for (String s : TagName.strings()) {
System.out.println(s);
}
}
}
This way you can simply add new tags and they'll automatically get picked up by the "strings" method; for extra performance you could compute that string array just once, statically, since you can't change the set of enums dynamically. You could get even fancier by auto-generating the tag strings from their constant values, if they are really normalized...

Categories