I am using cardme library to deal with vcards. Following is my code
package vcardtest;
import java.io.*;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.cardme.engine.VCardEngine;
import net.sourceforge.cardme.vcard.VCard;
import net.sourceforge.cardme.vcard.features.EmailFeature;
import net.sourceforge.cardme.vcard.features.NameFeature;
import net.sourceforge.cardme.vcard.features.NicknameFeature;
import net.sourceforge.cardme.vcard.features.TelephoneFeature;
import net.sourceforge.cardme.vcard.types.parameters.TelephoneParameterType;
public class VCardTest
{
public static void main(String[] args)
{
File vcardFile = new File("C:/Users/yohan/Contacts/Yohan Weerasinghe.vcf");
VCardEngine vcardEngine = new VCardEngine();
try
{
VCard vcard = vcardEngine.parse(vcardFile);
String name = vcard.getName().getGivenName();
EmailFeature email = vcard.getEmails().next();
String sEmail = email.getEmail();
NicknameFeature nickName = vcard.getNicknames();
Iterator<String> nicknames = nickName.getNicknames();
String sNickName = nicknames.next();
Iterator<TelephoneFeature> telephoneNumbers = vcard.getTelephoneNumbers();
TelephoneFeature next = telephoneNumbers.next();
String telephone = "";
while(vcard.getTelephoneNumbers().hasNext())
{
TelephoneFeature next1 = vcard.getTelephoneNumbers().next();
telephone = next1.getTelephone();
System.out.println(telephone);
}
Iterator<TelephoneParameterType> telephoneParameterTypes = next.getTelephoneParameterTypes();
TelephoneParameterType next1 = telephoneParameterTypes.next();
String type = next1.getType();
TelephoneParameterType next2 = telephoneParameterTypes.next();
String type2 = next2.getType();
System.out.println( name );
System.out.println(sEmail);
System.out.println(sNickName);
System.out.println(type);
System.out.println(type2);
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
However, there is no method called getNumber() or something. How can I get the mobile numbers and land numbers? Please help!
NOTE: I UPDATED THE CODE. In there, you can see I managed to get the phone number. But, this returns only the HOME phone and not anything else. Even the loop is not stopping. Please help!
I can see
TelephoneFeature.getTelephone()
I'd also suggest taking a look at
TelephoneFeature.getTelephoneParameterTypes()
to see the types
UPDATE
Be careful with the iterators
Each call to vcard.getTelephoneNumbers() is creating a new Iterator, which means you could end up in an infinite loop.
Iterator<TelephoneFeature> itNumbers = vcard.getTelephoneNumbers();
while (itNumbers.hasNext()) {
TelephoneFeature next1 = itNumbers.next();
String telephone = next1.getTelephone();
System.out.println(telephone);
System.out.println("types = " + next1.getExtendedTelephoneParameterSize());
Iterator<XTelephoneParameterType> itTypes = next1.getExtendedTelephoneParameterTypes();
while (itTypes.hasNext()) {
XTelephoneParameterType next = itTypes.next();
System.out.println(" - " + next.getType() + " / " + next.getDescription());
}
}
I stand corrected, the problem (isn't a bug) it's with the tester, not the API :P
If you add
Iterator<TelephoneParameterType> itNTypes = next1.getTelephoneParameterTypes();
while (itNTypes .hasNext()) {
TelephoneParameterType next = itNTypes .next();
System.out.println(" - " + next.getType() + " / " + next.getDescription());
}
to the previous loop, you should get what you're looking for
Related
Main Class
package main;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
import lib.Die;
import lib.Name;
import lib.PairOfDice;
import lib.Player;
public class PlayerAppTest {
/* Please note - when we come to mark the solution to this unit test we will change the input
* data set for the players added to the list to ensure the solution works dynamically based
* upon any given data set and is not hardcoded in any way.
*/
#Test
public void testExecute() {
ArrayList<Player> players = new ArrayList<>();
players.add(new Player(new Name("Joe", "Bloggs"), new PairOfDice()));
players.add(new Player(new Name("Fred", "Jones"), new Die()));
players.add(new Player(new Name("Nila", "Singh"), new PairOfDice(new Die(5), new Die(5))));
String result = PlayerApp.execute(players, "Cassie Downturn");
String expectedResult = "cassie, DOWNTURN\nnila, SINGH\n";
assertEquals("The string returned should match the expected result (run 1)", expectedResult, result);
/* Test with a second set of input data */
ArrayList<Player> players2 = new ArrayList<>();
players2.add(new Player(new Name("David", "Blunt"), new PairOfDice()));
players2.add(new Player(new Name("Tim", "Jonas"), new Die(5)));
players2.add(new Player(new Name("Remi", "Patel"), new Die()));
String result2 = PlayerApp.execute(players2, "Cassie Downturn");
String expectedResult2 = "cassie, DOWNTURN\ntim, JONAS\nremi, PATEL\n";
assertEquals("The string returned should match the expected result (run 2)", expectedResult2, result2);
}
}
Hello, this is the JUnit test which I have to pass, below is the code that I have written in my main package;
JUnit Test Class
package main;
import java.util.ArrayList;
import lib.Player;
public class PlayerApp {
public static String execute(ArrayList<Player> players, String fullName) {
players.get(0).setFullPlayerName(fullName);
fullName = "";
for (int i = 0; i <players.size(); i ++) {
if (players.get(i).getName().getFirstName().toLowerCase().contains("a") || players.get(i).getName().getFamilyName().toUpperCase().contains("a")) {
fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
}
System.out.println(fullName);
}
return fullName;
}
}
This is the code in my main package, I am trying to print out the names which contain a char "a" in the first name, the first name should be lowercase and the family name should be uppercase. It should print out
cassie, DOWNTURN
nila, SINGH which is the names with a new line between them, however, when i print it, it prints the following;
cassie, DOWNTURN
cassie, DOWNTURN
nila, SINGH
I am confused as to why cassie, DOWNTURN has been printed twice as i cannot find the error in my code, any help would be greatly appreciated, thank you.
You will print it even if the if doesn't match as it's outside the if-statement. Move it inside instead.
for (int i = 0; i <players.size(); i ++) {
if (players.get(i).getName().getFirstName().toLowerCase().contains("a") || players.get(i).getName().getFamilyName().toUpperCase().contains("a")) {
fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
System.out.println(fullName);
}
}
Your print statement is not conditional and will always execute, move it inside the if. You're printing twice as your are not changing the value in fullName if the if condition does not evaluate as true. Further your family name comparison will always be false as you're comparing upper and lower case.
Your code can also be tided up and made easier to read:
for(Player player : players){
if(player.getName().getFirstName()).toLowerCase().contains("a")||player.getName().getFamilyName().toUpperCase.contains("A"))){
String fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
System.out.println(fullname);
}
}
The program that I am writing is in Java. I am attempting to make my program read the file "name.txt" and store the values of the text file in an array.
So far I am using a text file that will be read in my main program, a service class called People.java which will be used as a template for my program, and my main program called Names.java which will read the text file and store its values into an array.
name.txt:
John!Doe
Jane!Doe
Mike!Smith
John!Smith
George!Smith
People.java:
public class People
{
String firstname = " ";
String lastname = " ";
public People()
{
firstname = "First Name";
lastname = "Last Name";
}
public People(String firnam, String lasnam)
{
firstname = firnam;
lastname = lasnam;
}
public String toString()
{
String str = firstname+" "+lastname;
return str;
}
}
Names.java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Names
{
public static void main(String[]args)
{
String a = " ";
String b = "empty";
String c = "empty";
int counter = 0;
People[]peoplearray=new People[5];
try
{
File names = new File("name.txt");
Scanner read = new Scanner(names);
while(read.hasNext())
{
a = read.next();
StringTokenizer token = new StringTokenizer("!", a);
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
People p = new People(b,c);
peoplearray[counter]=p;
++counter;
}
}
}
catch(IOException ioe1)
{
System.out.println("There was a problem reading the file.");
}
System.out.println(peoplearray[0]);
}
}
As I show in my program, I tried to print the value of peoplearray[0], but when I do this, my output reads: "null."
If the program were working corrrectly, the value of peoplearray[0] should be, "John Doe" as those are the appropriate values in "names.txt"
Is the value of peoplearray[0] supposed to be null?
If not, what can I do to fix this problem?
Thanks!
The order of your arguments is wrong:
StringTokenizer token = new StringTokenizer("!", a);
According to API constructor
public StringTokenizer(String str, String delim)
use
StringTokenizer token = new StringTokenizer(a,"!");
I need help from Authorized.net Java SDK experts. I am GetSettledBatchList transaction with the following code, but it gives me exceptions, I am not able to understand which Date format it accepts.
The error comes for reference:
11/05/15 00:32:56,875: INFO [pool-1-thread-1] (net.authorize.util.LogHelper:24) - Use Proxy: 'false'
Exception in thread "main" java.lang.NullPointerException
at com.auth.net.commons.authorize.net.GetSettledBatchList.main(GetSettledBatchList.java:52)
The code which I developed so far for reference: Please help me how to solve this error.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import net.authorize.Environment;
import net.authorize.api.contract.v1.GetSettledBatchListRequest;
import net.authorize.api.contract.v1.GetSettledBatchListResponse;
import net.authorize.api.contract.v1.MerchantAuthenticationType;
import net.authorize.api.contract.v1.MessageTypeEnum;
import net.authorize.api.controller.GetSettledBatchListController;
import net.authorize.api.controller.base.ApiOperationBase;
public class GetSettledBatchList {
public static final String apiLoginId= "XXXXX";
public static final String transactionKey= "XXXX";
public static void main(String[] args) throws ParseException, DatatypeConfigurationException {
GregorianCalendar gc=new GregorianCalendar();
ApiOperationBase.setEnvironment(Environment.SANDBOX);
MerchantAuthenticationType merchantAuthenticationType= new MerchantAuthenticationType() ;
merchantAuthenticationType.setName(apiLoginId);
merchantAuthenticationType.setTransactionKey(transactionKey);
ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType);
GetSettledBatchListRequest getRequest = new GetSettledBatchListRequest();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date firstSettlementDate = df.parse("2015-01-26");
gc.setTime(firstSettlementDate);
Date lastSettlementDate = df.parse("2015-05-05");
gc.setTime(lastSettlementDate);
getRequest.setFirstSettlementDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc));
getRequest.setLastSettlementDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc));
getRequest.setMerchantAuthentication(merchantAuthenticationType);
GetSettledBatchListController controller = new GetSettledBatchListController(getRequest);
controller.execute();
GetSettledBatchListResponse getResponse = new GetSettledBatchListResponse();
if (getResponse!=null) {
if (getResponse.getMessages().getResultCode() == MessageTypeEnum.OK) {
System.out.println(getResponse.getMessages().getMessage().get(0).getCode());
System.out.println(getResponse.getMessages().getMessage().get(0).getText());
}
else{
System.out.println("Failed to get settled batch list: " + getResponse.getMessages().getResultCode());
}
}
}
}
Something on line 52 is null. Try adding null checks:
if (getResponse!=null && getResponse.getMessages() != null && getResponse.getMessages().getResultCode() != null) {
if (getResponse.getMessages().getResultCode() == MessageTypeEnum.OK) {
if (getResponse.getMessages().getMessage() != null && getResponse.getMessages().getMessage().get(0) != null) {
System.out.println(getResponse.getMessages().getMessage().get(0).getCode());
System.out.println(getResponse.getMessages().getMessage().get(0).getText());
}
}
else{
System.out.println("Failed to get settled batch list: " + getResponse.getMessages().getResultCode());
}
}
Line 47 does not make sense in your code. The line
GetSettledBatchListResponse getResponse = new GetSettledBatchListResponse();
returns an empty response from the API. You do not have any line to actually extract the response from the controller.
If you look at this link in the Authorize.Net GitHub repository for the sample codes, you will notice that the above line should be replaced by
GetSettledBatchListResponse getResponse = controller.getApiResponse();
Try this and get back to us with the result.
This issue is fixed in latest version version of anet-java-sdk 1.8.6 per link https://github.com/AuthorizeNet/sdk-java/issues/61. So below code works fine. Make sure when you're using dates, FirstSettlementDate and LastSettlementDate gap should not be more that 30 days.
public class SettledTransactionDetails {
public static final String apiLoginID= "XXXXX";
public static final String transactionKey= "XXXXXX";
#SuppressWarnings("unchecked")
public static void main(String[] args) throws ParseException {
Merchant merchant = Merchant.createMerchant(Environment.SANDBOX, apiLoginID, transactionKey);
// get the list of Unsettled transactions
net.authorize.reporting.Transaction transaction =
merchant.createReportingTransaction(TransactionType.GET_SETTLED_BATCH_LIST);
ReportingDetails reportingDetails = ReportingDetails.createReportingDetails();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
reportingDetails.setBatchFirstSettlementDate(formatter.parse("16/06/2015"));
reportingDetails.setBatchLastSettlementDate(formatter.parse("15/07/2015"));
reportingDetails.setBatchIncludeStatistics(true);
transaction.setReportingDetails(reportingDetails);
Result<Transaction> result =(Result<Transaction>) merchant.postTransaction(transaction);
System.out.println("Result : " + result.getResultCode());
ArrayList<BatchDetails> batchDetailsList = result.getReportingDetails().getBatchDetailsList();
for (int i = 0; i < batchDetailsList.size(); i++) {
ArrayList<BatchStatistics> batchStatisticsList = batchDetailsList.get(i).getBatchStatisticsList();
for (int j = 0; j < batchStatisticsList.size(); j++) {
BatchStatistics batchStatistics = batchStatisticsList.get(j);
System.out.println("====================== " + j+ " start");
System.out.println("Account Type : [" + batchStatistics.getAccountType()+"]");
System.out.println("Charge Amount : [" + batchStatistics.getChargeAmount()+"]");
System.out.println("Charge BackAmount : [" + batchStatistics.getChargebackAmount()+"]");
System.out.println("Charge Charge Back Amount : [" + batchStatistics.getChargeChargebackAmount()+"]");
System.out.println("Charge Returned Items Amount [: " + batchStatistics.getChargeReturnedItemsAmount()+"]");
System.out.println("Refund Amount : [" + batchStatistics.getRefundAmount());
System.out.println("Refund Charge Back Amount : [" + batchStatistics.getRefundChargebackAmount());
System.out.println("Account Type : [" + batchStatistics.getAccountType());
System.out.println("====================== " + j+ " end");
}
}
}
}
I need to delete several test cases i have in rally. Rally website says that the only way around this problem is to communication with Rally API and write a small bulk deletion script.
E.g. i need to delete from TC100 - TC150.
Anyone can help me with this? I am using java.
Thanks.
Per Rally Rest toolkit for Java documentation there is a Delete method.
Here is a code example that queries test cases by a tag name and then bulk-deletes these test cases. Your query criteria will be different, but if you choose to identify test cases by tag, note that Tags.Name contains "tag1" returns test cases that may have more than one tag applied, and not only those that a single "tag1".
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.request.DeleteRequest;
import com.rallydev.rest.response.DeleteResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import java.net.URI;
public class GetTestCasesByTagAndBulkDelete {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123"; //use your api key
String applicationName = "Find TestCases by Tag and bulk delete";
String workspaceRef = "/workspace/12345";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
QueryRequest request = new QueryRequest("TestCase");
request.setWorkspace(workspaceRef);
request.setFetch(new Fetch(new String[] {"Name", "FormattedID", "Tags"}));
request.setLimit(1000);
request.setScopedDown(false);
request.setScopedUp(false);
request.setQueryFilter(new QueryFilter("Tags.Name", "contains", "\"tag1\""));
QueryResponse response = restApi.query(request);
System.out.println("Successful: " + response.wasSuccessful());
System.out.println("Results Size: " + response.getResults().size());
for (int i=0; i<response.getResults().size();i++){
JsonObject tcJsonObject = response.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + tcJsonObject.get("Name") + " FormattedID: " + tcJsonObject.get("FormattedID"));
int numberOfTags = tcJsonObject.getAsJsonObject("Tags").get("Count").getAsInt();
QueryRequest tagRequest = new QueryRequest(tcJsonObject.getAsJsonObject("Tags"));
tagRequest.setFetch(new Fetch("Name","FormattedID"));
//load the collection
JsonArray tags = restApi.query(tagRequest).getResults();
for (int j=0;j<numberOfTags;j++){
System.out.println("Tag Name: " + tags.get(j).getAsJsonObject().get("Name"));
}
System.out.println("deleting " + tcJsonObject.get("FormattedID")) ;
DeleteRequest deleteRequest = new DeleteRequest(tcJsonObject.get("_ref").getAsString());
DeleteResponse deleteResponse = restApi.delete(deleteRequest);
}
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}
I have the below data in a text file.
CS##NEWSLTR$$
RY##GLMALAW$$
VW##NWL$$
VW##GLS$$
IS##4$$
ST##NJ$$
ST##NY$$
SORTX##0050004018001$$
RC##18 No. 4 GLMALAW 1$$
CR##18 No. 4 M & A Law. 1$$
SO3##The M & A Lawyer$$
DL##April, 2014$$
TI##DUSTING OFF APPRAISAL RIGHTS: THE DEVELOPMENT OF A NEW INVESTMENT
STRATEGY$$
here i'm actually trying to fetch these values into a java array with the below code.
package strings;
import com.sun.org.apache.xalan.internal.xsltc.runtime.BasisLibrary;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
*
* #author u0138039
*/
public class Strings {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner inFile1 = null;
try {
inFile1 = new Scanner(new File("C:\\Users\\u0138039\\Desktop\\Adhil\\WDA.TP.GLASSER.IB.F486806.A.D140605.T.txt")).useDelimiter("$\\\\\\\\\\\\$");
} catch (FileNotFoundException ex) {
Logger.getLogger(Strings.class.getName()).log(Level.SEVERE, null, ex);
}
List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
tokens.add(inFile1.nextLine());
}
String[] tokenArray = tokens.toArray(new String[0]);
for (int i = 0; i < tokenArray.length; i++) {
String s = tokenArray[i];
System.out.println("a["+i+"]" +tokenArray[i]);
}
}
}
here my concept is that the line ends with a $$ and this is how it should be stored in an array, but when i run the above program i get the below output.
a[0]CS##NEWSLTR$$
a[1]RY##GLMALAW$$
a[2]VW##NWL$$
a[3]VW##GLS$$
a[4]IS##4$$
a[5]ST##NJ$$
a[6]ST##NY$$
a[7]SORTX##0050004018001$$
a[8]RC##18 No. 4 GLMALAW 1$$
a[9]CR##18 No. 4 M & A Law. 1$$
a[10]SO3##The M & A Lawyer$$
a[11]DL##April, 2014$$
a[12]TI##DUSTING OFF APPRAISAL RIGHTS: THE DEVELOPMENT OF A NEW INVESTMENT
a[13] STRATEGY$$
here a[12] and a[13] belong to same array number(index), but here these are divided into 2.
The expected output is as below(since the end $$ of a[12] came in a[13])
a[0]CS##NEWSLTR$$
a[1]RY##GLMALAW$$
a[2]VW##NWL$$
a[3]VW##GLS$$
a[4]IS##4$$
a[5]ST##NJ$$
a[6]ST##NY$$
a[7]SORTX##0050004018001$$
a[8]RC##18 No. 4 GLMALAW 1$$
a[9]CR##18 No. 4 M & A Law. 1$$
a[10]SO3##The M & A Lawyer$$
a[11]DL##April, 2014$$
a[12]TI##DUSTING OFF APPRAISAL RIGHTS: THE DEVELOPMENT OF A NEW INVESTMENT STRATEGY$$
please let me know where am i going wrong and how to fix it.
Thanks
Forget the useDelimiter
List<String> tokens = new ArrayList<String>();
int next = 0;
while (inFile1.hasNext()) {
String line = inFile1.nextLine();
if( next >= tokens.size() ){
tokens.add( line );
} else {
tokens.set( next, tokens.get(next) + line );
}
if( line.endsWith( "$$" ) ) next++;
}
You're issuing a inFile1.nextLine() so naturally, the strings in a[12] and a[13] would be separated.
One approach I can think of is putting the content of the file in a String object, then do a split using "\$\$" .
String s = "Hello$$World$$Sample$$";
for(String sa: s.split("\\$\\$")) {
System.out.println(sa);
}
Output:
Hello
World
Sample
But this will not include the trailing "$$" since you used it in the split. You can easily add that do the end of your string, but this is just one approach.
Hope this helps.
String partialLine = null;
while (inFile1.hasNext()) {
String line = inFile1.nextLine();
if (partialLine != null) {
line = partialLine + line;
partialLine = null;
}
if (line.endsWith("$$") {
tokens.add(line);
} else {
partialLine = line;
}
}
if (partialLine != null) {
// Probably empty line.
}
A bit of buffering: not adding a partial line (missing $$), but keeping it in partialLine.
As you see even several partial lines would work.