What is Java result:3? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm currently learning programming (java) and I've been using a program that runs on command prompt but as an exercise, I've been asked to run it on netbeans and to find out how it can work on it. When I run the program this is the output that I got.
run:
Please specify a path to a pricing catalogue file
Java Result: 3
BUILD SUCCESSFUL (total time: 0 seconds)
I've spent several hours on this issue but I was not able to sort it out. Can anybody help me with it please.
Here is the codes.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class Grocery {
private static Catalogue pricingCatalogue;
private static HashMap<String, Double> inputItemList = new HashMap<String, Double>();
private static ArrayList<PurchasedProduct> purchasedItemList;
public static void main(String[] args) {
if( args.length != 1 )
{
System.err.println( "" );
System.exit( 3 );
}
generateCatalogue( args[0] );
gatherUserInput();
rateItem();
printItemizedBill();
}
private static void generateCatalogue( String inputFile ) {
try {
List<String> lines = Files.readAllLines(
Paths.get(inputFile),
Charset.defaultCharset() );
pricingCatalogue = new Catalogue();
Boolean compareIgnoreCase = false;
for (String line : lines) {
StringTokenizer token = new StringTokenizer( line, "|" );
String productName = (String)token.nextElement();
String rateName = (String)token.nextElement();
String rateDescr = (String)token.nextElement();
Double effectiveQuantity = new Double( (String)token.nextElement() );
Double effectivePrice;
String tierPrice;
Rate newRate;
Product newProduct;
if( effectiveQuantity == -1 )
{
tierPrice = (String)token.nextElement();
newRate = new Rate( rateName, rateDescr, tierPrice );
}
else
{
effectivePrice = new Double( (String)token.nextElement() );
newRate = new Rate( rateName, rateDescr, effectiveQuantity, effectivePrice );
}
if( true == pricingCatalogue.productIsInCatalogue( productName, compareIgnoreCase ) )
{
pricingCatalogue.addRateToExistingProduct( productName, newRate );
}
else
{
newProduct = new Product( productName );
newProduct.addRate( newRate );
pricingCatalogue.addProduct( newProduct );
}
} // end reading input file
}
catch (IOException e) {
e.printStackTrace();
}
//pricingCatalogue.printCatalogue();
System.out.println( "Price catalogue loaded sucessfully from [" + inputFile + "]\n" );
}
private static void gatherUserInput()
{
BufferedReader br = new BufferedReader(new InputStreamReader( System.in ) );
String inStr = new String();
String magicWord = "CHECK OUT";
Boolean readyToCheckOut = false;
Boolean compareIgnoreCase = false;
StringTokenizer item_tok = null;
String tok = null;
String itemName = new String();
Double itemQuantity = new Double( 0 );
inputItemList.clear();
System.out.println( "Please enter an item with quantity in a format like '2 apple'" );
System.out.println( "When you are done entering item(s), type 'CHECK OUT' to get an itemized bill" );
while( false == readyToCheckOut )
{
System.out.print( ">> ");
try {
inStr = br.readLine();
}catch( IOException ioe ) {
System.err.println("Failed to read line item");
}
item_tok = new StringTokenizer( inStr );
while( false == inStr.equals( magicWord )
&&
true == item_tok.hasMoreTokens() )
{
try
{
tok = item_tok.nextElement().toString();
itemQuantity = new Double( tok );
tok = item_tok.nextElement().toString();
}
catch( NumberFormatException nfe )
{
System.err.println( "[" + tok + "] is not something I recognize. Try something like '2 apple'" );
break;
}
catch( Exception e )
{
System.err.println( "Oops I did not understand that. Try something like '2 apple'" );
break;
}
itemName = tok;
//System.out.println( "--- ITEM [" + itemName + "] QUANTITY [" + ItemQuantity + "]" );
if( false == pricingCatalogue.productIsInCatalogue( itemName, compareIgnoreCase ) )
{
System.err.println( "Item [" + itemName + "] does not exist in the catalogue" );
continue;
}
if( true == inputItemList.containsKey( itemName ) ) {
itemQuantity = itemQuantity + inputItemList.get( itemName );
inputItemList.remove( itemName );
inputItemList.put( itemName, itemQuantity );
}
else {
inputItemList.put( itemName, itemQuantity );
}
}
if( true == inStr.equals( magicWord ) ) {
readyToCheckOut = true;
}
}
//System.out.println( "inputItemList [" + inputItemList + "]" );
}
private static void rateItem()
{
purchasedItemList = new ArrayList<PurchasedProduct>();
Product aProduct;
Rate bestRate;
PurchasedProduct pp;
double purchasedQuantity = 0;
for( Map.Entry<String, Double> entry : inputItemList.entrySet() )
{
String prodName = entry.getKey();
Double prodQuantity = entry.getValue();
aProduct = pricingCatalogue.getProduct( prodName );
bestRate = aProduct.getBestRate( prodQuantity );
purchasedQuantity = bestRate.getEffectiveQuantity();
pp = new PurchasedProduct( prodName, purchasedQuantity, bestRate );
purchasedItemList.add( pp );
prodQuantity = prodQuantity - purchasedQuantity;
/*
* Keep finding the best rate for the same product until we
* have filled the quantity
*/
while( prodQuantity > 0 )
{
bestRate = aProduct.getBestRate( prodQuantity );
purchasedQuantity = bestRate.getEffectiveQuantity();
pp = new PurchasedProduct( prodName, purchasedQuantity, bestRate );
purchasedItemList.add( pp );
prodQuantity = prodQuantity - purchasedQuantity;
}
}
}
private static void printItemizedBill()
{
PurchasedProduct pp = null;
Double totalDue = new Double( 0 );
Double lineTotal = new Double( 0 );
System.out.println( "\nHere is your invoice:" );
Iterator ite = purchasedItemList.iterator();
while( ite.hasNext() )
{
pp = (PurchasedProduct)ite.next();
lineTotal = pp.getPurhcasedCost();
System.out.format( "%10s%20s%10.2f\n", pp.getPurchasedProductName(), pp.getPurchasedRateDescr(), lineTotal );
totalDue += lineTotal;
}
System.out.format( "\n%10s%20s$%9.2f\n", "TOTAL DUE", "", totalDue );
}
}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class Catalogue
{
private ArrayList<Product> productList;
Catalogue()
{
this.productList = new ArrayList<Product>();
}
/*
* Returns a boolean if a product exists in the catalogue. Use the second
* argument to set whether the comparsion should take case-sensitivity into accoun
*
*/
public boolean productIsInCatalogue( String inProdName, Boolean compareIgnoreCase )
{
HashSet<String> currentProductSet = new HashSet<String>();
/*
* Get list of pricing product names
*/
Iterator ite = this.productList.iterator();
while( ite.hasNext() )
{
if( true == compareIgnoreCase )
{
currentProductSet.add( ( (Product)ite.next() ).getProductName().toUpperCase() );
}
else
{
currentProductSet.add( ( (Product)ite.next() ).getProductName() );
}
}
if( true == compareIgnoreCase )
{
return currentProductSet.contains( inProdName.toUpperCase() );
}
else
{
return currentProductSet.contains( inProdName );
}
}
public void addProduct( Product inProduct )
{
this.productList.add( inProduct );
}
public void addRateToExistingProduct( String inExistingProdName, Rate inRate )
{
Iterator ite = this.productList.iterator();
while( ite.hasNext() )
{
Product currentProd = (Product)ite.next();
String currentProdName = currentProd.getProductName();
if( 0 == currentProdName.compareTo( inExistingProdName ) )
{
currentProd.addRate( inRate );
break;
}
}
}
public Product getProduct( String inExistingProdName )
{
Product foundProduct = null;
Iterator ite = this.productList.iterator();
while( ite.hasNext() )
{
Product aProduct = (Product)ite.next();
if( true == aProduct.getProductName().equals( inExistingProdName ) )
{
foundProduct = aProduct;
break;
}
}
return foundProduct;
}
public void printCatalogue()
{
Iterator ite = this.productList.iterator();
while( ite.hasNext() )
{
( (Product)ite.next() ).printProduct();
}
}
}
import java.util.HashSet;
import java.util.Iterator;
public class Product
{
private String productName;
private HashSet <Rate> productRate;
Product()
{
this( "N/A" );
}
Product( String inProductName )
{
this.productName = inProductName;
this.productRate = new HashSet <Rate>();
}
/*
* Add a rate to this product
*/
public void addRate( Rate inRate )
{
this.productRate.add( inRate );
}
public void printProduct()
{
System.out.println( "*** PRODUCT NAME [" + this.productName + "] ***\n" );
if( this.productRate.size() > 0 )
{
Iterator ite = this.productRate.iterator();
while( ite.hasNext() )
{
((Rate)ite.next()).printRate();
}
}
else
{
System.out.println( "This product does not have rates defined");
}
System.out.println( "" );
}
public String getProductName()
{
return this.productName;
}
public Rate getBestRate( Double inQuantity )
{
Rate lowestRate = null;
HashSet <Rate> applicableRate = new HashSet <Rate>();
Iterator ite = this.productRate.iterator();
while( ite.hasNext() )
{
Rate aRate = (Rate)ite.next();
if( inQuantity >= aRate.getEffectiveQuantity() )
{
applicableRate.add( aRate );
}
}
/*
* Amongst the available rates, pick the rate with
* the lowest cost per unit
*/
ite = applicableRate.iterator();
while( ite.hasNext() )
{
Rate appRate = (Rate)ite.next();
if( null == lowestRate )
{
/*
* Handle first time entering the loop
*/
lowestRate = appRate;
}
if( lowestRate.getCostPerUnit() > appRate.getCostPerUnit() )
{
lowestRate = appRate;
}
}
return lowestRate;
}
}
import java.math.BigDecimal;
import java.math.RoundingMode;
public class PurchasedProduct
{
private String purchasedProdName;
private double purchasedQuantity;
private Rate purchasedRate;
private double purchasedCost;
PurchasedProduct( String inProdName, double inQuantity, Rate inRate )
{
//this.purchasedProdName = Character.toUpperCase( inProdName.charAt(0) ) + inProdName.substring( 1 );
this.purchasedProdName = inProdName;
this.purchasedQuantity = inQuantity;
this.purchasedRate = inRate;
this.purchasedCost = this.getCost();
}
public String getPurchasedProductName()
{
return this.purchasedProdName;
}
public String getPurchasedRateDescr()
{
return this.purchasedRate.getRateDescr();
}
public double getPurhcasedCost()
{
return this.purchasedCost;
}
private double getCost()
{
double lineCost = 0;
if( false == this.purchasedRate.isTiered() )
{
lineCost = this.purchasedRate.getEffectivePrice();
}
else
{
lineCost = this.purchasedRate.getTierPrice( new Double( this.purchasedQuantity ) );
}
return round( lineCost, 2 );
}
private double round( double value, int places )
{
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
/*
* Rate class represents the detail on how to rate a specific product
* A product may have many rates
*/
public class Rate
{
private String rateName;
private String rateDescr; // bill invoice display
private double effectiveQuantity; // the total quantity applicable to take advantage of this rate
private double effectivePrice; // the total price applicable
private double costPerUnit; // average cost per unit
private ArrayList<Map> tiers; // ONLY applicable if this is tierd pricing
Rate()
{
this( "N/A", "N/A", 0, 0 );
}
/*
* Non-tier rate constructor
*/
Rate( String inRateName, String inRateDesc, double inEffQ, double inEffPr )
{
this.rateName = inRateName;
this.rateDescr = inRateDesc;
this.effectiveQuantity = inEffQ;
this.effectivePrice = inEffPr;
this.tiers = new ArrayList<Map>();
this.costPerUnit = this.getCostPerUnit();
}
/*
* Tier rate constructor
*/
Rate( String inRateName, String inRateDesc, String tier_val )
{
this.rateName = inRateName;
this.rateDescr = inRateDesc;
this.effectiveQuantity = -1; // this is calculated later in getCostPerUnit
this.effectivePrice = -1;
this.tiers = new ArrayList<Map>();
/*
* Example tier_val "1-1,0.50,1;2-2,0.50,0.50"
* Each tier is separated by ';'
* A token within a tier is operated by ','
*/
StringTokenizer more_tiers = new StringTokenizer( tier_val, ";" );
while( more_tiers.hasMoreTokens() )
{
StringTokenizer tier_detail = new StringTokenizer( (String)more_tiers.nextElement(), "," );
Map<String, Double> tier_map = new HashMap<String, Double>();
/*
* First token is the min to max quantity e.g. 1-1 or 1-5
*/
String[] minMaxVal = tier_detail.nextElement().toString().split("-");
tier_map.put( "MIN", new Double( minMaxVal[0] ) );
tier_map.put( "MAX", new Double( minMaxVal[1] ) );
/*
* Second token is the quantity price per unit so 1.50 mean charge each unit for 1.50
*/
tier_map.put( "PRICE", new Double( (String)tier_detail.nextElement() ) );
/*
* Third token is the discount scale, e.g 1 means 100% no discount and 0.5 means 50% discount
*/
tier_map.put( "SCALE", new Double( (String)tier_detail.nextElement() ) );
tiers.add( tier_map );
}
this.costPerUnit = this.getCostPerUnit();
}
public String getRateDescr()
{
return this.rateDescr;
}
public double getEffectiveQuantity()
{
return this.effectiveQuantity;
}
public double getEffectivePrice()
{
return this.effectivePrice;
}
public Boolean isTiered()
{
return ( this.effectivePrice == -1 );
}
/*
* Calculate the total cost with the input quantity
*/
public double getTierPrice( double inQuantity )
{
Iterator ite = this.tiers.iterator();
Double min = new Double( 0 );
Double max = new Double( 0 );
Double price = new Double( 0 );
Double scale = new Double( 0 );
Double total_cost = new Double( 0 );
Double total_quan = new Double( 0 );
Double tierMaxQ = new Double( 0 );
Double toRateQuan = new Double( inQuantity );
/*
* Step through each tier
*/
while( ite.hasNext() )
{
Map tier_map = (Map)ite.next();
min = (Double)tier_map.get( "MIN" );
max = (Double)tier_map.get( "MAX" );
price = (Double)tier_map.get( "PRICE" );
scale = (Double)tier_map.get( "SCALE" );
/*
* Get the tier applicable units
*/
tierMaxQ = max - min + 1;
if( 0 >= toRateQuan )
{
break;
}
else if( toRateQuan >= tierMaxQ )
{
/*
* The incoming to-to-rated quantity is greater than
* the tier total units. Rate it with the
* maximum units in this tier
*/
total_cost = total_cost + ( tierMaxQ * price * scale );
toRateQuan = toRateQuan - tierMaxQ;
continue;
}
else
{
/*
* The incoming to-be-rated quantity is less than
* the tier total units. Rate it with the to-be-rated
* quantity
*/
total_cost = total_cost + ( toRateQuan * price * scale );
break;
}
}
return total_cost;
}
/*
* Calculate the 'average' cost per unit
*
* For a non-tiered rate, the average cost is price over quantity
*
* For a tiered rate, we calculate each tier cost, add them up and
* divide by the total quantity to get the average cost
*
*/
public double getCostPerUnit()
{
if( false == this.isTiered() )
{
/*
* Simple pricing; individual or bulk
*/
return ( this.effectivePrice / this.effectiveQuantity );
}
else
{
/*
* Tier pricing. Calculate the total cost then divide by the quantity to
* get the average cost
*/
Iterator ite = this.tiers.iterator();
Double min = new Double( 0 );
Double max = new Double( 0 );
Double price = new Double( 0 );
Double scale = new Double( 0 );
Double total_cost = new Double( 0 );
Double total_quan = new Double( 0 );
Double costPerUnit = new Double( 0 );
while( ite.hasNext() )
{
Map tier_map = (Map)ite.next();
min = (Double)tier_map.get( "MIN" );
max = (Double)tier_map.get( "MAX" );
price = (Double)tier_map.get( "PRICE" );
scale = (Double)tier_map.get( "SCALE" );
if( 0 >= ( max - min + 1 ) )
{
break;
}
total_quan = total_quan + ( max - min + 1 );
total_cost = total_cost + ( ( max - min + 1 ) * price * scale );
}
this.effectiveQuantity = total_quan;
costPerUnit = total_cost / total_quan;
return costPerUnit;
}
}
/*
* DEBUG
*/
public void printRate()
{
System.out.println( "\tRATE NAME [" + this.rateName + "]" );
System.out.println( "\tRATE DESC [" + this.rateDescr + "]" );
System.out.println( "\tQUANTITY [" + this.effectiveQuantity + "]" );
System.out.println( "\tCOST PER UNIT [" + this.costPerUnit + "]" );
if( false == this.isTiered() )
{
System.out.println( "\tPRICE [" + this.effectivePrice + "]" );
}
else
{
int num_tiers = this.tiers.size();
for( int i = 0; i < num_tiers; ++i )
{
System.out.println( "\t--- TIER [" + ( i + 1 ) + "]" );
System.out.println( "\t\t --- MIN [" + this.tiers.get( i ).get( "MIN") + "]" );
System.out.println( "\t\t --- MAX [" + this.tiers.get( i ).get( "MAX") + "]" );
System.out.println( "\t\t --- PRICE [" + this.tiers.get( i ).get( "PRICE") + "]" );
System.out.println( "\t\t --- SCALE [" + this.tiers.get( i ).get( "SCALE") + "]" );
}
}
System.out.println( "\n\n");
}
}

This
System.exit( 3 );
Causes your process to return (in Java parlance it exits) with a value to the operating system. It's equivalent to the int returned by main in c and c++. On unix style systems you can access the return value with
echo $?
It looks like you are supposed to call this program with a file-path to some catalogue as the first argument (args[0]), otherwise it exits.

Related

Java Map with ArrayList weirdness

I need another pair of eyes, because I am missing something. This is my code:
...
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.*;
import java.nio.file.*;
public class TestMap {
private Map<String, ArrayList<String>> validCommands = new HashMap<String, ArrayList<String>>();
public TestMap( ) throws Exception {
getCommands();
}
private void getCommands() throws Exception {
Map<String,ArrayList<String>> dataMap = new HashMap<>();
String nameFile = "." + File.separator + "TestMap.txt";
FileInputStream fis = new FileInputStream( nameFile );
Scanner input = new Scanner( fis );
ArrayList<String> sub = new ArrayList<>();
while(input.hasNext()) {
String[] tt = {""};
tt[0] = input.nextLine().replace( " ", "" ).toUpperCase();
// Debug next 1 line
System.out.println( "\nRead: " + tt[0] );
CharSequence divider = ",";
sub.clear();
if( tt[0].contains( divider ) ) {
tt = tt[0].split( ",", 2 );
// Debug next 2 lines
System.out.print( "Split to " );
for( int i = 0; i<tt.length; i++ ) System.out.print( tt[i] + "/" );
if( tt.length > 1 ) {
for( int i = 1; i<tt.length; i++ ) {
sub.add( tt[i] );
}
}
}
// Debug next 2 lines
System.out.println( "\nsub is now " + sub );
System.out.println( "Now putting " + tt[0] + sub );
dataMap.put( tt[0], sub );
}
input.close();
// Debug next 3 lines
System.out.println( "\nFinal result:" );
for( String s : dataMap.keySet() ) System.out.println( s + "/" + dataMap.get( s ) );
System.out.println();
}
public static void main( String[] args ) {
try {
TestMap testmap = new TestMap();
}
catch ( Exception e ) {
System.exit( 1 );
}
}
}
...
I am using Windows and it compiles without a problem.
& 'C:\Program Files\java\jdk1.8.0_271\bin\javac' -Xlint:unchecked .\TestMap.java
The input file is:
Replace, Title, Description, Language
Create
Delete
Change, Title, Description**
The result I expect would be in the order of key, array of strings like:
DELETE/[]
CREATE/[]
CHANGE/[TITLE,DESCRIPTION]
REPLACE/[TITLE,DESCRIPTION,LANGUAGE]
The result I get (with debug print statements):
java TestMap
Read: REPLACE,TITLE,DESCRIPTION,LANGUAGE
Split to REPLACE/TITLE,DESCRIPTION,LANGUAGE/
sub is now [TITLE,DESCRIPTION,LANGUAGE]
Now putting REPLACE[TITLE,DESCRIPTION,LANGUAGE]
Read: CREATE
sub is now []
Now putting CREATE[]
Read: DELETE
sub is now []
Now putting DELETE[]
Read: CHANGE,TITLE,DESCRIPTION
Split to CHANGE/TITLE,DESCRIPTION/
sub is now [TITLE,DESCRIPTION]
Now putting CHANGE[TITLE,DESCRIPTION]
Final result:
DELETE/[TITLE,DESCRIPTION]
CREATE/[TITLE,DESCRIPTION]
CHANGE/[TITLE,DESCRIPTION]
REPLACE/[TITLE,DESCRIPTION]
Why am I getting the same ArrayList for all keys?
Put ArrayList sub = new ArrayList<>(); inside the loop, you are updating the same array. That is causing the issue. If you notice you are using the same array and clearing the array also putting the same array reference inside the map value. so the map value will contain the last value of array for all keys.
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.*;
import java.nio.file.*;
public class TestMap {
private Map<String, ArrayList<String>> validCommands = new HashMap<String, ArrayList<String>>();
public TestMap( ) throws Exception {
getCommands();
}
private void getCommands() throws Exception {
Map<String,ArrayList<String>> dataMap = new HashMap<>();
String nameFile = "." + File.separator + "TestMap.txt";
FileInputStream fis = new FileInputStream( nameFile );
Scanner input = new Scanner( fis );
while(input.hasNext()) {
ArrayList<String> sub = new ArrayList<>();
String[] tt = {""};
tt[0] = input.nextLine().replace( " ", "" ).toUpperCase();
// Debug next 1 line
System.out.println( "\nRead: " + tt[0] );
CharSequence divider = ",";
if( tt[0].contains( divider ) ) {
tt = tt[0].split( ",", 2 );
// Debug next 2 lines
System.out.print( "Split to " );
for( int i = 0; i<tt.length; i++ ) System.out.print( tt[i] + "/" );
if( tt.length > 1 ) {
for( int i = 1; i<tt.length; i++ ) {
sub.add( tt[i] );
}
}
}
// Debug next 2 lines
System.out.println( "\nsub is now " + sub );
System.out.println( "Now putting " + tt[0] + sub );
dataMap.put( tt[0], sub );
}
input.close();
// Debug next 3 lines
System.out.println( "\nFinal result:" );
for( String s : dataMap.keySet() ) System.out.println( s + "/" + dataMap.get( s ) );
System.out.println();
}
public static void main( String[] args ) {
try {
TestMap testmap = new TestMap();
}
catch ( Exception e ) {
System.exit( 1 );
}
}
}

How to traverse a B-Tree using Stack without recursion?

How to traverse a B-Tree using Stack without recursion?
This is function to traverse Btree using Stack but it does not work
void StackTraverse( BTreeNode node01 ) {
Stack< BTreeNode > stack01 = new Stack< BTreeNode >();
stack01.push( node01 ); // first node "to check"
String string01 = "";
int i = 0;
while ( stack01.size() > 0 ) {
BTreeNode current = stack01.pop();
if ( current.leaf == false ) {// if node is valid
for ( i = 0; i < current.n; i++ ) {
string01 = string01 + "Node : " + current.keys[ i ] + " ";
// string01 = string01 + current.traverse();
stack01.push( current.nodeChild[ i ] );
}
arrayString.add( string01 );
string01 = "";
}
}
}
void StackTraverse() {
String s01 = "";
if ( root != null ) {
StackTraverse( root );
System.out
.println( "\n arrayString.size() = " + arrayString.size() );
for ( int i = 0; i < arrayString.size(); i++ ) {
s01 = arrayString.get( i );
System.out.println( s01 );
}
}
}

Docx4j buffered image

I am using docx4j to manipulate docx. What im trying to do is make buffered image of every image in all tables. I have instance of org.docx4j.wml.Drawing, is there any way to make buffered image from it?
Source codes are mostly downloaded from somewhere.
Only relevant parts:
for (Object o : children ) {
System.out.println(" " + o.getClass().getName() );
if ( o instanceof javax.xml.bind.JAXBElement) {
System.out.println(" " + ((JAXBElement)o).getName() );
System.out.println(" " + ((JAXBElement)o).getDeclaredType().getName());
// TODO - unmarshall directly to Text.
if ( ((JAXBElement)o).getDeclaredType().getName().equals("org.docx4j.wml.Text") ) {
org.docx4j.wml.Text t = (org.docx4j.wml.Text)((JAXBElement)o).getValue();
System.out.println(" " + t.getValue() );
} else if ( ((JAXBElement)o).getDeclaredType().getName().equals("org.docx4j.wml.Drawing") ) {
org.docx4j.wml.Drawing d = (org.docx4j.wml.Drawing)((JAXBElement)o).getValue();
describeDrawing(d);
}
this will basically go thru cells in table and determine wherther its a text or a picture
I want to make bufferedimages from pictures.
Complete source codes:
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import org.docx4j.dml.picture.Pic;
import org.docx4j.dml.wordprocessingDrawing.Anchor;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.openpackaging.io.SaveToZipFile;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Body;
public class Test {
public static JAXBContext context = org.docx4j.jaxb.Context.jc;
/**
* #param args
*/
private static WordprocessingMLPackage wordMLPackage;
public static void main(String[] args) throws Exception {
//String inputfilepath = "/home/dev/workspace/docx4j/sample-docs/jpeg.docx";
String inputfilepath = "C:\\Users\\Blizzard\\Desktop\\VSE\\15.docx";
boolean save = false;
String outputfilepath = "C:\\Users\\Blizzard\\Desktop\\VSE\\112.docx";
// Open a document from the file system
// 1. Load the Package
wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
// 2. Fetch the document part
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
// Display its contents
System.out.println( "\n\n OUTPUT " );
System.out.println( "====== \n\n " );
org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document)documentPart.getJaxbElement();
Body body = wmlDocumentEl.getBody();
List <Object> bodyChildren = body.getEGBlockLevelElts();
walkJAXBElements(bodyChildren);
// Save it
if (save) {
SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
saver.save(outputfilepath);
}
}
static void walkJAXBElements(List <Object> bodyChildren){
for (Object o : bodyChildren ) {
if ( o instanceof javax.xml.bind.JAXBElement) {
System.out.println( o.getClass().getName() );
System.out.println( ((JAXBElement)o).getName() );
System.out.println( ((JAXBElement)o).getDeclaredType().getName() + "\n\n");
if ( ((JAXBElement)o).getDeclaredType().getName().equals("org.docx4j.wml.Tbl") ) {
org.docx4j.wml.Tbl tbl = (org.docx4j.wml.Tbl)((JAXBElement)o).getValue();
describeTable(tbl);
}
} else if (o instanceof org.docx4j.wml.P) {
System.out.println( "Paragraph object: ");
if (((org.docx4j.wml.P)o).getPPr() != null
&& ((org.docx4j.wml.P)o).getPPr().getRPr() != null
&& ((org.docx4j.wml.P)o).getPPr().getRPr().getB() !=null) {
System.out.println( "For a ParaRPr bold!");
}
walkList( ((org.docx4j.wml.P)o).getParagraphContent());
}
}
}
static void walkList(List children){
for (Object o : children ) {
System.out.println(" " + o.getClass().getName() );
if ( o instanceof javax.xml.bind.JAXBElement) {
System.out.println(" " + ((JAXBElement)o).getName() );
System.out.println(" " + ((JAXBElement)o).getDeclaredType().getName());
// TODO - unmarshall directly to Text.
if ( ((JAXBElement)o).getDeclaredType().getName().equals("org.docx4j.wml.Text") ) {
org.docx4j.wml.Text t = (org.docx4j.wml.Text)((JAXBElement)o).getValue();
System.out.println(" " + t.getValue() );
} else if ( ((JAXBElement)o).getDeclaredType().getName().equals("org.docx4j.wml.Drawing") ) {
org.docx4j.wml.Drawing d = (org.docx4j.wml.Drawing)((JAXBElement)o).getValue();
String relation = describeDrawing(d);
}
} else if (o instanceof org.w3c.dom.Node) {
System.out.println(" IGNORED " + ((org.w3c.dom.Node)o).getNodeName() );
} else if ( o instanceof org.docx4j.wml.R) {
org.docx4j.wml.R run = (org.docx4j.wml.R)o;
if (run.getRPr()!=null) {
System.out.println(" " + "Properties...");
if (run.getRPr().getB()!=null) {
System.out.println(" " + "B not null ");
System.out.println(" " + "--> " + run.getRPr().getB().isVal() );
} else {
System.out.println(" " + "B null.");
}
}
walkList(run.getRunContent());
} else {
System.out.println(" IGNORED " + o.getClass().getName() );
}
// else if ( o instanceof org.docx4j.jaxb.document.Text) {
// org.docx4j.jaxb.document.Text t = (org.docx4j.jaxb.document.Text)o;
// System.out.println(" " + t.getValue() );
// }
}
}
static void describeTable( org.docx4j.wml.Tbl tbl ) {
// What does a table look like?
boolean suppressDeclaration = false;
boolean prettyprint = true;
System.out.println( org.docx4j.XmlUtils.marshaltoString(tbl, suppressDeclaration, prettyprint) );
// Could get the TblPr if we wanted them
org.docx4j.wml.TblPr tblPr = tbl.getTblPr();
// Could get the TblGrid if we wanted it
org.docx4j.wml.TblGrid tblGrid = tbl.getTblGrid();
// But here, let's look at the table contents
for (Object o : tbl.getEGContentRowContent() ) {
if (o instanceof org.docx4j.wml.Tr) {
org.docx4j.wml.Tr tr = (org.docx4j.wml.Tr)o;
for (Object o2 : tr.getEGContentCellContent() ) {
System.out.println(" " + o2.getClass().getName() );
if ( o2 instanceof javax.xml.bind.JAXBElement) {
if ( ((JAXBElement)o2).getDeclaredType().getName().equals("org.docx4j.wml.Tc") ) {
org.docx4j.wml.Tc tc = (org.docx4j.wml.Tc)((JAXBElement)o2).getValue();
// Look at the paragraphs in the tc
walkJAXBElements( tc.getEGBlockLevelElts() );
}
else {
// What is it, if it isn't a Tc?
System.out.println(" " + ((JAXBElement)o).getName() );
System.out.println(" " + ((JAXBElement)o).getDeclaredType().getName());
}
} else {
System.out.println("A " + o.getClass().getName() );
}
}
} else {
System.out.println("C " + o.getClass().getName() );
}
}
}
static String describeDrawing( org.docx4j.wml.Drawing d ) {
System.out.println(" describeDrawing " );
String vrat = null;
if ( d.getAnchorOrInline().get(0) instanceof Anchor ) {
System.out.println(" ENCOUNTERED w:drawing/wp:anchor " );
// That's all for now...
} else if ( d.getAnchorOrInline().get(0) instanceof Inline ) {
// Extract w:drawing/wp:inline/a:graphic/a:graphicData/pic:pic/pic:blipFill/a:blip/#r:embed
Inline inline = (Inline )d.getAnchorOrInline().get(0);
Pic pic = inline.getGraphic().getGraphicData().getPic();
//pic.
vrat = pic.getNvPicPr().getCNvPr().getName();
System.out.println( "image name: " + vrat);
//bordel(inline);
} else {
System.out.println(" Didn't get Inline :( How to handle " + d.getAnchorOrInline().get(0).getClass().getName() );
}
return vrat;
}
}
I tried adding some methods and im getting rly desperate:
private static void bordel(org.docx4j.wml.Drawing d){
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
RelationshipsPart relsPart = documentPart.getRelationshipsPart();
Relationships rels = relsPart.getRelationships();
List<Relationship> relsList = rels.getRelationship();
for (Relationship r : relsList) {
JAXBElement el = printInfo(relsPart.getPart(r));
if (el != null) {
if ( el.getDeclaredType().getName().equals("org.docx4j.wml.Drawing") ) {
org.docx4j.wml.Drawing c = (org.docx4j.wml.Drawing) el.getValue();
if (c.equals(d)){
System.out.println( "I found part");
}
}
}
}
}
this method is called on every image in cell and attemps to find Part which i believe i can convert to bufferedimage
but next method converting Part to JAXBElement always returns null
public static JAXBElement printInfo(Part p) {
JAXBElement el = null;
if (p instanceof JaxbXmlPart) {
Object o = ((JaxbXmlPart)p).getJaxbElement();
if (o instanceof javax.xml.bind.JAXBElement) {
//sb.append(" containing JaxbElement:" + XmlUtils.JAXBElementDebug((JAXBElement)o) );
el= (JAXBElement) o;
} else {
//sb.append(" containing JaxbElement:" + o.getClass().getName() );
}
}
return el;
}
The following code will find the image relationships for you:
BlipFinder bf = new BlipFinder();
new TraversalUtil(paragraphs, bf);
for (CTBlip imageReference : bf.blips) {
if (imageReference.getLink() != null
&& !imageReference.getLink().equals("")) {
Relationship existingRel = docxPkg.getMainDocumentPart()
.getRelationshipsPart().getRelationshipByID(
imageReference.getLink());
:
} else if (imageReference.getEmbed() != null) {
String relId = imageReference.getEmbed();
Relationship r = docxPkg.getMainDocumentPart().getRelationshipsPart().getRelationshipByID(relId);
if (r.getTargetMode()!=null
&& r.getTargetMode().toLowerCase().equals("external")) {
:
} else {
BinaryPartAbstractImage oldPart = (BinaryPartAbstractImage)docxPkg.getMainDocumentPart().getRelationshipsPart().getPart(relId);
:
}
} else {
log.error("HELP! neither linked nor embedded?");
}
}
}
static class BlipFinder extends CallbackImpl {
List<CTBlip> blips = new ArrayList<CTBlip>();
#Override
public List<Object> apply(Object o) {
if (o instanceof CTBlip)
blips.add((CTBlip)o);
return null;
}
and in the indicated case, give you a BinaryPartAbstractImage. Once you have that, you can do whatever you like...

Connecting java to ms access database using jdbc odbc, java user login system

i've a problem connecting java to mc access to check a user authentication, when i run this program it doesn't give me any error message(i presume there's no problem with connection) but it also doesn't check whether the account number and password are valid or not. The others method like withdraw, deposit and getBalance are working fine.
Any help or hint will be greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Logic
{
private enum State { ACCOUNT_NO, PASSWORD, PROCESSING };
private State state = State.ACCOUNT_NO;
private long number;
private long acNumber = 0;
private long acPIN = 0;
private char op = ' ';
private Bank bank = new Bank();
private JTextArea display1, display2;
public Logic( JTextArea area1, JTextArea area2 )
{
display1 = area1; display2 = area2;
display2.setText( "Welcome: Enter your account number" );
}
public void process( String button )
{
String info = null;
if ( button.length() == 1 )
{
char c = button.charAt(0);
if ( c >= '0' && c <= '9' ) // Digit
{
number = number * 10 + c-'0'; // Build number
display1.setText( "" + number );
}
return;
}
if ( button.equals( "CLR" ) )
{
number = 0;
display1.setText( "" + number );
}
if ( button.equals( "Ent" ) )
{
switch ( state )
{
case ACCOUNT_NO:
bank.setAcNumber( number );
number = 0;
state = State.PASSWORD;
display1.setText( "" );
display2.setText( "Now enter your password" );
break;
case PASSWORD:
bank.setAcPasswd( number );
number = 0;
display1.setText( "" );
if ( bank.checkValid() )
{
state = State.PROCESSING;
display2.setText( "Now enter transaction" );
} else {
state = State.ACCOUNT_NO;
display2.setText( "Invalid: Start again" );
}
break;
default :
}
return;
}
if ( state != State.PROCESSING )
{
state = State.ACCOUNT_NO;
display2.setText( "But you are not loged in\n" );
display2.append( "Welcome: Enter your account number" );
return;
}
if ( button.equals( "W/D" ) ) // Clear Result
{
display1.setText( "" );
if ( bank.withdraw( number ) )
{
display2.setText( "Withdrawn: " + number );
} else {
display2.setText( "You do not have surficient funds" );
}
number = 0;
return;
}
if ( button.equals( "Bal" ) ) // Clear Result
{
number = 0;
display2.setText( "Your balance is: " + bank.getBalance() );
return;
}
if ( button.equals( "Dep" ) ) // Clear Result
{
bank.deposit( number );
display1.setText( "" );
display2.setText( "Deposited: " + number );
number = 0;
return;
}
if ( button.equals( "Fin" ) ) // Clear Result
{
state = State.ACCOUNT_NO;
number = 0;
display2.setText( "Welcome: Enter your account number" );
return;
}
return;
}
public long getResult()
{
return number;
}
public long getNumber()
{
return number;
}
}
Bank class.
import java.sql.*;
class Bank
{
long AcNumber = 0;
long AcPasswd = 0;
long balance = 0;
long deposit = 0;
long withdraw = 0;
long amount = 0;
Connection con;
Statement st;
ResultSet rs;
public void connect()
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:db3";
con = DriverManager.getConnection(db);
st = con.createStatement();
}
catch (Exception ex)
{
System.err.println("Can not load JDBC/ODBC driver.");
System.exit( -1 );
}
}
public void setAcNumber( long accNumber )
{
AcNumber = accNumber;
}
public void setAcPasswd( long accNumber )
{
AcPasswd = accNumber;
}
public boolean checkValid()
{
try {
String sql = "select user,pass from Table1 where user='"+AcNumber+"'and pass='"+AcPasswd+"'";
rs = st.executeQuery(sql);
int count = 0;
while(rs.next())
{
count = count + 1;
}
if(count == 1)
{
System.out.println("User Found, Now enter transaction");
}
else
{
System.out.println("user not found");
}
}
catch (Exception ex)
{
}
return true;
}
public boolean withdraw( long amount )
{
balance = balance - amount;
System.out.println( "Bank: Withdrawm " + amount );
return true;
}
public void deposit( long amount )
{
balance = balance + amount;
System.out.println( "Bank: deposit " + amount );
return;
}
public long getBalance() {
System.out.println( "Bank: Balance: "+ balance );
return balance;
}
}
You probably don't have an error message because you do nothing when you catch an exception in checkValid. Add ex.printStackTrace() inside your catch block to have more information on what's happening.

Can you add a number to a number in a Array?

package javaapplication1;
import java.io.*;
/**
*
* #author simon
*/
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
NotSimple[] objArray;
BufferedReader stdin = new BufferedReader(
new InputStreamReader( System.in ) );
System.out.println( "Enter a number of objects:" );
int size;
size = Integer.parseInt( stdin.readLine() );
//Initialize objArray
objArray = new NotSimple[size];
//TODO: Implement following functions
initializeObj(objArray);
increaseData(objArray);
printObjData(objArray);
//TODO: Explain all outputs of the below function
explainOutputs();
return;
}
//TODO
//initialize every Notsimple object in the array 'a'
//to NotSimple()
//Hint: using the for loop, assign a[i] = new NotSimple();
static void initializeObj(NotSimple[] a){
//TODO: FILL ME
for (int i = 0; i < a.length; i++)
{
a[i] = new NotSimple();
}
}
//TODO:
//Increase the ‘data’ member of every NotSimple object
//in the array ‘a’ by 1
static void increaseData(NotSimple[] a) {
//TODO: FILL ME
for (int i = 0; i < a.length; i++)
{
a[i].setData(a[i].getData()+1);
}
}
//TODO:
//Print the data of every NotSimple object in the array ‘a’
static void printObjData(NotSimple[] a) {
//TODO: FILL ME
for (int i = 0; i < a.length; i++)
{
System.out.println (a[i].getData());
}
}
//TODO explain all the outputs 1a-1f
static void explainOutputs() {
NotSimple nsObj1 = new NotSimple();
//1a
System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );
NotSimple nsObj2 = new NotSimple( 50,
"Another immutable string!" );
//1b
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
nsObj2 = nsObj1;
nsObj2.setData(10);
nsObj1.setData(100);
//1c
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
nsObj1 = new NotSimple();
//1d
System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
nsObj2 = new NotSimple();
//1e
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
nsObj2.setData(10);
//1f
System.out.println( "nsObj1.data is\t" + nsObj1.getData() );
System.out.println( "nsObj1.str is \t" + nsObj1.getStr() );
System.out.println( "nsObj2.data is\t" + nsObj2.getData() );
System.out.println( "nsObj2.str is \t" + nsObj2.getStr() );
}
}
class NotSimple
{
NotSimple()
{
data = 5;
str = new String( "Initialized!" );
}
NotSimple( int i, String str1 )
{
data = i;
str = str1;
}
void setData( int i )
{
data = i;
return;
}
int getData()
{
return data;
}
void setStr( String str1)
{
str = str1;
return;
}
String getStr()
{
return str;
}
private int data;
private String str;
}
I want to add 1 to the array but it doesn't work. I get the following compilation error:
operator ++ cannot be applied to javaapplication1.NotSimple
Use
for (int i = 0; i < a.length; i++)
{
a[i].setData(a[i].getData()+1);
}
Since Java does not support operator overloading, you'll need to retrieve the old value (i.e. the getData() call), add 1 to it, and set it as the new value (i.e. the setData() call).
What does the NotSimple class look like?
Is NotSimple a numeric type that can be incremented so?
If NotSimple has a field called 'data' then replace a[i]++ with a[i].data++

Categories

Resources