I have build code clone application, that using JCCD API that impelemnted ANTLR. To show the code clone, I am using a jtable. This is my screenshot Application : https://docs.google.com/file/d/0B_Rg--NnjJccMERpaTNidzR3cFE/edit?usp=sharing
Okey, from the following screenshot above, I was success to compare one file to another one file. The problem is when I am compare a file to two or more files. The tables just give me the last suspect of code clone.
But, in my netbeans output console, I was success that showed in this link : https://drive.google.com/file/d/0B_Rg--NnjJccWWdVTjdZc1R1bWc/edit?usp=sharing
How can I showed the right output console one to more files to my jTable ?
This is My code :
public static void printSimilarityGroups(final SimilarityGroupManager groupContainer) {
SimilarityGroup[] simGroups = groupContainer.getSimilarityGroups(); // output similarity groups
DefaultTableModel model = (DefaultTableModel) Main_Menu.jTable1.getModel();
model.setRowCount(0);
List<final_tugas_akhir.Report> theListData = new ArrayList<Report>();
if (null == simGroups) {
simGroups = new SimilarityGroup[0];
}
if ((null != simGroups) && (0 < simGroups.length)) {
for (int i = 0; i < simGroups.length; i++) {
final ASourceUnit[] nodes = simGroups[i].getNodes();
System.out.println("");
System.out.println("Similarity Group " + simGroups[i].getGroupId());
for (int j = 0; j < nodes.length; j++) {
final SourceUnitPosistion minPos = getFirstNodePosition((ANode) nodes[j]);
final SourceUnitPosistion maxPos = getLastNodePosition((ANode) nodes[j]);
ANode fileNode = (ANode) nodes[j];
while (fileNode.getTipe() != TipeNode.FILE.getTipe()) {
fileNode = fileNode.getParent();
}
final_tugas_akhir.Report theResult = new final_tugas_akhir.Report(); //final_tugas_akhir.Report() is a class that contain getter and setter
//Mixing the Line
StringBuilder sb = new StringBuilder();
StringBuilder append = sb.append(minPos.getBaris()).append("."); // get the row
sb.append(minPos.getKarakter()).append(" - "); //get Character
StringBuilder append1 = sb.append(maxPos.getBaris()).append(".");// get row
sb.append(maxPos.getKarakter()); get the character
theResult.setSimiliaritygroup(simGroups[i].getGroupId()); //Similiarity Group
theResult.setId(nodes[j].getId()); //setter similiarity id on token
theResult.setIndikasi(nodes[j].getText()); // setter Kind of Similairity
theResult.setFileutama(fileNode.getText()); //Files name
theResult.setLine(sb.toString());
theListData.add(theResult);
}
}
for (Report report : theListData) {
//test for the console
System.out.print(report.getSimiliaritygroup() + " ");
System.out.print(report.getId() + " ");
System.out.print(report.getIndikasi() + " ");
System.out.print(report.getFileutama() + " ");
System.out.print(report.getLine() + "\n");
//for table that failed
model.addRow(new Object[]{
report.getSimiliaritygroup(),
report.getId(),
report.getIndikasi(),
report.getFileutama(),
report.getLine()});
}
} else {
System.out.println("No similar nodes found.");
}
}
Thank you so much...
Related
My problem is in the part where I'm doing the "if/else" conditions, when I call the function that will perform the comparisons and will define if the test passed or not and will send some information, I'm receiving null.
Problems are among the asterisks. If anyone can help me
This is my code :
public static void fxSpot_GBP_JPY(TradeData data, TradeData output) throws Exception {
if (data == null) {
fail("The input data object was not correctly filled");
}
if (output == null) {
fail("The output data object was not correctly filled");
}
//Used to set the comment, the status and update to JIRA
FieldsJSON fields = new FieldsJSON();
String assertionError = "";
List<String> inputs = new ArrayList<String>();
List<String> outputs = new ArrayList<String>();
String newDate = Utils.formatTimeZoneMinute(data.getTradeDate());
String asOfTrade = Utils.formatTimeZoneMinute(data.getAsOfTradeDate());
String executionDate = Utils.formatTimeZoneMinute(output.getExecutionDateTime());
try {
//Add the data in the list
inputs.add(data.getTransactionNumber()); outputs.add(output.getBloombergId());
inputs.add(newDate); outputs.add(output.getTradeDate());
inputs.add(asOfTrade); outputs.add(executionDate);
inputs.add(data.getSettlementDate()); outputs.add(output.getValueDate());
inputs.add(data.getTradeAmount()); outputs.add(output.getAmount2());
inputs.add(data.getCustomerAccountCounterparty()); outputs.add(output.getMiPartyId());
inputs.add(data.getPrincipalLoanAmount()); outputs.add(output.getAmount());
inputs.add(data.getSecurityPrice()); outputs.add(output.getRate());
inputs.add(data.getISOCodeOf1stCurrency()); outputs.add("BRL");//output.getCurrency2()
inputs.add(data.getISOCodeOf2ndCurrency()); outputs.add(output.getCurrency1());
//Compare values
System.out.println("-------------------");
int y = 0;
int x = 0;
for(String input : inputs) {
for(String out : outputs) {
if(y == x) {
if(input.equals(out)) {
WriterCSV.setOk("Ok");
**String comment = input + " = " + out;
fields.setComment(comment);
fields.setStatus("PASS");**
System.out.println("ok - " + input + " = " + out);
}else {
WriterCSV.setOk("not Ok");
**String comment = input + " = " + out;
fields.setComment(comment);
fields.setStatus("FAIL");**
System.out.println("not Ok - " + input + " = " + out);
}
}
x = x+1; // count of the list of output
}
y = y+1; // count of the list of inputs
x = 0; // reset to 0 the count of outputs
}
// evidence with the name and value of fields compared
WriterCSV.reportSpot_CSV(data,output);
}
Here is my test:
#Test
#Tag("compare")
public void CompareSpot() throws Exception {
//Create a list to read the CSVfile
List<DTOTradeData> dto;
//Used to get the TradeData of list dto.
DTOTradeData dtd = new DTOTradeData();
// Read a csvFile and return a list with the values to new xml
dto = CSVReader.readCSV("spot.csv");
//The xpath of xml
FileDriverSpot spot = new FileDriverSpot();
FileDriver output = new FileDriverSpotOutput();
FieldsJSON fields = new FieldsJSON();
//new xml = dataInput and the outputFile = dataOutput
TradeData dataInput = new TradeData();
TradeData dataOutput = new TradeData();
for (int i = 0; i < dto.size(); i++) {
dtd = dto.get(i); // get TradeData
dtd.getTradeData().setDriver(spot); // set the driver
if (fileExist(Setup.xmlPath + dtd.getInputFile() + ".xml")) {
dataInput = Reader.read(spot, Setup.xmlPath + dtd.getInputFile() + ".xml");
dataOutput = Reader.read(output, Setup.spotPath + dtd.getOutputFile());
try {
// make the comparison
**FunctionalTest.fxSpot_GBP_JPY(dataInput, dataOutput);**
}
catch(AssertionError e) {
String comment = e.toString();
fields.setComment(comment);
}
} else {
fail("The file: " + dtd.getTemplateFile()
+ " needs to go through the writing process before being compared.");
}
//Convert the file to base64
String inputData = UpdateTestStatus.convertToBase64(Setup.xmlPath + dtd.getInputFile() + ".xml");
String outputData = UpdateTestStatus.convertToBase64(Setup.spotPath + dtd.getOutputFile());
String evidenceCompared = UpdateTestStatus.convertToBase64(Setup.reportPath+"ReportSpot.csv");
System.out.println(UpdateTestStatus.updateTestRun(**fields.getStatus(),fields.getComment()**,
inputData,dtd.getInputFile()+ ".xml", //data of the XML and the name of the file
outputData,dtd.getOutputFile(),
evidenceCompared,"ReportSpot.csv",
Setup.testExec, dtd.getJiraId()).asString()); // ID testExecution and ID of
}
}
The test and the code under test each create a separate instance of FieldsJSON. Data set in one instance will not be visible in the other (unless the data is declared static, in which case there's no need to create instances).
You can fix this by using a single instance, either passed to the fxSpot_GBP_JPY method from the test, or returned from that method to the test.
We need to get below format
Redemption Reference Code|Status|Delivery company|Shipper Tracking Number|Comments
2006995040|Shipped|USPS|ABCD12345|Order SHIPPED
2006995042|Cancelled|||INVALID Address
2006995048|Ordered|USPS|ABCD12345|Order SHIPPED
I am using below code
private void accumulateOrdersFromPlacement(){
int count = 0;
for (int i = 0; i < orderIds.size(); i++) {
if (count == 0) {
outPutLineData.add(orderIds.get(i));
outPutLineData.add("Cancelled");
outPutLineData.add("");
outPutLineData.add(" ");
outPutLineData.add(" ");
cancelledStatusLineItems.add(orderIds.get(i));
count++;
} else if (count == 1) {
outPutLineData.add(orderIds.get(i));
outPutLineData.add("Shipped");
if (outPutLineData.contains("Shipped")) {
outPutLineData.add("USPS");
outPutLineData.add("order SHIPPED");
outPutLineData.add("");
}
shippedStatusLineItems.add(orderIds.get(i));
count++;
} else if (count == 2) {
outPutLineData.add(orderIds.get(i));
outPutLineData.add("No Longer Available");
outPutLineData.add("");
outPutLineData.add(" ");
outPutLineData.add(" ");
count++;
nlaStatusLineItems.add(orderIds.get(i));
} else if (count == 3) {
outPutLineData.add(orderIds.get(i));
outPutLineData.add("Ordered");
outPutLineData.add("");
outPutLineData.add(" ");
outPutLineData.add(" ");
orderedStatusLineItems.add(orderIds.get(i));
count = 0;
}
}
I am using below code for file creation. This is the detailed coding . This has more readability to understand code.Here i got confused about the code.We are taking order id count andbased on that this code is working.
private File createFile(final File directory) {
FileWriter fw = null;
File tempFile = null;
try {
directory.mkdir();
tempFile = new File(".//FidelityFulfillment//" + generateFileName(countyThreeLetterCode, "FidelityFulfillment", ".csv", date));
logReport(GenericConstants.NEW_LINE + "Fulfillment file creating:", tempFile.getName());
fw = new FileWriter(tempFile, true);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile, true))) {
writer.write(generateHeaderLine());
writer.newLine();
for (int y = 1; y < outPutLineData.size(); y++) {
if (y % 5 < 4) {
writer.write(outPutLineData.get(y-1) + fieldSeperator);
logReport(outPutLineData.get(y - 1) + fieldSeperator);
}
else {
writer.write(outPutLineData.get(y-1));
logReport(outPutLineData.get(y));
}
if (y % 5 == 0) {
writer.newLine();
logReport("newline");
}
}
writer.close();
} catch (final IOException e) {
e.printStackTrace();
final String err = "Unable to write file due to : " + e;
logReport(GenericConstants.NEW_LINE + "Unable to create temp local File");
} finally {
fw.close();
}
}catch (Exception e){
e.printStackTrace();
}
return tempFile;
}
Getting response as
Redemption Reference Code|Status|Delivery company|ShipperTrackingNumber|Comments
2006964032|Cancelled|| |
newline
2006964034|Shipped|USPS||
newline
2006964036|No Longer Available||
Last line one pipline is getting missing
First, you loop in a strange way :
for (int y = 1; y < outPutLineData.size(); y++) {
In general, we start at 0.
But you tried to correct that with the condition :
if (y % 5 < 4) {
//System.out.print("size:"+y);
writer.write(outPutLineData.get(y-1) + fieldSeperator);
logReport(outPutLineData.get(y - 1) + fieldSeperator);
}
else {
//System.out.print("size noseperator:"+y);
writer.write(outPutLineData.get(y-1));
logReport(outPutLineData.get(y));
}
Instead, simply use an iterator to read the values, then on read the correct amount of values :
Iterator<String> it = outPutLineData.iterator();
while(it.hasNext()){
for (int j = 0; j < columnCount; ++j) {
writer.write(it.next());
if( j < columnCount - 1)
writer.write(fieldSeperator);
}
writer.newLine();
}
Example with a StringBuilder to print in console :
int columnCount = 2;
String fieldSeperator = "|";
List<String> list = Arrays.asList("foo", "1", "bar", "2");
Iterator<String> it = list.iterator();
//Safe guard !
if(list.size() % columnCount != 0)
throw new RuntimeException("The list does have the correct amount of data");
while(it.hasNext()){
for (int j = 0; j < columnCount; ++j) {
sb.append( it.next() );
if( j < columnCount - 1)
sb.append(fieldSeperator );
}
System.out.println(sb.toString());
sb.setLength(0);
}
foo|1
bar|2
Use a POJO
You are using a List<String> to hold the values, you need to know how many column you need to read to get the value. Instead, use a POJO :
public class Redemption{
String redemptionReference;
String code;
String status;
String deliveryCompany;
String shipperTrackingNumber;
String comments;
}
And create the instance in your first loop :
List<Redemption> list...
That way, you just need to iterate each instance to build your row :
for(Redemption r: list){
writer.write(r.getRedemptionReference() + fieldSeperator);
...
writer.write(r.getComments());
writer.newLine();
}
Of course, you need to use getter and setter but this is just to show what you should do.
CSV API
Big warning, writing your own CSV writer is dangerous. If you have a comment like "This is a | character". You will end up with a line like :
2006995040|Shipped|USPS|This is a | character|Order SHIPPED
That one column to many... because you should have
2006995040|Shipped|USPS|"This is a | character"|Order SHIPPED
But you are not checking that case, and this is only one case. Using a CSV API is safer and simpler.
See Any good library to read and write csv files?
I have a single CSV file which contains many lines.
1shelf CSV file sample content:
#ManagementNode,SHELF-INFORMATION,NE_ID,RACK_ID,SHLEF_ID,STATUS,SHELF_TYPE,MAX_SLOT_NUMBER
ManagementNode,SHELF-INFORMATION,0005,0,0,,,13
#ManagementNode,BOARD-INFORMATION,NE_ID,RACK_ID,SHELF_ID,SLOT_ID,BOARD_NAME,ACTIVE_MODE,ADMIN_STATE,OPER_STATE,VERSION,SERIAL_NO,MANUFACTURER,MANUFACTURE_DATE
ManagementNode,BOARD-INFORMATION,0005,0,0,6,LEMA0,ACTIVE,UNLOCK,ENABLE,,S61F91571,XYZ,2014-09-03
2shelf CSV file sample content:
#ManagementNode,SHELF-INFORMATION,NE_ID,RACK_ID,SHLEF_ID,STATUS,SHELF_TYPE,MAX_SLOT_NUMBER
ManagementNode,SHELF-INFORMATION,0001,0,0,,,13
#ManagementNode,SHELF-INFORMATION,NE_ID,RACK_ID,SHLEF_ID,STATUS,SHELF_TYPE,MAX_SLOT_NUMBER
ManagementNode,SHELF-INFORMATION,0001,0,1,,,13
Please note that in the 2shelf file the header value of line 1 and line 3 is the same and also line 2 5th row value is 0 and line 5 5th row value is 1, this means it's a 2shelf file. The same is not true for 1shelf file.
I am new to Java, able to print required lines but dont know how to implement the compare logic to figure out 1shelf or 2shelf file.
BufferedReader in = new BufferedReader (new FileReader("C:\\Files\\1_2_Shelf\\Test.csv"));
String info = "";
int startLine = 4;
int endLine = 7;
for (int i = 0; i < startLine; i++) {
info = in.readLine();
}
for (int i = startLine; i < endLine + 1; i++) {
info = in.readLine();
System.out.println(info);
}
in.close();
}
Add the import shown below to the top of your class file.
Then use info.split(",") to break up the CSV string into fields in an array.
Then you will grab the 5th field of the array using field index = 4 (array element indexes starts at zero).
Sample code below, inserted into your original code:
import java.util.regex.Pattern; // NEW import to add at top of your file
...
// Some constants for identifying shelves
final int FIELD_SHELF_ID = 4;
final String SHELF1 = "0";
final String SHELF2 = "1";
BufferedReader in =
new BufferedReader (new FileReader("C:\\Files\\1_2_Shelf\\Test.csv"));
String info = "";
int startLine = 4;
int endLine = 7;
for (int i = 0; i < startLine; i++) {
info = in.readLine();
}
for (int i = startLine; i < endLine + 1; i++) {
info = in.readLine();
System.out.println(info);
String infoFields[] = info.split(",");
System.out.println("infoFields[FIELD_SHELF_ID] =
" + infoFields[FIELD_SHELF_ID]);
switch(infoFields[FIELD_SHELF_ID]) {
case SHELF1:
System.out.println("Found 1SHELF row"); break;
case SHELF2:
System.out.println("Found 2SHELF row"); break;
default:
System.out.println("Unknown shelf-type row"); break;
}
}
in.close();
If you are using an older version of Java, instead of the switch statement you can use if/else if/else as follows:
if (infoFields[FIELD_SHELF_ID].equals(SHELF1)) {
System.out.println("Found 1SHELF row");
}
else if (infoFields[FIELD_SHELF_ID].equals(SHELF2)) {
System.out.println("Found 2SHELF row");
}
else {
System.out.println("Unknown shelf-type row");
}
I have a text editor where user can put text like this:
[[PAYMENTS_N]] You have to pay [[amount]]$ before [[date]].[[/PAYMENTS_N]]
[[PAYMENTS_Z]] You didn't pay [[debt]]$ on time: [[ddate]].[[/PAYMENTS_Z]]
And there are XML files that look like this:
<DATA_NZ><USER><ID>12345</ID><COMP_NZ><COMP>
<STATUS>Z</STATUS>
<AMOUNT_NZ>128.01</AMOUNT_NZ>
<DATE_NZ>28.05.2015</DATE_NZ>
<STATUS>N</STATUS>
<AMOUNT_NZ>12.32</AMOUNT_NZ>
<DATE_NZ>21.09.2015</DATE_NZ>
<STATUS>N</STATUS>
<AMOUNT_NZ>12.32</AMOUNT_NZ>
<DATE_NZ>20.10.2015</DATE_NZ>
</COMP></COMP_NZ></USER></DATA_NZ>
Now I want to change the text from editor into something like this:
Remember about your next payments:
You have to pay 12.32$ before 21.09.2015.
You have to pay 12.32$ before 20.10.2015.
You didn't pay 128.01$ on time: 28.05.2015.
And I have this code:
public void parseTags(String content) {
String nOpenTag, nCloseTag;
String zOpenTag, zCloseTag;
String dnTag, knTag, dzTag, kzTag;
nOpenTag = "[[PAYMENTS_N]]";
nCloseTag = "[[/PAYMENTS_N]]";
zOpenTag = "[[PAYMENTS_Z]]";
zCloseTag = "[[/PAYMENTS_Z]]";
dnTag = "[[amount]]";
knTag = "[[date]]";
dzTag = "[[debt]]";
kzTag = "[[ddate]]";
String textToExtract = "";
String textToExtract = "";
String textToReplace = "";
String parsedContent = content;//; = content;
if (content.contains(nOpenTag) || content.contains(zOpenTag)) {
for (int i = 0; i < getXMLContainer("SZUK_XM4.XML").getUsers().size(); i++) {
if (getXMLContainer("SZUK_XM4.XML").getUsers().get(i) != null) { //
contact = consentService.findByContactTypeAndIdNumber(ContactType.EMAIL, getXMLContainer("SZUK_XM4.XML").getUsers().get(i).getIdNumber());
payments = getXMLContainer("SZUK_XM4.XML").getUsers().get(i).getPaymentContainer().getPayments();
if (contact.size() > 0) {
StringBuilder strB = new StringBuilder();
StringBuilder strB2 = new StringBuilder();
String textToReplace;
for (int c = 0; c < contact.size(); c++) {
strB.setLength(0);
for (int p = 0; p < payments.size(); p++) {
if (payments.get(p).getStatus().contains("N")) {
textToExtract = content.substring(content.indexOf(nOpenTag) + nOpenTag.length(), content.indexOf(nCloseTag));
textToReplace = textToExtract.replace(dnTag, "Day " + payments.get(p).getPaymentDate());
textToReplace = textToReplace.replace(knTag, "Amount " + payments.get(p).getPaymentAmount());
strB.append(textToReplace);
parsedContent = content.replace(textToExtract, strB.toString());
}
if (payments.get(p).getStatus().contains("Z")) {
textToExtract = parsedContent.substring(parsedContent.indexOf(zOpenTag) + zOpenTag.length(), parsedContent.indexOf(zCloseTag));
textToReplace = textToExtract.replace(dzTag, "Day " + payments.get(p).getPaymentDate());
textToReplace = textToReplace.replace(kzTag, "Amount " + payments.get(p).getPaymentAmount());
strB2.append(textToReplace);
parsedContent = parsedContent.replace(textToExtract, strB2.toString());
}
}
mailService.sendTemplateMail(contact.get(c).getContact(), parsedContent);
}
}
}
}
}
}
This code is supposed to find in the database user with given ID from XML.
If user exists then it reads all the data between and replaces [[TAGS]] from the text editor. After everything's done, it should send an email with replaced text.
The problem is that the text it sends isn't correctly replaced. It gives
Remember about your next payments: You have to pay 12.32$ before
21.09.2015. You have to pay 12.32$ before 20.10.2015.
You didn't pay [[debt]]$ on time: [[ddate]].
See the difference in the last line?
I'm using JAXB to read XML, if it matters.
Hope you can help me! Thanks.
replace:
parsedContent = content.replace(textToExtract, strB.toString());
with:
parsedContent = parsedContent.replace(textToExtract, strB.toString());
I am reading data from a txt file. I want to create new objects from every ten lines and "." indicates that the current object doesn't have any more data lines (I work with two types of object("Nemfuggetlen" and "fuggetlen"), "fuggetlen" has 9 and "Nemfuggetlen" has 7 lines, "." separates their data lines).
The problem is: when I read two "Nemfuggetlen" objects in a row, it works fine, but if I read "fuggetlen" after "Nemfuggetlen" it makes "-------" to the next object first data lines, when it shouldn't. For "Nemfuggetlen" object it should fill the last 3 lines of "adatok" string array with "-------" and step to the next object.
int sorokszama = 0;
input.mark(300);
while((s = input.readLine()) !=null){
sorokszama++;
System.out.println("Sorok szama : " + sorokszama);
input.reset();
for(int h = 0; h < sorokszama/10; h++){
for(int i = 0;(s = input.readLine()) !=null; i++) {
if(i < 10){
if(!(".".equals(s))) {
adatok[i] = s;
System.out.println(adatok[i]);
}
else {
adatok[i] = "-------";
System.out.println(adatok[i]);
break;
}
}
}
if("Ferfi".equals(adatok[2])){
nem = true;
}
else {
nem = false;
}
if("Van".equals(adatok[4])){
tamogato = true;
}
else{
tamogato = false;
}
if("-------".equals(adatok[7])){ //A kepviselo nem fuggetlen
k = new Nemfuggetlen(adatok[0], Integer.parseInt(adatok[1]), nem, adatok[4], new Kerulet (Integer.parseInt(adatok[5])), adatok[6]);
}
if("-------".equals(adatok[9])){ // A kepviselo fuggetlen
k = new Fuggetlen(adatok[0], Integer.parseInt(adatok[1]), nem, adatok[4], new Kerulet (Integer.parseInt(adatok[5])),tamogato, adatok[7], Integer.parseInt(adatok[8]));
}
kepviselok.add(k);
//System.out.println(kepviselok.get(0));
}
System.out.println("Kepviselok szama : " + sorokszama/10);
for(int i = 0; i < kepviselok.size(); i++) {
System.out.println((i+1) + ". tag : " + kepviselok.get(i));
}
input.close();