Search Results

Search found 163 results on 7 pages for 'filereader'.

Page 4/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • Java :Interface for this code

    - by ibrahim
    Please i neeed help to make interface for this code: package com.ejada.alinma.edh.xsdtransform; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import java.util.StringTokenizer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /*import org.apache.log4j.Logger;*/ import org.apache.log4j.PropertyConfigurator; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.sun.org.apache.xml.internal.serialize.OutputFormat; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; /** * An XSD Transformer that replaces the "name" attribute's value in T24 XSDs * with the "shortname" attribute's value * * @author ahusseiny * */ public class XSDTransformer { /** * constants representing the XSD tags and attributes' names used in the parse process */ public static final String TAG_SCHEMA = "xsd:schema"; public static final String TAG_TEXT = "#text"; public static final String TAG_COMPLEX_TYPE = "xsd:complexType"; public static final String TAG_SIMPLE_TYPE = "xsd:simpleType"; public static final String TAG_SEQUENCE = "xsd:sequence"; public static final String TAG_ATTRIBUTE = "xsd:attribute"; public static final String TAG_ELEMENT = "xsd:element"; public static final String TAG_ANNOTATION = "xsd:annotation"; public static final String TAG_APP_INFO = "xsd:appinfo"; public static final String TAG_HAS_PROPERTY = "xsd:hasProperty"; public static final String TAG_RESTRICTION = "xsd:restriction"; public static final String TAG_MAX_LENGTH = "xsd:maxLength"; public static final String ATTR_NAME = "name"; public static final String ATTR_VALUE = "value"; public static final String ATTR_TYPE = "type"; public static final String ATTR_MIXED = "mixed"; public static final String ATTR_USE = "use"; public static final String ATTR_REF = "ref"; public static final String ATTR_MAX_OCCURS = "maxOccurs"; /** * constants representing specific XSD attributes' values used in the parse process */ public static final String FIELD_TAG = "fieldtag"; public static final String FIELD_NUMBER = "fieldnumber"; public static final String FIELD_DATA_TYPE = "fielddatatype"; public static final String FIELD_FMT = "fieldfmt"; public static final String FIELD_LEN = "fieldlen"; public static final String FIELD_INPUT_LEN = "fieldinputlen"; public static final String FIELD_GROUP_NUMBER = "fieldgroupnumber"; public static final String FIELD_MV_GROUP_NUMBER = "fieldmvgroupnumber"; public static final String FIELD_SHORT_NAME = "fieldshortname"; public static final String FIELD_NAME = "fieldname"; public static final String FIELD_COLUMN_NAME = "fieldcolumnname"; public static final String FIELD_GROUP_NAME = "fieldgroupname"; public static final String FIELD_MV_GROUP_NAME = "fieldmvgroupname"; public static final String FIELD_JUSTIFICATION = "fieldjustification"; public static final String FIELD_TYPE = "fieldtype"; public static final String FIELD_SINGLE_OR_MULTI = "singleormulti"; public static final String DELIMITER_COLUMN_TYPE = "#"; public static final String COLUMN_FK_ROW = "FK_ROW"; public static final String COLUMN_XPK_ROW = "XPK_ROW"; public static final int SQL_VIEW_MULTI = 1; public static final int SQL_VIEW_SINGLE = 2; public static final String DATA_TYPE_XSD_NUMERIC = "numeric"; public static final String DATA_TYPE_XSD_DECIMAL = "decimal"; public static final String DATA_TYPE_XSD_STRING = "string"; public static final String DATA_TYPE_XSD_DATE = "date"; /** * application configuration properties */ public static final String PROP_LOG4J_CONFIG_FILE = "log4j_config"; public static final String PROP_MAIN_VIEW_NAME_SINGLE = "view_name_single"; public static final String PROP_MAIN_VIEW_NAME_MULTI = "view_name_multi"; public static final String PROP_MAIN_TABLE_NAME = "main_edh_table_name"; public static final String PROP_SUB_TABLE_PREFIX = "sub_table_prefix"; public static final String PROP_SOURCE_XSD_FULLNAME = "source_xsd_fullname"; public static final String PROP_RESULTS_PATH = "results_path"; public static final String PROP_NEW_XSD_FILENAME = "new_xsd_filename"; public static final String PROP_CSV_FILENAME = "csv_filename"; /** * static holders for application-level utilities */ private static Properties appProps; private static Logger appLogger; /** * */ private StringBuffer sqlViewColumnsSingle = null; private StringBuffer sqlViewSelectSingle = null; private StringBuffer columnsCSV = null; private ArrayList<String> singleValueTableColumns = null; private HashMap<String, String> multiValueTablesSQL = null; private HashMap<Object, HashMap<String, Object>> groupAttrs = null; public XSDTransformer(String appConfigPropsPath) { if (appProps == null) { appProps = new Properties(); } try { init(appConfigPropsPath); } catch (Exception e) { appLogger.error(e.getMessage()); } } /** * initialization */ private void init(String appConfigPropsPath) throws Exception { // init the properties object FileReader in = new FileReader(appConfigPropsPath); appProps.load(in); // init the logger if ((appProps.getProperty(XSDTransformer.PROP_LOG4J_CONFIG_FILE) != null) && (!appProps.getProperty(XSDTransformer.PROP_LOG4J_CONFIG_FILE).equals(""))) { PropertyConfigurator.configure(appProps.getProperty(XSDTransformer.PROP_LOG4J_CONFIG_FILE)); if (appLogger == null) { appLogger = Logger.getLogger(XSDTransformer.class.getName()); } appLogger.info("Application initialization successful."); } sqlViewColumnsSingle = new StringBuffer(); sqlViewSelectSingle = new StringBuffer(); columnsCSV = new StringBuffer(XSDTransformer.FIELD_TAG + "," + XSDTransformer.FIELD_NUMBER + "," + XSDTransformer.FIELD_DATA_TYPE + "," + XSDTransformer.FIELD_FMT + "," + XSDTransformer.FIELD_LEN + "," + XSDTransformer.FIELD_INPUT_LEN + "," + XSDTransformer.FIELD_GROUP_NUMBER + "," + XSDTransformer.FIELD_MV_GROUP_NUMBER + "," + XSDTransformer.FIELD_SHORT_NAME + "," + XSDTransformer.FIELD_NAME + "," + XSDTransformer.FIELD_COLUMN_NAME + "," + XSDTransformer.FIELD_GROUP_NAME + "," + XSDTransformer.FIELD_MV_GROUP_NAME + "," + XSDTransformer.FIELD_JUSTIFICATION + "," + XSDTransformer.FIELD_TYPE + "," + XSDTransformer.FIELD_SINGLE_OR_MULTI + System.getProperty("line.separator")); singleValueTableColumns = new ArrayList<String>(); singleValueTableColumns.add(XSDTransformer.COLUMN_XPK_ROW + XSDTransformer.DELIMITER_COLUMN_TYPE + XSDTransformer.DATA_TYPE_XSD_NUMERIC); multiValueTablesSQL = new HashMap<String, String>(); groupAttrs = new HashMap<Object, HashMap<String, Object>>(); } /** * initialize the <code>DocumentBuilder</code> and read the XSD file * * @param docPath * @return the <code>Document</code> object representing the read XSD file */ private Document retrieveDoc(String docPath) { Document xsdDoc = null; File file = new File(docPath); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); xsdDoc = builder.parse(file); } catch (Exception e) { appLogger.error(e.getMessage()); } return xsdDoc; } /** * perform the iteration/modification on the document * iterate to the level which contains all the elements (Single-Value, and Groups) and start processing each * * @param xsdDoc * @return */ private Document transformDoc(Document xsdDoc) { ArrayList<Object> newElementsList = new ArrayList<Object>(); HashMap<String, Object> docAttrMap = new HashMap<String, Object>(); Element sequenceElement = null; Element schemaElement = null; // get document's root element NodeList nodes = xsdDoc.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { if (XSDTransformer.TAG_SCHEMA.equals(nodes.item(i).getNodeName())) { schemaElement = (Element) nodes.item(i); break; } } // process the document (change single-value elements, collect list of new elements to be added) for (int i1 = 0; i1 < schemaElement.getChildNodes().getLength(); i1++) { Node childLevel1 = (Node) schemaElement.getChildNodes().item(i1); // <ComplexType> element if (childLevel1.getNodeName().equals(XSDTransformer.TAG_COMPLEX_TYPE)) { // first, get the main attributes and put it in the csv file for (int i6 = 0; i6 < childLevel1.getChildNodes().getLength(); i6++) { Node child6 = childLevel1.getChildNodes().item(i6); if (XSDTransformer.TAG_ATTRIBUTE.equals(child6.getNodeName())) { if (child6.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { String attrName = child6.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); if (((Element) child6).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE).getLength() != 0) { Node simpleTypeElement = ((Element) child6).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE) .item(0); if (((Element) simpleTypeElement).getElementsByTagName(XSDTransformer.TAG_RESTRICTION).getLength() != 0) { Node restrictionElement = ((Element) simpleTypeElement).getElementsByTagName( XSDTransformer.TAG_RESTRICTION).item(0); if (((Element) restrictionElement).getElementsByTagName(XSDTransformer.TAG_MAX_LENGTH).getLength() != 0) { Node maxLengthElement = ((Element) restrictionElement).getElementsByTagName( XSDTransformer.TAG_MAX_LENGTH).item(0); HashMap<String, String> elementProperties = new HashMap<String, String>(); elementProperties.put(XSDTransformer.FIELD_TAG, attrName); elementProperties.put(XSDTransformer.FIELD_NUMBER, "0"); elementProperties.put(XSDTransformer.FIELD_DATA_TYPE, XSDTransformer.DATA_TYPE_XSD_STRING); elementProperties.put(XSDTransformer.FIELD_FMT, ""); elementProperties.put(XSDTransformer.FIELD_NAME, attrName); elementProperties.put(XSDTransformer.FIELD_SHORT_NAME, attrName); elementProperties.put(XSDTransformer.FIELD_COLUMN_NAME, attrName); elementProperties.put(XSDTransformer.FIELD_SINGLE_OR_MULTI, "S"); elementProperties.put(XSDTransformer.FIELD_LEN, maxLengthElement.getAttributes().getNamedItem( XSDTransformer.ATTR_VALUE).getNodeValue()); elementProperties.put(XSDTransformer.FIELD_INPUT_LEN, maxLengthElement.getAttributes() .getNamedItem(XSDTransformer.ATTR_VALUE).getNodeValue()); constructElementRow(elementProperties); // add the attribute as a column in the single-value table singleValueTableColumns.add(attrName + XSDTransformer.DELIMITER_COLUMN_TYPE + XSDTransformer.DATA_TYPE_XSD_STRING + XSDTransformer.DELIMITER_COLUMN_TYPE + maxLengthElement.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE).getNodeValue()); // add the attribute as a column in the single-values view sqlViewColumnsSingle.append(System.getProperty("line.separator") + attrName + ", "); sqlViewSelectSingle.append(System.getProperty("line.separator") + attrName + ", "); appLogger.debug("added attribute: " + attrName); } } } } } } // now, loop on the elements and process them for (int i2 = 0; i2 < childLevel1.getChildNodes().getLength(); i2++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(i2); // <Sequence> element if (childLevel2.getNodeName().equals(XSDTransformer.TAG_SEQUENCE)) { sequenceElement = (Element) childLevel2; for (int i3 = 0; i3 < childLevel2.getChildNodes().getLength(); i3++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(i3); // <Element> element if (childLevel3.getNodeName().equals(XSDTransformer.TAG_ELEMENT)) { // check if single element or group if (isGroup(childLevel3)) { processGroup(childLevel3, true, null, docAttrMap, xsdDoc, newElementsList); // insert a new comment node with the contents of the group tag sequenceElement.insertBefore(xsdDoc.createComment(serialize(childLevel3)), childLevel3); // remove the group tag sequenceElement.removeChild(childLevel3); } else { processElement(childLevel3); } } } } } } } // add new elements // this step should be after finishing processing the whole document. when you add new elements to the document // while you are working on it, those new elements will be included in the processing. We don't need that! for (int i = 0; i < newElementsList.size(); i++) { sequenceElement.appendChild((Element) newElementsList.get(i)); } // write the new required attributes to the schema element Iterator<String> attrIter = docAttrMap.keySet().iterator(); while(attrIter.hasNext()) { Element attr = (Element) docAttrMap.get(attrIter.next()); Element newAttrElement = xsdDoc.createElement(XSDTransformer.TAG_ATTRIBUTE); appLogger.debug("appending attr. [" + attr.getAttribute(XSDTransformer.ATTR_NAME) + "]..."); newAttrElement.setAttribute(XSDTransformer.ATTR_NAME, attr.getAttribute(XSDTransformer.ATTR_NAME)); newAttrElement.setAttribute(XSDTransformer.ATTR_TYPE, attr.getAttribute(XSDTransformer.ATTR_TYPE)); schemaElement.appendChild(newAttrElement); } return xsdDoc; } /** * check if the <code>element</code> sent is single-value element or group * element. the comparison depends on the children of the element. if found one of type * <code>ComplexType</code> then it's a group element, and if of type * <code>SimpleType</code> then it's a single-value element * * @param element * @return <code>true</code> if the element is a group element, * <code>false</code> otherwise */ private boolean isGroup(Node element) { for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node child = (Node) element.getChildNodes().item(i); if (child.getNodeName().equals(XSDTransformer.TAG_COMPLEX_TYPE)) { // found a ComplexType child (Group element) return true; } else if (child.getNodeName().equals(XSDTransformer.TAG_SIMPLE_TYPE)) { // found a SimpleType child (Single-Value element) return false; } } return false; /* String attrName = null; if (element.getAttributes() != null) { Node attribute = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME); if (attribute != null) { attrName = attribute.getNodeValue(); } } if (attrName.startsWith("g")) { // group element return true; } else { // single element return false; } */ } /** * process a group element. recursively, process groups till no more group elements are found * * @param element * @param isFirstLevelGroup * @param attrMap * @param docAttrMap * @param xsdDoc * @param newElementsList */ private void processGroup(Node element, boolean isFirstLevelGroup, Node parentGroup, HashMap<String, Object> docAttrMap, Document xsdDoc, ArrayList<Object> newElementsList) { String elementName = null; HashMap<String, Object> groupAttrMap = new HashMap<String, Object>(); HashMap<String, Object> parentGroupAttrMap = new HashMap<String, Object>(); if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { elementName = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); } appLogger.debug("processing group [" + elementName + "]..."); // get the attributes if a non-first-level-group // attributes are: groups's own attributes + parent group's attributes if (!isFirstLevelGroup) { // get the current element (group) attributes for (int i1 = 0; i1 < element.getChildNodes().getLength(); i1++) { if (XSDTransformer.TAG_COMPLEX_TYPE.equals(element.getChildNodes().item(i1).getNodeName())) { Node complexTypeNode = element.getChildNodes().item(i1); for (int i2 = 0; i2 < complexTypeNode.getChildNodes().getLength(); i2++) { if (XSDTransformer.TAG_ATTRIBUTE.equals(complexTypeNode.getChildNodes().item(i2).getNodeName())) { appLogger.debug("add group attr: " + ((Element) complexTypeNode.getChildNodes().item(i2)).getAttribute(XSDTransformer.ATTR_NAME)); groupAttrMap.put(((Element) complexTypeNode.getChildNodes().item(i2)).getAttribute(XSDTransformer.ATTR_NAME), complexTypeNode.getChildNodes().item(i2)); docAttrMap.put(((Element) complexTypeNode.getChildNodes().item(i2)).getAttribute(XSDTransformer.ATTR_NAME), complexTypeNode.getChildNodes().item(i2)); } } } } // now, get the parent's attributes parentGroupAttrMap = groupAttrs.get(parentGroup); if (parentGroupAttrMap != null) { Iterator<String> iter = parentGroupAttrMap.keySet().iterator(); while (iter.hasNext()) { String attrName = iter.next(); groupAttrMap.put(attrName, parentGroupAttrMap.get(attrName)); } } // put the attributes in the attributes map groupAttrs.put(element, groupAttrMap); } for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node childLevel1 = (Node) element.getChildNodes().item(i); if (childLevel1.getNodeName().equals(XSDTransformer.TAG_COMPLEX_TYPE)) { for (int j = 0; j < childLevel1.getChildNodes().getLength(); j++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(j); if (childLevel2.getNodeName().equals(XSDTransformer.TAG_SEQUENCE)) { for (int k = 0; k < childLevel2.getChildNodes().getLength(); k++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(k); if (childLevel3.getNodeName().equals(XSDTransformer.TAG_ELEMENT)) { // check if single element or group if (isGroup(childLevel3)) { // another group element.. // unfortunately, a recursion is // needed here!!! :-( processGroup(childLevel3, false, element, docAttrMap, xsdDoc, newElementsList); } else { // reached a single-value element.. copy it under the // main sequence and apply the name-shorname // replacement processGroupElement(childLevel3, element, isFirstLevelGroup, xsdDoc, newElementsList); } } } } } } } appLogger.debug("finished processing group [" + elementName + "]."); } /** * process the sent <code>element</code> to extract/modify required * information: * 1. replace the <code>name</code> attribute with the <code>shortname</code>. * * @param element */ private void processElement(Node element) { String fieldShortName = null; String fieldColumnName = null; String fieldDataType = null; String fieldFormat = null; String fieldInputLength = null; String elementName = null; HashMap<String, String> elementProperties = new HashMap<String, String>(); if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { elementName = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); } appLogger.debug("processing element [" + elementName + "]..."); for (int i = 0; i < element.getChildNodes().getLength(); i++) { Node childLevel1 = (Node) element.getChildNodes().item(i); if (childLevel1.getNodeName().equals(XSDTransformer.TAG_ANNOTATION)) { for (int j = 0; j < childLevel1.getChildNodes().getLength(); j++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(j); if (childLevel2.getNodeName().equals(XSDTransformer.TAG_APP_INFO)) { for (int k = 0; k < childLevel2.getChildNodes().getLength(); k++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(k); if (childLevel3.getNodeName().equals(XSDTransformer.TAG_HAS_PROPERTY)) { if (childLevel3.getAttributes() != null) { String attrName = null; Node attribute = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME); if (attribute != null) { attrName = attribute.getNodeValue(); elementProperties.put(attrName, childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue()); if (attrName.equals(XSDTransformer.FIELD_SHORT_NAME)) { fieldShortName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_COLUMN_NAME)) { fieldColumnName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_DATA_TYPE)) { fieldDataType = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_FMT)) { fieldFormat = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_INPUT_LEN)) { fieldInputLength = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } } } } } } } } } if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).setNodeValue(fieldShortName); } sqlViewColumnsSingle.append(System.getProperty("line.separator") + fieldColumnName + ", "); sqlViewSelectSingle.append(System.getProperty("line.separator") + fieldShortName + ", "); elementProperties.put(XSDTransformer.FIELD_SINGLE_OR_MULTI, "S"); constructElementRow(elementProperties); singleValueTableColumns.add(fieldShortName + XSDTransformer.DELIMITER_COLUMN_TYPE + fieldDataType + fieldFormat + XSDTransformer.DELIMITER_COLUMN_TYPE + fieldInputLength); appLogger.debug("finished processing element [" + elementName + "]."); } /** * process the sent <code>element</code> to extract/modify required * information: * 1. copy the element under the main sequence * 2. replace the <code>name</code> attribute with the <code>shortname</code>. * 3. add the attributes of the parent groups (if non-first-level-group) * * @param element */ private void processGroupElement(Node element, Node parentGroup, boolean isFirstLevelGroup, Document xsdDoc, ArrayList<Object> newElementsList) { String fieldShortName = null; String fieldColumnName = null; String fieldDataType = null; String fieldFormat = null; String fieldInputLength = null; String elementName = null; Element newElement = null; HashMap<String, String> elementProperties = new HashMap<String, String>(); ArrayList<String> tableColumns = new ArrayList<String>(); HashMap<String, Object> groupAttrMap = null; if (element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME) != null) { elementName = element.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME).getNodeValue(); } appLogger.debug("processing element [" + elementName + "]..."); // 1. copy the element newElement = (Element) element.cloneNode(true); newElement.setAttribute(XSDTransformer.ATTR_MAX_OCCURS, "unbounded"); // 2. if non-first-level-group, replace the element's SimpleType tag with a ComplexType tag if (!isFirstLevelGroup) { if (((Element) newElement).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE).getLength() != 0) { // there should be only one tag of SimpleType Node simpleTypeNode = ((Element) newElement).getElementsByTagName(XSDTransformer.TAG_SIMPLE_TYPE).item(0); // create the new ComplexType element Element complexTypeNode = xsdDoc.createElement(XSDTransformer.TAG_COMPLEX_TYPE); complexTypeNode.setAttribute(XSDTransformer.ATTR_MIXED, "true"); // get the list of attributes for the parent group groupAttrMap = groupAttrs.get(parentGroup); Iterator<String> attrIter = groupAttrMap.keySet().iterator(); while(attrIter.hasNext()) { Element attr = (Element) groupAttrMap.get(attrIter.next()); Element newAttrElement = xsdDoc.createElement(XSDTransformer.TAG_ATTRIBUTE); appLogger.debug("adding attr. [" + attr.getAttribute(XSDTransformer.ATTR_NAME) + "]..."); newAttrElement.setAttribute(XSDTransformer.ATTR_REF, attr.getAttribute(XSDTransformer.ATTR_NAME)); newAttrElement.setAttribute(XSDTransformer.ATTR_USE, "optional"); complexTypeNode.appendChild(newAttrElement); } // replace the old SimpleType node with the new ComplexType node newElement.replaceChild(complexTypeNode, simpleTypeNode); } } // 3. replace the name with the shortname in the new element for (int i = 0; i < newElement.getChildNodes().getLength(); i++) { Node childLevel1 = (Node) newElement.getChildNodes().item(i); if (childLevel1.getNodeName().equals(XSDTransformer.TAG_ANNOTATION)) { for (int j = 0; j < childLevel1.getChildNodes().getLength(); j++) { Node childLevel2 = (Node) childLevel1.getChildNodes().item(j); if (childLevel2.getNodeName().equals(XSDTransformer.TAG_APP_INFO)) { for (int k = 0; k < childLevel2.getChildNodes().getLength(); k++) { Node childLevel3 = (Node) childLevel2.getChildNodes().item(k); if (childLevel3.getNodeName().equals(XSDTransformer.TAG_HAS_PROPERTY)) { if (childLevel3.getAttributes() != null) { String attrName = null; Node attribute = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_NAME); if (attribute != null) { attrName = attribute.getNodeValue(); elementProperties.put(attrName, childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue()); if (attrName.equals(XSDTransformer.FIELD_SHORT_NAME)) { fieldShortName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_COLUMN_NAME)) { fieldColumnName = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_DATA_TYPE)) { fieldDataType = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE) .getNodeValue(); } else if (attrName.equals(XSDTransformer.FIELD_FMT)) { fieldFormat = childLevel3.getAttributes().getNamedItem(XSDTransformer.ATTR_VALUE)

    Read the article

  • Error "window" is not defined when loading Protovis from javax.script?

    - by Shane
    I am loading Protovis using javax.script: ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName(scriptEngine); engine.eval(new java.io.FileReader("protovis-d3.1.js")); But I get the following exception: Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascr ipt.internal.EcmaError: ReferenceError: "window" is not defined. (<Unknown sourc e>#5033) in <Unknown source> at line number 5033 at com.sun.script.javascript.RhinoScriptEngine.eval(Unknown Source) at javax.script.AbstractScriptEngine.eval(Unknown Source) at RJScript.EvalScript(RJScript.java:20) at RJScript.main(RJScript.java:26) This same script runs from a browser. Do I need to do something so that the "window" is defined?

    Read the article

  • Jruby embedded modules and classes.

    - by James Moore
    Hey, I have a ruby file as follows: module Example class Myclass def t_st "Hello World!" end end end now if this was just a class I would be able to use the following java code: ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby"); jruby.eval(new BufferedReader(new FileReader("example.rb"))); Object example = jruby.eval("myclass.new"); However, this class rests inside a module. Calling the same code as above produces the error: Exception in thread "main" org.jruby.embed.EvalFailedException: uninitialized constant myclass In addition, calling: Object example = jruby.eval("Example"); The module returns no error. So one would assume this follows the format for Ruby. Object example = jruby.eval("Example::myclass.new"); Again however, I get the same error as before. Can anyone help? As there is little documentation on JRuby? Thanks

    Read the article

  • Unit Testing XML independent of physical XML file

    - by RAbraham
    Hi, My question is: In JUnit, How do I setup xml data for my System Under Test(SUT) without making the SUT read from an XML file physically stored on the file system Background: I am given a XML file which contains rules for creation of an invoice. My job is to convert these rules from XMl to Java Objects e.g. If there is a tag as below in my XML file which indicates that after a period of 30 days, the transaction cannot be invoiced <ExpirationDay>30</ExpirationDay> this converts to a Java class , say ExpirationDateInvoicingRule I have a class InvoiceConfiguration which should take the XML file and create the *InvoicingRule objects. I am thinking of using StAX to parse the XML document within InvoiceConfiguration Problem: I want to unit test InvoiceConfiguration. But I dont want InvoiceConfiguration to read from an xml file physically on the file system . I want my unit test to be independent of any physical stored xml file. I want to create a xml representation in memory. But a StAX parser only takes FileReader( or I can play with the File Object)

    Read the article

  • Java: Print and access List <String[]>

    - by battousai622
    Im reading in a file and storing it in t1. How do i access the elements in t1? When i try to print it i get addresses instead of values. Also whats the dif between string and string[]? CSVReader reader = new CSVReader(new FileReader("src/new_acquisitions.csv")); List <String[]> t1 = reader.readAll(); int i = 0 while(i < t1.size()) { System.out.println(t1.get(i)); i++; } output: [Ljava.lang.String;@9304b1 [Ljava.lang.String;@190d11 [Ljava.lang.String;@a90653 [Ljava.lang.String;@de6ced

    Read the article

  • How to create a Java String from the contents of a file

    - by Oscar Reyes
    I've been using this idiom for some time now. And it seems to be the most wide spread at least in the sites I've visited. Does anyone have a better/different way to read a file into a string in Java. Thanks private String readFile( String file ) throws IOException { BufferedReader reader = new BufferedReader( new FileReader (file)); String line = null; StringBuilder stringBuilder = new StringBuilder(); String ls = System.getProperty("line.separator"); while( ( line = reader.readLine() ) != null ) { stringBuilder.append( line ); stringBuilder.append( ls ); } return stringBuilder.toString(); }

    Read the article

  • Invalid Viewstate

    - by murak
    I always got this error guys on my site.Anybody got a solution. Stacktrace at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType) at System.Web.UI.Page.DecryptString(String s) at System.Web.Handlers.ScriptResourceHandler.DecryptParameter(NameValueCollection queryString) at System.Web.Handlers.ScriptResourceHandler.ProcessRequestInternal(HttpResponse response, NameValueCollection queryString, VirtualFileReader fileReader) at System.Web.Handlers.ScriptResourceHandler.ProcessRequest(HttpContext context) at System.Web.Handlers.ScriptResourceHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Query String d=J_c3w3Q59U-PnoRlWBPOJMVgHe_9Ile9wANEXiRFLzG8mequestManager._initialize('ctl00%24ScriptManager1' I noticed that there are strings that got appended on the last part of ScriptResource.axd which are not part of the querystring(equestManager._initialize('ctl00%24ScriptManager1').I don't know how this string ends up here.I am using MS ajax, webforms and IIS7 on a shared hosting plan.

    Read the article

  • How to get java to recognize symbolic links under cygwin

    - by Keith Randall
    Here's a very simple java program to print the first line of a file: import java.io.* public class test { public static void main(String[] args) throws IOException { System.out.print(new BufferedReader(new FileReader(args[0])).readLine()); } } When I run this program under cygwin and pass it the name of a symbolic link, it prints the contents of the symbolic link, not the target of that link: $ echo foo > testfile $ ln -s testfile symlink_to_testfile $ java test testfile foo $ java test symlink_to_testfile !<symlink> ?t e s t f i l e How do I convince java to follow the symlink? I was hoping there was something simpler than implementing the redirect myself.

    Read the article

  • Java: opening and reading from a file without locking it.

    - by rogue780
    I need to be able to mimic 'tail -f' with Java. I'm trying to read a log file as it's being written by another process, but when I open the file to read it, it locks the file and the other process can't write to it anymore. Any help would be greatly appreciated! Here is the code that I'm using currently: public void read(){ Scanner fp = null; try{ fp = new Scanner(new FileReader(this.filename)); fp.useDelimiter("\n"); }catch(java.io.FileNotFoundException e){ System.out.println("java.io.FileNotFoundException e"); } while(true){ if(fp.hasNext()){ this.parse(fp.next()); } } }

    Read the article

  • Huge file in Clojure and Java heap space error

    - by trzewiczek
    I posted before on a huge XML file - it's a 287GB XML with Wikipedia dump I want ot put into CSV file (revisions authors and timestamps). I managed to do that till some point. Before I got the StackOverflow Error, but now after solving the first problem I get: java.lang.OutOfMemoryError: Java heap space error. My code (partly taken from Justin Kramer answer) looks like that: (defn process-pages [page] (let [title (article-title page) revisions (filter #(= :revision (:tag %)) (:content page))] (for [revision revisions] (let [user (revision-user revision) time (revision-timestamp revision)] (spit "files/data.csv" (str "\"" time "\";\"" user "\";\"" title "\"\n" ) :append true))))) (defn open-file [file-name] (let [rdr (BufferedReader. (FileReader. file-name))] (->> (:content (data.xml/parse rdr :coalescing false)) (filter #(= :page (:tag %))) (map process-pages)))) I don't show article-title, revision-user and revision-title functions, because they just simply take data from a specific place in the page or revision hash. Anyone could help me with this - I'm really new in Clojure and don't get the problem.

    Read the article

  • Problem with "scopes" of variables in try catch blocks in Java

    - by devoured elysium
    Could anyone explain me why in the last lines, br is not recognized as variable? I've even tried putting br in the try clause, setting it as final, etc. Does this have anything to do with Java not support closures? I am 99% confident similar code would work in C#. private void loadCommands(String fileName) { try { final BufferedReader br = new BufferedReader(new FileReader(fileName)); while (br.ready()) { actionList.add(CommandFactory.GetCommandFromText(this, br.readLine())); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) br.close(); //<-- This gives error. It doesn't // know the br variable. } } Thanks

    Read the article

  • Write a file in UTF-8 using FileWriter (Java)?

    - by user1280970
    I have the following code however, I want it to write as a UTF-8 file to handle foreign characters. Is there a way of doing this, is there some need to have a parameter? I would really appreciate your help with this. Thanks. try { BufferedReader reader = new BufferedReader(new FileReader("C:/Users/Jess/My Documents/actresses.list")); writer = new BufferedWriter(new FileWriter("C:/Users/Jess/My Documents/actressesFormatted.csv")); while( (line = reader.readLine()) != null) { //If the line starts with a tab then we just want to add a movie //using the current actor's name. if(line.length() == 0) continue; else if(line.charAt(0) == '\t') { readMovieLine2(0, line, surname.toString(), forename.toString()); } //Else we've reached a new actor else { readActorName(line); } } } catch (IOException e) { e.printStackTrace(); } }

    Read the article

  • Using javax.script or Rhino to run javascript in Java with browser context (e.g. envjs)?

    - by Shane
    I am trying to run Protovis javascript from a Java program using javax.script: ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.eval(new java.io.FileReader("protovis-d3.1.js")); In order to run this, the JavaScript engine needs to have all the context of a web browser. The best option for this seems to be envjs. Unfortunately it seems that the version of Rhino included in the JVM isn't up to date and doesn't include everything that's necessary for envjs. Has anyone had any success working with a browser context from javax.script, or am I missing something? This is related to this question: "Can I create a ‘window’ object for javascript running in the Java6 Rhino Script Engine".

    Read the article

  • How to append text into text file dynamically

    - by niraj deshmukh
    [12] key1=val1 key2=val2 key3=val3 key4=val4 key5=val5 [13] key1=val1 key2=val2 key3=val3 key4=val4 key5=xyz [14] key1=val1 key2=val2 key3=val3 key4=val4 key5=val5 I want to update key5=val5 where [13]. try { br = new BufferedReader(new FileReader(oldFileName)); bw = new BufferedWriter(new FileWriter(tmpFileName)); String line; while ((line = br.readLine()) != null) { System.out.println(line); if (line.contains("[13]")) { while (line.contains("key5")) { if (line.contains("key5")) { line = line.replace("key5", "key5= Val5"); bw.write(line+"\n"); } } } } } catch (Exception e) { return; } finally { try { if(br != null) br.close(); } catch (IOException e) { // } try { if(bw != null) bw.close(); } catch (IOException e) { // } }

    Read the article

  • How to deal with extra space characters while Reading a CSV file?

    - by Ravi Dutt
    I am reading a CSV file with CSV Open Source API. as shown below: Java Code:--> CSVReader reader = new CSVReader(new FileReader(filePath),'\n'); String[] values; if((read=(reader.readNext()))!=null) { values = (read[0].split(" (?=([^\"]*\"[^\"]*\")*[^\"]*$)",-1)).length; } // code ends here When I read this CSV file line by line and split that line with delimiter. Then after spliting values each value I get contains extra space character after each character in String. Suppose value in file is like "ABC" and I got this after reading from CSV file reader as " A B C " . I used removeAll("\s+","") on each value even after it is not working. Thank You in Advance.

    Read the article

  • Force IOException during file reading

    - by DixonD
    I have the piece of code that reads data from file. I want to force IOException in this code for testing purpose (I want to check if code throws correct custom exception in this case). Is there a some way to create a file which is protected from being read, for example? Maybe dealing with some security checks can help? Please, note that passing name to not-existent file cannot help, because FileNotFoundException has separate catch clause. Here peace of code for better undestanding of question: BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(csvFile)); String rawLine; while ((rawLine = reader.readLine()) != null) { // some work is done here } } catch (FileNotFoundException e) { throw new SomeCustomException(); } catch (IOException e) { throw new SomeCustomException(); } finally { // close the input stream if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } } }

    Read the article

  • What is the best way to read files in an EventMachine-based app?

    - by Theo
    In order not to block the reactor I would like to read files asynchronously, but I've found no obvious way of doing it using EventMachine. I've tried a few different approaches, but none of them feels right: Just read the file, it'll block the reactor, but what the hell, it's not that slow (unless it's a big file, and then it definitely is). Open the file for reading and read a chunk on each tick (but how much to read? too much and it'll block the reactor, too little and reading will get slower than necessary). EM.popen('cat some/file', FileReader) feels really weird, but works better than the alternatives above. In combination with the LineAndTextProtocol it reads lines pretty swiftly. EM.attach, but I haven't found any examples of how to use it, and the only thing I've found on the mailing list is that it's deprecated in favour of… EM.watch, which I've found no examples of how to use for reading files. How do you read files within a EventMachine reactor loop?

    Read the article

  • JAVA. Writing a matrix in a file using column information.

    - by Dmitry
    Hello, everybody! I have a file in which a matrix is stored. This file has a RandomAccessFile type. This matrix is stored by columns. I mean that in an i-th row of this matrix an i-th column (of a real matrix) is stored. There is an example: i-th row: 1 2 3 4 (in the file). That means that the real matrix has an i-th column: (1 2 3 4)(transpose). I need to save this matrix in natural way (by rows) in a new file, which I will then open with FileReader and display with TestArea. DO you know, how to do that? If so, please help =)

    Read the article

  • How to read comma separated values from text file in JAVA?

    - by user1425223
    I have got this text file with latitude and longitude values of different points on a map. I want to store these coordinates into a mySQL database using hibernate. I want to know how can I split my string into latitudes and longitudes? What is the general way to do these type of things that is with other delimiters like space, tab etc.? File: 28.515046280572285,77.38258838653564 28.51430151808072,77.38336086273193 28.513566177802456,77.38413333892822 28.512830832397192,77.38490581512451 28.51208605426073,77.3856782913208 28.511341270865113,77.38645076751709 28.510530488025346,77.38720178604126 28.509615992924807,77.38790988922119 28.50875805732363,77.38862872123718 28.507994394490268,77.38943338394165 28.50728729434496,77.39038825035095 28.506674470385246,77.39145040512085 28.506174780521828,77.39260911941528 28.505665660113582,77.39376783370972 28.505156537248446,77.39492654800415 28.50466626846366,77.39608526229858 28.504175997400655,77.39724397659302 28.503685724059455,77.39840269088745 28.503195448440064,77.39956140518188 28.50276174118543,77.4007523059845 28.502309175192945,77.40194320678711 28.50185660725938,77.40313410758972 28.50140403738471,77.40432500839233 28.500951465568985,77.40551590919495 28.500498891812207,77.40670680999756 28.5000463161144,77.40789771080017 28.49959373847559,77.40908861160278 Code I am using to read from file: try { BufferedReader in = new BufferedReader(new FileReader("G:\\RoutePPAdvant2.txt")); String str; str = in.readLine(); while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (IOException e) { System.out.println("File Read Error"); }

    Read the article

  • Java. Writing a matrix in a file using column information. ( matrix transposition )

    - by Dmitry
    Hello, everybody! I have a file in which a matrix is stored. This file has a RandomAccessFile type. This matrix is stored by columns. I mean that in an i-th row of this matrix an i-th column (of a real matrix) is stored. There is an example: i-th row: 1 2 3 4 (in the file). That means that the real matrix has an i-th column: (1 2 3 4)(is transposed). I need to save this matrix in a natural way (by rows) in a new file, which I will then open with FileReader and display with TextArea. Do you know, how to do that? If so, please help =)

    Read the article

  • Using methods on 2 input files - 2nd is printing multiple times - Java

    - by Aaa
    I have the following code to read in text, store in a hashmap as bigrams (with other methods to sort them by frequency and do v. v. basic additive smoothing. I had it working great for one language input file (english) and then I want to expand it for the second language input file (japanese - doens;t matter what it is I suppose) using the same methods but the Japanese bigram hashmap is printing out 3 times in a row with diff. values. I've tried using diff text in the input file, making sure there are no gaps in text etc. I've also put print statements at certain places in the Japanese part of the code to see if I can get any clues but all the print statements are printing each time so I can't work out if it is looping at a certain place. I have gone through it with a fine toothcomb but am obviously missing something and slowly going crazy here - any help would be appreciated. thanks in advance... package languagerecognition2; import java.lang.String; import java.io.InputStreamReader; import java.util.*; import java.util.Iterator; import java.util.List.*; import java.util.ArrayList; import java.util.AbstractMap.*; import java.lang.Object; import java.io.*; import java.util.Enumeration; import java.util.Arrays; import java.lang.Math; public class Main { /** public static void main(String[] args) { //training English ----------------------------------------------------------------- File file = new File("english1.txt"); StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String test = null; //test = reader.readLine(); // repeat until all lines are read while ((test = reader.readLine()) != null) { test = test.toLowerCase(); char[] charArrayEng = test.toCharArray(); HashMap<String, Integer> hashMapEng = new HashMap<String, Integer>(bigrams(charArrayEng)); LinkedHashMap<String, Integer> sortedListEng = new LinkedHashMap<String, Integer>(sort(hashMapEng)); int sizeEng=sortedListEng.size(); System.out.println("Total count of English bigrams is " + sizeEng); LinkedHashMap<String, Integer> smoothedListEng = new LinkedHashMap<String, Integer>(smooth(sortedListEng, sizeEng)); //print linkedHashMap to check values Set set= smoothedListEng.entrySet(); Iterator iter = set.iterator ( ) ; System.out.println("Beginning English"); while ( iter.hasNext()) { Map.Entry entry = ( Map.Entry ) iter.next ( ) ; Object key = entry.getKey ( ) ; Object value = entry.getValue ( ) ; System.out.println( key+" : " + value); } System.out.println("End English"); }//end while }//end try catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } //End training English----------------------------------------------------------- //Training japanese-------------------------------------------------------------- File file2 = new File("japanese1.txt"); StringBuffer contents2 = new StringBuffer(); BufferedReader reader2 = null; try { reader2 = new BufferedReader(new FileReader(file2)); String test2 = null; //repeat until all lines are read while ((test2 = reader2.readLine()) != null) { test2 = test2.toLowerCase(); char[] charArrayJap = test2.toCharArray(); HashMap<String, Integer> hashMapJap = new HashMap<String, Integer>(bigrams(charArrayJap)); //System.out.println( "bigrams stage"); LinkedHashMap<String, Integer> sortedListJap = new LinkedHashMap<String, Integer>(sort(hashMapJap)); //System.out.println( "sort stage"); int sizeJap=sortedListJap.size(); //System.out.println("Total count of Japanese bigrams is " + sizeJap); LinkedHashMap<String, Integer> smoothedListJap = new LinkedHashMap<String, Integer>(smooth(sortedListJap, sizeJap)); System.out.println( "smooth stage"); //print linkedHashMap to check values Set set2= smoothedListJap.entrySet(); Iterator iter2 = set2.iterator(); System.out.println("Beginning Japanese"); while ( iter2.hasNext()) { Map.Entry entry2 = ( Map.Entry ) iter2.next ( ) ; Object key = entry2.getKey ( ) ; Object value = entry2.getValue ( ) ; System.out.println( key+" : " + value); }//end while System.out.println("End Japanese"); }//end while }//end try catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader2 != null) { reader2.close(); } } catch (IOException e) { e.printStackTrace(); } } //end training Japanese--------------------------------------------------------- } //end main (inner)

    Read the article

  • How to read loaded image into a blob?

    - by Gajus Kuizinas
    I am facing same-origin policy restrictions when loading remote images. However DOM 0 Image object can be used to load a remote resource (this is essentially the same as creating an <img /> tag). var fr = new FileReader(), img = new Image(); img.src = 'http://distilleryimage8.s3.amazonaws.com/6cf25568491a11e2af8422000a9e28e9_7.jpg'; img.onload = function () { // how to get this image as a Blob object? }; Is there a way to read this resource into a Blob/arraybuffer object? This is not a duplicate of How to convert an image object to a binary blob as the latter does not rise with same-origin issues.

    Read the article

  • Calling class in Java after editing file used in as source for table

    - by user2892290
    I'm currently working on a project, I'll try to subrscibe first. I save data into text file, that I use as a source for browser of that data. The browser is based on table that contains the data. I have to rewrite the source file everytime I delete or edit data. That's where the problem comes in. After deleting or editing data I call a method to create the table again, but the table never creates. Is it possibly made by editing the file and calling the method right after that? If I restart my app the table is successfully created with right data. Take in note that I don't get any error message. This is the method I use for loading data from source file: try (BufferedReader input1 = new BufferedReader(new FileReader("./src/data.src"))) { int lines = 0; while (input1.read() != -1) { if (!(input1.readLine()).equals("")) { lines++; } } input1.close(); if (lines == 0) { JOptionPane.showMessageDialog(null, "No data to load, create a note first!"); new Writer().build(frame); } else { try (BufferedReader input = new BufferedReader(new FileReader("./src/data.src"))) { Game[] g = new Game[lines]; String currentLine; String[] help; int counter = 0; while (lines > 0) { currentLine = input.readLine(); help = currentLine.split("#"); g[counter] = new Game(help[0],help[1], help[2], help[3], help[4], help[5], help[6], help[7], help[8], help[9]); counter++; lines--; } input.close(); final JButton bButton = new backButton().create(frame, mPanel); build(g, frame, bButton); mPanel.add(panel); mPanel.add(panel2); mPanel.add(searchPanel); mPanel.add(bButton); bButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); panel.removeAll(); frame.setCursor(Cursor.getDefaultCursor()); } }); mPanel.setPreferredSize(new Dimension(1000, 750)); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); frame.setLayout(new FlowLayout()); frame.add(mPanel); frame.pack(); JMenuBar menuBar = new Menu().create(frame, mPanel); frame.setJMenuBar(menuBar); frame.setVisible(true); Rectangle rec = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); int width = (int) rec.getWidth(); int height = (int) rec.getHeight(); frame.setBounds(1, 3, width, height); frame.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { frame.setLocation(1, 3); } }); And this is the method I use for creating the table: String[][] tableData = new String[g.length][9]; for (int i = 0; i < tableData.length; i++) { tableData[i][0] = g[i].getChampion(); tableData[i][1] = g[i].getRole(); tableData[i][2] = g[i].getEnemy(); tableData[i][3] = g[i].getDifficulty(); tableData[i][4] = g[i].getResult(); tableData[i][5] = g[i].getScore(); tableData[i][6] = g[i].getGameType(); tableData[i][7] = g[i].getPoints(); tableData[i][8] = g[i].getLeague(); } final JLabel searchLabel = new JLabel("Search for champion played."); final JButton searchButton = new JButton("Search"); final JTextField searchText = new JTextField(20); frame.setTitle("LoL Notepad - reading your notes"); JTable table = new JTable(tableData, columnNames); final JScrollPane scrollPane = new JScrollPane(table); scrollPane.setPreferredSize(new Dimension(980, 500)); panel2.setPreferredSize(new Dimension(1000, 550)); panel2.setVisible(false); panel2.setBorder(new EmptyBorder(10, 10, 10, 10)); panel3.setVisible(false); panel.setLayout(new FlowLayout()); panel.add(scrollPane); searchPanel.add(searchLabel); searchPanel.add(searchText); searchPanel.add(searchButton); searchButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); search(g, searchText.getText(), frame, bButton); frame.setCursor(Cursor.getDefaultCursor()); } catch (IOException ex) { Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex); } } }); table.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getClickCount() == 1) { JTable target = (JTable) e.getSource(); panel.setVisible(false); searchPanel.setVisible(false); bButton.setVisible(false); int row = target.getSelectedRow(); specific(row, g, frame, bButton); } } });

    Read the article

  • Drawing Image onto Canvas Stretches Image?

    - by Fred Finkle
    I have this code (stolen from the web): function readIt() { var reader = new FileReader(); reader.onload = (function(e) { var img = new Image(); img.src = e.target.result; var c = document.getElementById("canvas"); var ctx = c.getContext("2d"); ctx.drawImage(img, 0, 0); } ); reader.readAsDataURL(document.getElementById('userImage').files[0]); } Which works up to a point. The canvas's width and height are set to the size of the image, but only the top left of the image appears - It appears to be stretched so it fits all the space allocated to the canvas (enough to display the whole image - 615px x 615px). If I add an <img> element sized the same size as the canvas and point the src to the image in the file system it appears perfect. I'm using Chrome, but it appears the same in Firefox. Thanks in advance.

    Read the article

  • Java Double Array

    - by user1062058
    I'm having trouble setting up and placing values into an array using a text file containing the floating point numbers 2.1 and 4.3 each number is separated by a space - below is the error I'm getting: Exception in thread "main" java.util.NoSuchElementException import java.util.*; import java.io.*; public class DoubleArray { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new FileReader("mytestnumbers.txt")); double [] nums = new double[2]; for (int counter=0; counter < 2; counter++) { int index = 0; index++; nums[index] = in.nextDouble(); } } } Thanks, I'm sure this isn't a hard question to answer... I appreciate your time.

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >