List of usage examples for org.xml.sax SAXException SAXException
public SAXException(Exception e)
From source file:SAXTreeValidator.java
/** * <p>// w w w . ja va2s .c o m * This will report an error that has occurred; this indicates * that a rule was broken, typically in validation, but that * parsing can reasonably continue. * </p> * * @param exception <code>SAXParseException</code> that occurred. * @throws <code>SAXException</code> when things go wrong */ public void error(SAXParseException exception) throws SAXException { System.out.println("**Parsing Error**\n" + " Line: " + exception.getLineNumber() + "\n" + " URI: " + exception.getSystemId() + "\n" + " Message: " + exception.getMessage()); throw new SAXException("Error encountered"); }
From source file:XMLWriter.java
/** * Write a newline at the end of the document. * * Pass the event on down the filter chain for further processing. * * @exception org.xml.sax.SAXException If there is an error * writing the newline, or if a handler further down * the filter chain raises an exception. * @see org.xml.sax.ContentHandler#endDocument *//*ww w.j a v a 2 s .c o m*/ public void endDocument() throws SAXException { write('\n'); super.endDocument(); try { flush(); } catch (IOException e) { throw new SAXException(e); } }
From source file:SAXTreeValidator.java
/** * <p>/*from w w w . ja v a 2 s.c o m*/ * This will report a fatal error that has occurred; this indicates * that a rule has been broken that makes continued parsing either * impossible or an almost certain waste of time. * </p> * * @param exception <code>SAXParseException</code> that occurred. * @throws <code>SAXException</code> when things go wrong */ public void fatalError(SAXParseException exception) throws SAXException { System.out.println("**Parsing Fatal Error**\n" + " Line: " + exception.getLineNumber() + "\n" + " URI: " + exception.getSystemId() + "\n" + " Message: " + exception.getMessage()); throw new SAXException("Fatal Error encountered"); }
From source file:de.nware.app.hsDroid.provider.onlineService2Provider.java
/** * Parses the exam info./* w w w . ja va 2 s . c o m*/ * * @param htmlContentString * der/die/das html content string * @return der/die/das cursor * @throws SAXException */ private Cursor parseExamInfo(String htmlContentString) throws SAXException { final MatrixCursor cursor = new MatrixCursor(EXAM_INFOS_COLUMNS); try { ExamInfoParser handler = new ExamInfoParser(); System.out.println("content exam info: " + htmlContentString); Xml.parse(htmlContentString, handler); ExamInfo exInfos = handler.getExamInfos(); cursor.addRow(new Object[] { 0, exInfos.getSehrGutAmount(), exInfos.getGutAmount(), exInfos.getBefriedigendAmount(), exInfos.getAusreichendAmount(), exInfos.getNichtAusreichendAmount(), exInfos.getAttendees(), exInfos.getAverage() }); } catch (SAXException e) { Log.e("read:SAXException:", e.getMessage()); e.printStackTrace(); throw new SAXException(e); } return cursor; }
From source file:com.avalara.avatax.services.base.ser.BeanDeserializer.java
protected void handleMixedContent() throws SAXException { BeanPropertyDescriptor propDesc = getAnyPropertyDesc(); if (propDesc == null || val.size() == 0) { return;//from w w w .j a v a 2 s.co m } String textValue = val.toString().trim(); val.reset(); if (textValue.length() == 0) { return; } try { MessageElement[] curElements = (MessageElement[]) propDesc.get(value); int length = 0; if (curElements != null) { length = curElements.length; } MessageElement[] newElements = new MessageElement[length + 1]; if (curElements != null) { System.arraycopy(curElements, 0, newElements, 0, length); } MessageElement thisEl = new MessageElement(new org.apache.axis.message.Text(textValue)); newElements[length] = thisEl; propDesc.set(value, newElements); } catch (Exception e) { throw new SAXException(e); } }
From source file:eu.planets_project.pp.plato.xml.ProjectImporter.java
/** * Imports the XML representation of plans from the given inputstream. * /*from w w w. j a v a 2s . c o m*/ * @return list of read plans */ public List<Plan> importProjects(InputStream in) throws IOException, SAXException { String tempPath = OS.getTmpPath() + "import_xml" + System.currentTimeMillis() + "/"; File tempDir = new File(tempPath); tempDir.mkdirs(); try { String currentVersionFile = getCurrentVersionData(in, tempPath); if (currentVersionFile == null) { log.error("Failed to migrate plans."); return this.plans; } Digester digester = new Digester(); // digester.setValidating(true); StrictErrorHandler errorHandler = new StrictErrorHandler(); digester.setErrorHandler(errorHandler); digester.setNamespaceAware(true); // digester.setSchemaLanguage("http://www.w3.org/2001/XMLSchema"); // digester.setSchema("http://localhost:8080/plato/schema/plato-2.1.xsd"); /* * It is NOT sufficient to use setValidating(true) and digester.setSchema("data/schemas/plato.xsd")! * the following parameters have to be set and a special error handler is necessary */ try { digester.setFeature("http://xml.org/sax/features/validation", true); digester.setFeature("http://apache.org/xml/features/validation/schema", true); // digester.setFeature("http://xml.org/sax/features/namespaces", true); // digester.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); /* * And provide the relative path to the xsd-schema: */ digester.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); URL platoSchema = Thread.currentThread().getContextClassLoader() .getResource("data/schemas/plato-3.0.xsd"); URL wdtSchema = Thread.currentThread().getContextClassLoader() .getResource("data/schemas/planets_wdt-1.0.xsd"); digester.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "http://www.planets-project.eu/plato " + platoSchema + " http://www.planets-project.eu/wdt " + wdtSchema); //http://localhost:8080/plato/schema/planets_wdt-1.0.xsd } catch (ParserConfigurationException e) { log.debug("Cannot import XML file: Configuration of parser failed.", e); throw new SAXException("Cannot import XML file: Configuration of parser failed."); } digester.push(this); // start with a new file digester.addObjectCreate("*/plan", Plan.class); digester.addSetProperties("*/plan"); digester.addSetRoot("*/plan", "setProject"); digester.addFactoryCreate("*/changelog", ChangeLogFactory.class); digester.addSetNext("*/changelog", "setChangeLog"); digester.addObjectCreate("*/plan/state", PlanState.class); digester.addSetProperties("*/plan/state"); digester.addSetNext("*/plan/state", "setState"); digester.addObjectCreate("*/plan/properties", PlanProperties.class); digester.addSetProperties("*/plan/properties"); digester.addSetNext("*/plan/properties", "setPlanProperties"); digester.addCallMethod("*/plan/properties/description", "setDescription", 0); digester.addCallMethod("*/plan/properties/owner", "setOwner", 0); addCreateUpload(digester, "*/plan/properties/report", "setReportUpload", DigitalObject.class); digester.addObjectCreate("*/plan/basis", ProjectBasis.class); digester.addSetProperties("*/plan/basis"); digester.addSetNext("*/plan/basis", "setProjectBasis"); digester.addCallMethod("*/plan/basis/applyingPolicies", "setApplyingPolicies", 0); digester.addCallMethod("*/plan/basis/designatedCommunity", "setDesignatedCommunity", 0); digester.addCallMethod("*/plan/basis/mandate", "setMandate", 0); digester.addCallMethod("*/plan/basis/documentTypes", "setDocumentTypes", 0); digester.addCallMethod("*/plan/basis/identificationCode", "setIdentificationCode", 0); digester.addCallMethod("*/plan/basis/organisationalProcedures", "setOrganisationalProcedures", 0); digester.addCallMethod("*/plan/basis/planningPurpose", "setPlanningPurpose", 0); digester.addCallMethod("*/plan/basis/planRelations", "setPlanRelations", 0); digester.addCallMethod("*/plan/basis/preservationRights", "setPreservationRights", 0); digester.addCallMethod("*/plan/basis/referenceToAgreements", "setReferenceToAgreements", 0); // define common rule for triggers, for all */triggers/...! // also used for PlanDefinition digester.addObjectCreate("*/triggers", TriggerDefinition.class); digester.addSetNext("*/triggers", "setTriggers"); // every time a */triggers/trigger is encountered: digester.addFactoryCreate("*/triggers/trigger", TriggerFactory.class); digester.addSetNext("*/triggers/trigger", "setTrigger"); // // Policy Tree // digester.addObjectCreate("*/plan/basis/policyTree", PolicyTree.class); digester.addSetProperties("*/plan/basis/policyTree"); digester.addSetNext("*/plan/basis/policyTree", "setPolicyTree"); digester.addObjectCreate("*/plan/basis/policyTree/policyNode", PolicyNode.class); digester.addSetProperties("*/plan/basis/policyTree/policyNode"); digester.addSetNext("*/plan/basis/policyTree/policyNode", "setRoot"); digester.addObjectCreate("*/policyNode/policyNode", PolicyNode.class); digester.addSetProperties("*/policyNode/policyNode"); digester.addSetNext("*/policyNode/policyNode", "addChild"); digester.addObjectCreate("*/policyNode/policy", Policy.class); digester.addSetProperties("*/policyNode/policy"); digester.addSetNext("*/policyNode/policy", "addChild"); // // Sample Records // digester.addObjectCreate("*/plan/sampleRecords", SampleRecordsDefinition.class); digester.addSetProperties("*/plan/sampleRecords"); digester.addSetNext("*/plan/sampleRecords", "setSampleRecordsDefinition"); digester.addCallMethod("*/plan/sampleRecords/samplesDescription", "setSamplesDescription", 0); // - records digester.addObjectCreate("*/record", SampleObject.class); digester.addSetProperties("*/record"); digester.addSetNext("*/record", "addRecord"); digester.addCallMethod("*/record/description", "setDescription", 0); digester.addCallMethod("*/record/originalTechnicalEnvironment", "setOriginalTechnicalEnvironment", 0); digester.addObjectCreate("*/record/data", BinaryDataWrapper.class); digester.addSetTop("*/record/data", "setData"); digester.addCallMethod("*/record/data", "setFromBase64Encoded", 0); // set up an general rule for all jhove strings! digester.addObjectCreate("*/jhoveXML", BinaryDataWrapper.class); digester.addSetTop("*/jhoveXML", "setString"); digester.addCallMethod("*/jhoveXML", "setFromBase64Encoded", 0); digester.addCallMethod("*/jhoveXML", "setMethodName", 1, new String[] { "java.lang.String" }); digester.addObjectParam("*/jhoveXML", 0, "setJhoveXMLString"); // set up general rule for all fitsXMLs digester.addObjectCreate("*/fitsXML", BinaryDataWrapper.class); digester.addSetTop("*/fitsXML", "setString"); digester.addCallMethod("*/fitsXML", "setFromBase64Encoded", 0); digester.addCallMethod("*/fitsXML", "setMethodName", 1, new String[] { "java.lang.String" }); digester.addObjectParam("*/fitsXML", 0, "setFitsXMLString"); digester.addObjectCreate("*/record/formatInfo", FormatInfo.class); digester.addSetProperties("*/record/formatInfo"); digester.addSetNext("*/record/formatInfo", "setFormatInfo"); addCreateUpload(digester, "*/record/xcdlDescription", "setXcdlDescription", XcdlDescription.class); // - collection profile digester.addObjectCreate("*/plan/sampleRecords/collectionProfile", CollectionProfile.class); digester.addSetProperties("*/plan/sampleRecords/collectionProfile"); digester.addSetNext("*/plan/sampleRecords/collectionProfile", "setCollectionProfile"); digester.addCallMethod("*/plan/sampleRecords/collectionProfile/collectionID", "setCollectionID", 0); digester.addCallMethod("*/plan/sampleRecords/collectionProfile/description", "setDescription", 0); digester.addCallMethod("*/plan/sampleRecords/collectionProfile/numberOfObjects", "setNumberOfObjects", 0); digester.addCallMethod("*/plan/sampleRecords/collectionProfile/typeOfObjects", "setTypeOfObjects", 0); digester.addCallMethod("*/plan/sampleRecords/collectionProfile/expectedGrowthRate", "setExpectedGrowthRate", 0); digester.addCallMethod("*/plan/sampleRecords/collectionProfile/retentionPeriod", "setRetentionPeriod", 0); // requirements definition digester.addObjectCreate("*/plan/requirementsDefinition", RequirementsDefinition.class); digester.addSetProperties("*/plan/requirementsDefinition"); digester.addSetNext("*/plan/requirementsDefinition", "setRequirementsDefinition"); digester.addCallMethod("*/plan/requirementsDefinition/description", "setDescription", 0); // - uploads digester.addObjectCreate("*/plan/requirementsDefinition/uploads", ArrayList.class); digester.addSetNext("*/plan/requirementsDefinition/uploads", "setUploads"); addCreateUpload(digester, "*/plan/requirementsDefinition/uploads/upload", "add", DigitalObject.class); // alternatives digester.addObjectCreate("*/plan/alternatives", AlternativesDefinition.class); digester.addSetProperties("*/plan/alternatives"); digester.addCallMethod("*/plan/alternatives/description", "setDescription", 0); digester.addSetNext("*/plan/alternatives", "setAlternativesDefinition"); digester.addObjectCreate("*/plan/alternatives/alternative", Alternative.class); digester.addSetProperties("*/plan/alternatives/alternative"); digester.addSetNext("*/plan/alternatives/alternative", "addAlternative"); // - action digester.addObjectCreate("*/plan/alternatives/alternative/action", PreservationActionDefinition.class); digester.addSetProperties("*/plan/alternatives/alternative/action"); digester.addBeanPropertySetter("*/plan/alternatives/alternative/action/descriptor"); digester.addBeanPropertySetter("*/plan/alternatives/alternative/action/parameterInfo"); digester.addSetNext("*/plan/alternatives/alternative/action", "setAction"); digester.addCallMethod("*/plan/alternatives/alternative/description", "setDescription", 0); // - - params digester.addObjectCreate("*/plan/alternatives/alternative/action/params", LinkedList.class); digester.addSetNext("*/plan/alternatives/alternative/action/params", "setParams"); digester.addObjectCreate("*/plan/alternatives/alternative/action/params/param", Parameter.class); digester.addSetProperties("*/plan/alternatives/alternative/action/params/param"); digester.addSetNext("*/plan/alternatives/alternative/action/params/param", "add"); // - resource description digester.addObjectCreate("*/resourceDescription", ResourceDescription.class); digester.addSetProperties("*/resourceDescription"); digester.addSetNext("*/resourceDescription", "setResourceDescription"); digester.addCallMethod("*/resourceDescription/configSettings", "setConfigSettings", 0); digester.addCallMethod("*/resourceDescription/necessaryResources", "setNecessaryResources", 0); digester.addCallMethod("*/resourceDescription/reasonForConsidering", "setReasonForConsidering", 0); // - experiment digester.addObjectCreate("*/experiment", ExperimentWrapper.class); digester.addSetProperties("*/experiment"); digester.addSetNext("*/experiment", "setExperiment"); digester.addCallMethod("*/experiment/description", "setDescription", 0); digester.addCallMethod("*/experiment/settings", "setSettings", 0); addCreateUpload(digester, "*/experiment/results/result", null, DigitalObject.class); addCreateUpload(digester, "*/result/xcdlDescription", "setXcdlDescription", XcdlDescription.class); // call function addUpload of ExperimentWrapper CallMethodRule r = new CallMethodRule(1, "addResult", 2); //method with two params // every time */experiment/uploads/upload is encountered digester.addRule("*/experiment/results/result", r); // use attribute "key" as first param digester.addCallParam("*/experiment/results/result", 0, "key"); // and the object on stack (DigitalObject) as the second digester.addCallParam("*/experiment/results/result", 1, true); // addCreateUpload(digester, "*/experiment/xcdlDescriptions/xcdlDescription", null, XcdlDescription.class); // // call function addXcdlDescription of ExperimentWrapper // r = new CallMethodRule(1, "addXcdlDescription", 2); //method with two params // // every time */experiment/xcdlDescriptions/xcdlDescription is encountered // digester.addRule("*/experiment/xcdlDescriptions/xcdlDescription", r); // // use attribute "key" as first param // digester.addCallParam("*/experiment/xcdlDescriptions/xcdlDescription", 0 , "key"); // // and the object on stack (DigitalObject) as the second // digester.addCallParam("*/experiment/xcdlDescriptions/xcdlDescription",1,true); digester.addObjectCreate("*/experiment/detailedInfos/detailedInfo", DetailedExperimentInfo.class); digester.addSetProperties("*/experiment/detailedInfos/detailedInfo"); digester.addBeanPropertySetter("*/experiment/detailedInfos/detailedInfo/programOutput"); digester.addBeanPropertySetter("*/experiment/detailedInfos/detailedInfo/cpr"); // call function "addDetailedInfo" of ExperimentWrapper r = new CallMethodRule(1, "addDetailedInfo", 2); //method with two params // every time */experiment/detailedInfos/detailedInfo is encountered digester.addRule("*/experiment/detailedInfos/detailedInfo", r); // use attribute "key" as first param digester.addCallParam("*/experiment/detailedInfos/detailedInfo", 0, "key"); // and the object on stack as second parameter digester.addCallParam("*/experiment/detailedInfos/detailedInfo", 1, true); // read contained measurements: digester.addObjectCreate("*/detailedInfo/measurements/measurement", Measurement.class); digester.addSetNext("*/detailedInfo/measurements/measurement", "put"); // values are defined with wild-cards, and therefore set automatically digester.addObjectCreate("*/measurement/property", MeasurableProperty.class); digester.addSetProperties("*/measurement/property"); digester.addSetNext("*/measurement/property", "setProperty"); // scales are defined with wild-cards, and therefore set automatically /* * for each value type a set of rules * because of FreeStringValue we need to store the value as XML-element * instead of an attribute * naming them "ResultValues" wasn't nice too */ addCreateValue(digester, BooleanValue.class, "setValue"); addCreateValue(digester, FloatRangeValue.class, "setValue"); addCreateValue(digester, IntegerValue.class, "setValue"); addCreateValue(digester, IntRangeValue.class, "setValue"); addCreateValue(digester, OrdinalValue.class, "setValue"); addCreateValue(digester, PositiveFloatValue.class, "setValue"); addCreateValue(digester, PositiveIntegerValue.class, "setValue"); addCreateValue(digester, YanValue.class, "setValue"); addCreateValue(digester, FreeStringValue.class, "setValue"); // go no go decision digester.addObjectCreate("*/plan/decision", Decision.class); digester.addSetProperties("*/plan/decision"); digester.addSetNext("*/plan/decision", "setDecision"); digester.addCallMethod("*/plan/decision/actionNeeded", "setActionNeeded", 0); digester.addCallMethod("*/plan/decision/reason", "setReason", 0); digester.addFactoryCreate("*/plan/decision/goDecision", GoDecisionFactory.class); digester.addSetNext("*/plan/decision/goDecision", "setDecision"); // evaluation digester.addObjectCreate("*/plan/evaluation", Evaluation.class); digester.addSetProperties("*/plan/evaluation"); digester.addSetNext("*/plan/evaluation", "setEvaluation"); digester.addCallMethod("*/plan/evaluation/comment", "setComment", 0); // importance weighting digester.addObjectCreate("*/plan/importanceWeighting", ImportanceWeighting.class); digester.addSetProperties("*/plan/importanceWeighting"); digester.addSetNext("*/plan/importanceWeighting", "setImportanceWeighting"); digester.addCallMethod("*/plan/importanceWeighting/comment", "setComment", 0); // recommendation digester.addObjectCreate("*/plan/recommendation", RecommendationWrapper.class); digester.addSetProperties("*/plan/recommendation"); digester.addSetNext("*/plan/recommendation", "setRecommendation"); digester.addCallMethod("*/plan/recommendation/reasoning", "setReasoning", 0); digester.addCallMethod("*/plan/recommendation/effects", "setEffects", 0); // transformation digester.addObjectCreate("*/plan/transformation", Transformation.class); digester.addSetProperties("*/plan/transformation"); digester.addSetNext("*/plan/transformation", "setTransformation"); digester.addCallMethod("*/plan/transformation/comment", "setComment", 0); // Tree /* Some rules for tree parsing are necessary for importing templates too, * that's why they are added by this static method. */ ProjectImporter.addTreeParsingRulesToDigester(digester); digester.addObjectCreate("*/leaf/evaluation", HashMap.class); digester.addSetNext("*/leaf/evaluation", "setValueMap"); /* * The valueMap has an entry for each (considered) alternative ... * and for each alternative there is a list of values, one per SampleObject. * Note: The digester uses a stack, therefore the rule to put the list of values to the valueMap * must be added after the rule for adding the values to the list. */ /* * 2. and for each alternative there is a list of values, one per SampleObject */ digester.addObjectCreate("*/leaf/evaluation/alternative", Values.class); digester.addCallMethod("*/leaf/evaluation/alternative/comment", "setComment", 0); /* * for each result-type a set of rules * they are added to the valueMap by the rules above */ addCreateResultValue(digester, BooleanValue.class); addCreateResultValue(digester, FloatValue.class); addCreateResultValue(digester, FloatRangeValue.class); addCreateResultValue(digester, IntegerValue.class); addCreateResultValue(digester, IntRangeValue.class); addCreateResultValue(digester, OrdinalValue.class); addCreateResultValue(digester, PositiveFloatValue.class); addCreateResultValue(digester, PositiveIntegerValue.class); addCreateResultValue(digester, YanValue.class); addCreateResultValue(digester, FreeStringValue.class); /* * 1. The valueMap has an entry for each (considered) alternative ... */ // call put of the ValueMap (HashMap) r = new CallMethodRule(1, "put", 2); digester.addRule("*/leaf/evaluation/alternative", r); digester.addCallParam("*/leaf/evaluation/alternative", 0, "key"); digester.addCallParam("*/leaf/evaluation/alternative", 1, true); // digester.addObjectCreate("*/plan/executablePlan/planWorkflow", ExecutablePlanContentWrapper.class); // digester.addSetProperties("*/plan/executablePlan/planWorkflow"); // digester.addSetNext("*/plan/executablePlan/planWorkflow", "setRecommendation"); // Executable plan definition digester.addObjectCreate("*/plan/executablePlan", ExecutablePlanDefinition.class); digester.addSetProperties("*/plan/executablePlan"); digester.addSetNext("*/plan/executablePlan", "setExecutablePlanDefinition"); // // Import Planets executable plan if present // try { // object-create rules are called at the beginning element-tags, in the same order as defined // first create the wrapper digester.addObjectCreate("*/plan/executablePlan/planWorkflow", NodeContentWrapper.class); // then an element for workflowConf digester.addRule("*/plan/executablePlan/planWorkflow/workflowConf", new NodeCreateRule()); // CallMethod and SetNext rules are called at closing element-tags, (last in - first out!) CallMethodRule rr = new CallMethodRule(1, "setNodeContent", 2); digester.addRule("*/plan/executablePlan/planWorkflow/workflowConf", rr); // right below the wrapper is an instance of ExecutablePlanDefinition digester.addCallParam("*/plan/executablePlan/planWorkflow/workflowConf", 0, 1); // provide the name of the setter method digester.addObjectParam("*/plan/executablePlan/planWorkflow/workflowConf", 1, "setExecutablePlan"); // the generated node is not accessible as CallParam (why?!?), but available for addSetNext digester.addSetNext("*/plan/executablePlan/planWorkflow/workflowConf", "setNode"); } catch (ParserConfigurationException e) { PlatoLogger.getLogger(this.getClass()).error(e.getMessage(), e); } // // Import EPrints executable plan if present // try { digester.addObjectCreate("*/plan/executablePlan/eprintsPlan", NodeContentWrapper.class); // then an element for workflowConf digester.addRule("*/plan/executablePlan/eprintsPlan", new NodeCreateRule()); CallMethodRule rr2 = new CallMethodRule(1, "setNodeContentEPrintsPlan", 2); digester.addRule("*/plan/executablePlan/eprintsPlan", rr2); // right below the wrapper is an instance of ExecutablePlanDefinition digester.addCallParam("*/plan/executablePlan/eprintsPlan", 0, 1); // provide the name of the setter method digester.addObjectParam("*/plan/executablePlan/eprintsPlan", 1, "setEprintsExecutablePlan"); digester.addSetNext("*/plan/executablePlan/eprintsPlan", "setNode"); } catch (ParserConfigurationException e) { PlatoLogger.getLogger(this.getClass()).error(e.getMessage(), e); } digester.addCallMethod("*/plan/executablePlan/objectPath", "setObjectPath", 0); digester.addCallMethod("*/plan/executablePlan/toolParameters", "setToolParameters", 0); digester.addCallMethod("*/plan/executablePlan/triggersConditions", "setTriggersConditions", 0); digester.addCallMethod("*/plan/executablePlan/validateQA", "setValidateQA", 0); // Plan definition digester.addObjectCreate("*/plan/planDefinition", PlanDefinition.class); digester.addSetProperties("*/plan/planDefinition"); digester.addSetNext("*/plan/planDefinition", "setPlanDefinition"); digester.addCallMethod("*/plan/planDefinition/costsIG", "setCostsIG", 0); digester.addCallMethod("*/plan/planDefinition/costsPA", "setCostsPA", 0); digester.addCallMethod("*/plan/planDefinition/costsPE", "setCostsPE", 0); digester.addCallMethod("*/plan/planDefinition/costsQA", "setCostsQA", 0); digester.addCallMethod("*/plan/planDefinition/costsREI", "setCostsREI", 0); digester.addCallMethod("*/plan/planDefinition/costsRemarks", "setCostsRemarks", 0); digester.addCallMethod("*/plan/planDefinition/costsRM", "setCostsRM", 0); digester.addCallMethod("*/plan/planDefinition/costsTCO", "setCostsTCO", 0); digester.addCallMethod("*/plan/planDefinition/responsibleExecution", "setResponsibleExecution", 0); digester.addCallMethod("*/plan/planDefinition/responsibleMonitoring", "setResponsibleMonitoring", 0); digester.addObjectCreate("*/plan/planDefinition/triggers", TriggerDefinition.class); digester.addSetNext("*/plan/planDefinition/triggers", "setTriggers"); // every time a */plan/basis/triggers/trigger is encountered: digester.addFactoryCreate("*/plan/planDefinition/triggers/trigger", TriggerFactory.class); digester.addSetNext("*/plan/planDefinition/triggers/trigger", "setTrigger"); digester.setUseContextClassLoader(true); this.plans = new ArrayList<Plan>(); // finally parse the XML representation with all created rules digester.parse(new FileInputStream(currentVersionFile)); for (Plan plan : plans) { String projectName = plan.getPlanProperties().getName(); if ((projectName != null) && (!"".equals(projectName))) { /* * establish links from values to scales */ plan.getTree().initValues(plan.getAlternativesDefinition().getConsideredAlternatives(), plan.getSampleRecordsDefinition().getRecords().size(), true); /* * establish references of Experiment.uploads */ HashMap<String, SampleObject> records = new HashMap<String, SampleObject>(); for (SampleObject record : plan.getSampleRecordsDefinition().getRecords()) { records.put(record.getShortName(), record); } for (Alternative alt : plan.getAlternativesDefinition().getAlternatives()) { if ((alt.getExperiment() != null) && (alt.getExperiment() instanceof ExperimentWrapper)) { alt.setExperiment(((ExperimentWrapper) alt.getExperiment()).getExperiment(records)); } } // DESCRIBE all DigitalObjects with Jhove. for (SampleObject record : plan.getSampleRecordsDefinition().getRecords()) { if (record.isDataExistent()) { // characterise try { record.setJhoveXMLString(new JHoveAdaptor().describe(record)); } catch (Throwable e) { log.error("Error running Jhove for record " + record.getShortName() + ". " + e.getMessage(), e); } for (Alternative alt : plan.getAlternativesDefinition().getAlternatives()) { DigitalObject result = alt.getExperiment().getResults().get(record); if (result != null && result.isDataExistent()) { try { result.setJhoveXMLString(new JHoveAdaptor().describe(result)); } catch (Throwable e) { log.error( "Error running Jhove for record " + record.getShortName() + ", alternative " + alt.getName() + ". " + e.getMessage(), e); } } } } } // CHECK NUMERIC TRANSFORMER THRESHOLDS for (Leaf l : plan.getTree().getRoot().getAllLeaves()) { eu.planets_project.pp.plato.model.transform.Transformer t = l.getTransformer(); if (t != null && t instanceof NumericTransformer) { NumericTransformer nt = (NumericTransformer) t; if (!nt.checkOrder()) { StringBuffer sb = new StringBuffer("NUMERICTRANSFORMER THRESHOLD ERROR "); sb.append(l.getName()).append("::NUMERICTRANSFORMER:: "); sb.append(nt.getThreshold1()).append(" ").append(nt.getThreshold2()).append(" ") .append(nt.getThreshold3()).append(" ").append(nt.getThreshold4()) .append(" ").append(nt.getThreshold5()); log.error(sb.toString()); } } } /* * establish references to selected alternative */ HashMap<String, Alternative> alternatives = new HashMap<String, Alternative>(); for (Alternative alt : plan.getAlternativesDefinition().getAlternatives()) { alternatives.put(alt.getName(), alt); } if ((plan.getRecommendation() != null) && (plan.getRecommendation() instanceof RecommendationWrapper)) { plan.setRecommendation( ((RecommendationWrapper) plan.getRecommendation()).getRecommendation(alternatives)); } if ((plan.getState().getValue() == PlanState.ANALYSED) && ((plan.getRecommendation() == null) || (plan.getRecommendation().getAlternative() == null))) { /* * This project is NOT completely analysed */ plan.getState().setValue(PlanState.ANALYSED - 1); } } else { throw new SAXException("Could not find any project data."); } } } finally { OS.deleteDirectory(tempDir); /* * Importing big plans results in an increasing memory consumption * strange: The rise of memory consumption occurs when persisting the loaded project * NOT during parsing with the digester */ System.gc(); } return this.plans; }
From source file:com.atlassian.jira.action.admin.OfbizImportHandler.java
@Override public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (hasRootElement) { if (ENTITY_ENGINE_XML.equals(qName)) { // Write any unwritten batch entries if (createEntities) { createValue(valueBatch); valueBatch = new ArrayList<GenericValue>(); }/*from w ww .j a v a 2 s . co m*/ log.debug("Read closing ROOT element"); hasRootElement = false; } else { if (inEntity == null) { throw new SAXException("There is no entity set"); } else { if (inEntity.equals(qName)) { log.debug("Read closing " + qName + " element"); entityCount++; // We have closed the entity so you can add the generic value to the list of entities and reset the current one. if (createEntities) { if (valueBatch.size() > 64) { createValue(valueBatch); valueBatch = new ArrayList<GenericValue>(); } if (value != null) { valueBatch.add(value); } taskProgressSink.makeProgress(entityCount, "data.import.store.entities", "data.import.store.entities.progress"); } value = null; inEntity = null; } else if (!EntityImportExportExclusions.ENTITIES_EXCLUDED_FROM_IMPORT_EXPORT .contains(inEntity)) { log.debug("Read closing subelement " + qName + " of entity " + value); if (hasText) { if (log.isDebugEnabled()) { log.debug("Setting attribute " + qName + " with value " + textBuffer.toString()); } if (isBlob(value, qName)) { value.set(qName, deserialize(textBuffer.toString())); } else { // Do not trim the textBuffer as we need to preserve the leading and trailing space of the attribute value.setString(qName, textBuffer.toString()); } } } resetTextBuffer(); } } } else { throw new SAXException("How did we get here an exception should already have been thrown"); } }
From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Validate each Content block in a TAXII document (against the STIX schema files) * * @param taxiiDoc The TAXII document containing the STIX to be validated * @return true if all STIX validates, false otherwise * */// www. ja v a 2 s . c o m public static boolean validateStix(Document taxiiDoc) { try { NodeList bindings = taxiiDoc.getElementsByTagNameNS("*", "Content_Binding"); NodeList contents = taxiiDoc.getElementsByTagNameNS("*", "Content"); int numBindings = bindings.getLength(); if (numBindings != contents.getLength()) { logger.warn("STIX Validation mismatch for number of Content_Bindings and Contents. Message failed"); return false; } for (int i = 0; i < numBindings; i++) { Node binding = bindings.item(i); String stixVersion = getStixVersion(binding); logger.debug("STIX Version: " + stixVersion); Node stix = contents.item(i).getFirstChild(); Source source = new DOMSource(stix); if (!stixVersion.isEmpty() && stixVersions.contains(stixVersion)) { StixValidator sv = new StixValidator(stixVersion); List<SchemaError> errors = sv.validate(source); if (errors.size() > 0) { logger.warn("STIX Validation Errors: " + errors.size()); for (SchemaError error : errors) { logger.debug("SchemaError Category: " + error.getCategory()); logger.debug("SchemaError Message: " + error.getMessage()); } logger.warn("Message failed due to STIX " + stixVersion + " content validation errors! Please check content and try again."); return false; } } else { throw new SAXException( "Error: No STIX version number is specified by the Content_Binding urn."); } } } catch (SAXException e) { logger.debug("SAX Exception when attempting to validate STIX content. "); return false; } catch (IOException e) { logger.debug("IOException when attempting to validate STIX content. "); return false; } logger.debug("All STIX has been validated successfully."); return true; }
From source file:net.sf.jasperreports.engine.util.JRStyledTextParser.java
/** * */// w ww. java2s.c o m private void parseStyle(JRStyledText styledText, Node parentNode) throws SAXException { NodeList nodeList = parentNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.TEXT_NODE) { styledText.append(node.getNodeValue()); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_style.equals(node.getNodeName())) { NamedNodeMap nodeAttrs = node.getAttributes(); Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); if (nodeAttrs.getNamedItem(ATTRIBUTE_fontName) != null) { styleAttrs.put(TextAttribute.FAMILY, nodeAttrs.getNamedItem(ATTRIBUTE_fontName).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isBold) != null) { styleAttrs.put(TextAttribute.WEIGHT, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isBold).getNodeValue()) ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isItalic) != null) { styleAttrs.put(TextAttribute.POSTURE, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isItalic).getNodeValue()) ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isUnderline) != null) { styleAttrs.put(TextAttribute.UNDERLINE, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isUnderline).getNodeValue()) ? TextAttribute.UNDERLINE_ON : null); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isStrikeThrough) != null) { styleAttrs.put(TextAttribute.STRIKETHROUGH, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isStrikeThrough).getNodeValue()) ? TextAttribute.STRIKETHROUGH_ON : null); } if (nodeAttrs.getNamedItem(ATTRIBUTE_size) != null) { styleAttrs.put(TextAttribute.SIZE, Float.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_size).getNodeValue())); } if (nodeAttrs.getNamedItem(ATTRIBUTE_pdfFontName) != null) { styleAttrs.put(JRTextAttribute.PDF_FONT_NAME, nodeAttrs.getNamedItem(ATTRIBUTE_pdfFontName).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_pdfEncoding) != null) { styleAttrs.put(JRTextAttribute.PDF_ENCODING, nodeAttrs.getNamedItem(ATTRIBUTE_pdfEncoding).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isPdfEmbedded) != null) { styleAttrs.put(JRTextAttribute.IS_PDF_EMBEDDED, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isPdfEmbedded).getNodeValue())); } if (nodeAttrs.getNamedItem(ATTRIBUTE_forecolor) != null) { Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_forecolor).getNodeValue(), Color.black); styleAttrs.put(TextAttribute.FOREGROUND, color); } if (nodeAttrs.getNamedItem(ATTRIBUTE_backcolor) != null) { Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_backcolor).getNodeValue(), Color.black); styleAttrs.put(TextAttribute.BACKGROUND, color); } int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_bold.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_italic.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_underline.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_sup.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_sub.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_font.equalsIgnoreCase(node.getNodeName())) { NamedNodeMap nodeAttrs = node.getAttributes(); Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); if (nodeAttrs.getNamedItem(ATTRIBUTE_size) != null) { styleAttrs.put(TextAttribute.SIZE, Float.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_size).getNodeValue())); } if (nodeAttrs.getNamedItem(ATTRIBUTE_color) != null) { Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_color).getNodeValue(), Color.black); styleAttrs.put(TextAttribute.FOREGROUND, color); } if (nodeAttrs.getNamedItem(ATTRIBUTE_fontFace) != null) { String fontFaces = nodeAttrs.getNamedItem(ATTRIBUTE_fontFace).getNodeValue(); StringTokenizer t = new StringTokenizer(fontFaces, ","); while (t.hasMoreTokens()) { String face = t.nextToken().trim(); if (AVAILABLE_FONT_FACE_NAMES.contains(face)) { styleAttrs.put(TextAttribute.FAMILY, face); break; } } } int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_br.equalsIgnoreCase(node.getNodeName())) { styledText.append("\n"); int startIndex = styledText.length(); resizeRuns(styledText.getRuns(), startIndex, 1); parseStyle(styledText, node); styledText.addRun( new JRStyledText.Run(new HashMap<Attribute, Object>(), startIndex, styledText.length())); if (startIndex < styledText.length()) { styledText.append("\n"); resizeRuns(styledText.getRuns(), startIndex, 1); } } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_li.equalsIgnoreCase(node.getNodeName())) { String tmpText = styledText.getText(); if (tmpText.length() > 0 && !tmpText.endsWith("\n")) { styledText.append("\n"); } styledText.append(" \u2022 "); int startIndex = styledText.length(); resizeRuns(styledText.getRuns(), startIndex, 1); parseStyle(styledText, node); styledText.addRun( new JRStyledText.Run(new HashMap<Attribute, Object>(), startIndex, styledText.length())); // if the text in the next node does not start with a '\n', or // if the next node is not a <li /> one, we have to append a new line Node nextNode = node.getNextSibling(); String textContent = getFirstTextOccurence(nextNode); if (nextNode != null && !((nextNode.getNodeType() == Node.ELEMENT_NODE && NODE_li.equalsIgnoreCase(nextNode.getNodeName()) || (textContent != null && textContent.startsWith("\n"))))) { styledText.append("\n"); resizeRuns(styledText.getRuns(), startIndex, 1); } } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_a.equalsIgnoreCase(node.getNodeName())) { if (hyperlink == null) { NamedNodeMap nodeAttrs = node.getAttributes(); Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); hyperlink = new JRBasePrintHyperlink(); hyperlink.setHyperlinkType(HyperlinkTypeEnum.REFERENCE); styleAttrs.put(JRTextAttribute.HYPERLINK, hyperlink); if (nodeAttrs.getNamedItem(ATTRIBUTE_href) != null) { hyperlink.setHyperlinkReference(nodeAttrs.getNamedItem(ATTRIBUTE_href).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_type) != null) { hyperlink.setLinkType(nodeAttrs.getNamedItem(ATTRIBUTE_type).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_target) != null) { hyperlink.setLinkTarget(nodeAttrs.getNamedItem(ATTRIBUTE_target).getNodeValue()); } int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); hyperlink = null; } else { throw new SAXException("Hyperlink <a> tags cannot be nested."); } } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_param.equalsIgnoreCase(node.getNodeName())) { if (hyperlink == null) { throw new SAXException("Hyperlink <param> tags must appear inside an <a> tag only."); } else { NamedNodeMap nodeAttrs = node.getAttributes(); JRPrintHyperlinkParameter parameter = new JRPrintHyperlinkParameter(); if (nodeAttrs.getNamedItem(ATTRIBUTE_name) != null) { parameter.setName(nodeAttrs.getNamedItem(ATTRIBUTE_name).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_valueClass) != null) { parameter.setValueClass(nodeAttrs.getNamedItem(ATTRIBUTE_valueClass).getNodeValue()); } String strValue = node.getTextContent(); if (strValue != null) { Object value = JRValueStringUtils.deserialize(parameter.getValueClass(), strValue); parameter.setValue(value); } hyperlink.addHyperlinkParameter(parameter); } } else if (node.getNodeType() == Node.ELEMENT_NODE) { String nodeName = "<" + node.getNodeName() + ">"; throw new SAXException("Tag " + nodeName + " is not a valid styled text tag."); } } }
From source file:com.flexive.core.storage.GenericDivisionImporter.java
/** * Import data from a zip archive to a database table * * @param stmt statement to use * @param zip zip archive containing the zip entry * @param ze zip entry within the archive * @param xpath xpath containing the entries to import * @param table name of the table * @param executeInsertPhase execute the insert phase? * @param executeUpdatePhase execute the update phase? * @param updateColumns columns that should be set to <code>null</code> in a first pass (insert) * and updated to the provided values in a second pass (update), * columns that should be used in the where clause have to be prefixed * with "KEY:", to assign a default value use the expression "columnname:default value", * if the default value is "@", it will be a negative counter starting at 0, decreasing. * If the default value starts with "%", it will be set to the column following the "%" * character in the first pass * @throws Exception on errors/*from w w w. j a va 2 s. com*/ */ protected void importTable(Statement stmt, final ZipFile zip, final ZipEntry ze, final String xpath, final String table, final boolean executeInsertPhase, final boolean executeUpdatePhase, final String... updateColumns) throws Exception { //analyze the table final ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE 1=2"); StringBuilder sbInsert = new StringBuilder(500); StringBuilder sbUpdate = updateColumns.length > 0 ? new StringBuilder(500) : null; if (rs == null) throw new IllegalArgumentException("Can not analyze table [" + table + "]!"); sbInsert.append("INSERT INTO ").append(table).append(" ("); final ResultSetMetaData md = rs.getMetaData(); final Map<String, ColumnInfo> updateClauseColumns = updateColumns.length > 0 ? new HashMap<String, ColumnInfo>(md.getColumnCount()) : null; final Map<String, ColumnInfo> updateSetColumns = updateColumns.length > 0 ? new LinkedHashMap<String, ColumnInfo>(md.getColumnCount()) : null; final Map<String, String> presetColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null; //preset to a referenced column (%column syntax) final Map<String, String> presetRefColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null; final Map<String, Integer> counters = updateColumns.length > 0 ? new HashMap<String, Integer>(10) : null; final Map<String, ColumnInfo> insertColumns = new HashMap<String, ColumnInfo>( md.getColumnCount() + (counters != null ? counters.size() : 0)); int insertIndex = 1; int updateSetIndex = 1; int updateClauseIndex = 1; boolean first = true; for (int i = 0; i < md.getColumnCount(); i++) { final String currCol = md.getColumnName(i + 1).toLowerCase(); if (updateColumns.length > 0) { boolean abort = false; for (String col : updateColumns) { if (col.indexOf(':') > 0 && !col.startsWith("KEY:")) { String value = col.substring(col.indexOf(':') + 1); col = col.substring(0, col.indexOf(':')); if ("@".equals(value)) { if (currCol.equalsIgnoreCase(col)) { counters.put(col, 0); insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++)); sbInsert.append(',').append(currCol); } } else if (value.startsWith("%")) { if (currCol.equalsIgnoreCase(col)) { presetRefColumns.put(col, value.substring(1)); insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++)); sbInsert.append(',').append(currCol); // System.out.println("==> adding presetRefColumn "+col+" with value of "+value.substring(1)); } } else if (!presetColumns.containsKey(col)) presetColumns.put(col, value); } if (currCol.equalsIgnoreCase(col)) { abort = true; updateSetColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), updateSetIndex++)); break; } } if (abort) continue; } if (first) { first = false; } else sbInsert.append(','); sbInsert.append(currCol); insertColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), insertIndex++)); } if (updateColumns.length > 0 && executeUpdatePhase) { sbUpdate.append("UPDATE ").append(table).append(" SET "); int counter = 0; for (String updateColumn : updateSetColumns.keySet()) { if (counter++ > 0) sbUpdate.append(','); sbUpdate.append(updateColumn).append("=?"); } sbUpdate.append(" WHERE "); boolean hasKeyColumn = false; for (String col : updateColumns) { if (!col.startsWith("KEY:")) continue; hasKeyColumn = true; String keyCol = col.substring(4); for (int i = 0; i < md.getColumnCount(); i++) { if (!md.getColumnName(i + 1).equalsIgnoreCase(keyCol)) continue; updateClauseColumns.put(keyCol, new ColumnInfo(md.getColumnType(i + 1), updateClauseIndex++)); sbUpdate.append(keyCol).append("=? AND "); break; } } if (!hasKeyColumn) throw new IllegalArgumentException("Update columns require a KEY!"); sbUpdate.delete(sbUpdate.length() - 5, sbUpdate.length()); //remove trailing " AND " //"shift" clause indices for (String col : updateClauseColumns.keySet()) { GenericDivisionImporter.ColumnInfo ci = updateClauseColumns.get(col); ci.index += (updateSetIndex - 1); } } if (presetColumns != null) { for (String key : presetColumns.keySet()) sbInsert.append(',').append(key); } sbInsert.append(")VALUES("); for (int i = 0; i < insertColumns.size(); i++) { if (i > 0) sbInsert.append(','); sbInsert.append('?'); } if (presetColumns != null) { for (String key : presetColumns.keySet()) sbInsert.append(',').append(presetColumns.get(key)); } sbInsert.append(')'); if (DBG) { LOG.info("Insert statement:\n" + sbInsert.toString()); if (updateColumns.length > 0) LOG.info("Update statement:\n" + sbUpdate.toString()); } //build a map containing all nodes that require attributes //this allows for matching simple xpath queries like "flatstorages/storage[@name='FX_FLAT_STORAGE']/data" final Map<String, List<String>> queryAttributes = new HashMap<String, List<String>>(5); for (String pElem : xpath.split("/")) { if (!(pElem.indexOf('@') > 0 && pElem.indexOf('[') > 0)) continue; List<String> att = new ArrayList<String>(5); for (String pAtt : pElem.split("@")) { if (!(pAtt.indexOf('=') > 0)) continue; att.add(pAtt.substring(0, pAtt.indexOf('='))); } queryAttributes.put(pElem.substring(0, pElem.indexOf('[')), att); } final PreparedStatement psInsert = stmt.getConnection().prepareStatement(sbInsert.toString()); final PreparedStatement psUpdate = updateColumns.length > 0 && executeUpdatePhase ? stmt.getConnection().prepareStatement(sbUpdate.toString()) : null; try { final SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); final DefaultHandler handler = new DefaultHandler() { private String currentElement = null; private Map<String, String> data = new HashMap<String, String>(10); private StringBuilder sbData = new StringBuilder(10000); boolean inTag = false; boolean inElement = false; int counter; List<String> path = new ArrayList<String>(10); StringBuilder currPath = new StringBuilder(100); boolean insertMode = true; /** * {@inheritDoc} */ @Override public void startDocument() throws SAXException { counter = 0; inTag = false; inElement = false; path.clear(); currPath.setLength(0); sbData.setLength(0); data.clear(); currentElement = null; } /** * {@inheritDoc} */ @Override public void processingInstruction(String target, String data) throws SAXException { if (target != null && target.startsWith("fx_")) { if (target.equals("fx_mode")) insertMode = "insert".equals(data); } else super.processingInstruction(target, data); } /** * {@inheritDoc} */ @Override public void endDocument() throws SAXException { if (insertMode) LOG.info("Imported [" + counter + "] entries into [" + table + "] for xpath [" + xpath + "]"); else LOG.info("Updated [" + counter + "] entries in [" + table + "] for xpath [" + xpath + "]"); } /** * {@inheritDoc} */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { pushPath(qName, attributes); if (currPath.toString().equals(xpath)) { inTag = true; data.clear(); for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if (StringUtils.isEmpty(name)) name = attributes.getQName(i); data.put(name, attributes.getValue(i)); } } else { currentElement = qName; } inElement = true; sbData.setLength(0); } /** * Push a path element from the stack * * @param qName element name to push * @param att attributes */ private void pushPath(String qName, Attributes att) { if (att.getLength() > 0 && queryAttributes.containsKey(qName)) { String curr = qName + "["; boolean first = true; final List<String> attList = queryAttributes.get(qName); for (int i = 0; i < att.getLength(); i++) { if (!attList.contains(att.getQName(i))) continue; if (first) first = false; else curr += ','; curr += "@" + att.getQName(i) + "='" + att.getValue(i) + "'"; } curr += ']'; path.add(curr); } else path.add(qName); buildPath(); } /** * Pop the top path element from the stack */ private void popPath() { path.remove(path.size() - 1); buildPath(); } /** * Rebuild the current path */ private synchronized void buildPath() { currPath.setLength(0); for (String s : path) currPath.append(s).append('/'); if (currPath.length() > 1) currPath.delete(currPath.length() - 1, currPath.length()); // System.out.println("currPath: " + currPath); } /** * {@inheritDoc} */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (currPath.toString().equals(xpath)) { if (DBG) LOG.info("Insert [" + xpath + "]: [" + data + "]"); inTag = false; try { if (insertMode) { if (executeInsertPhase) { processColumnSet(insertColumns, psInsert); counter += psInsert.executeUpdate(); } } else { if (executeUpdatePhase) { if (processColumnSet(updateSetColumns, psUpdate)) { processColumnSet(updateClauseColumns, psUpdate); counter += psUpdate.executeUpdate(); } } } } catch (SQLException e) { throw new SAXException(e); } catch (ParseException e) { throw new SAXException(e); } } else { if (inTag) { data.put(currentElement, sbData.toString()); } currentElement = null; } popPath(); inElement = false; sbData.setLength(0); } /** * Process a column set * * @param columns the columns to process * @param ps prepared statement to use * @return if data other than <code>null</code> has been set * @throws SQLException on errors * @throws ParseException on date/time conversion errors */ private boolean processColumnSet(Map<String, ColumnInfo> columns, PreparedStatement ps) throws SQLException, ParseException { boolean dataSet = false; for (String col : columns.keySet()) { ColumnInfo ci = columns.get(col); String value = data.get(col); if (insertMode && counters != null && counters.get(col) != null) { final int newVal = counters.get(col) - 1; value = String.valueOf(newVal); counters.put(col, newVal); // System.out.println("new value for " + col + ": " + newVal); } if (insertMode && presetRefColumns != null && presetRefColumns.get(col) != null) { value = data.get(presetRefColumns.get(col)); // System.out.println("Set presetRefColumn for "+col+" to ["+value+"] from column ["+presetRefColumns.get(col)+"]"); } if (value == null) ps.setNull(ci.index, ci.columnType); else { dataSet = true; switch (ci.columnType) { case Types.BIGINT: case Types.NUMERIC: if (DBG) LOG.info("BigInt " + ci.index + "->" + new BigDecimal(value)); ps.setBigDecimal(ci.index, new BigDecimal(value)); break; case java.sql.Types.DOUBLE: if (DBG) LOG.info("Double " + ci.index + "->" + Double.parseDouble(value)); ps.setDouble(ci.index, Double.parseDouble(value)); break; case java.sql.Types.FLOAT: case java.sql.Types.REAL: if (DBG) LOG.info("Float " + ci.index + "->" + Float.parseFloat(value)); ps.setFloat(ci.index, Float.parseFloat(value)); break; case java.sql.Types.TIMESTAMP: case java.sql.Types.DATE: if (DBG) LOG.info("Timestamp/Date " + ci.index + "->" + FxFormatUtils.getDateTimeFormat().parse(value)); ps.setTimestamp(ci.index, new Timestamp(FxFormatUtils.getDateTimeFormat().parse(value).getTime())); break; case Types.TINYINT: case Types.SMALLINT: if (DBG) LOG.info("Integer " + ci.index + "->" + Integer.valueOf(value)); ps.setInt(ci.index, Integer.valueOf(value)); break; case Types.INTEGER: case Types.DECIMAL: try { if (DBG) LOG.info("Long " + ci.index + "->" + Long.valueOf(value)); ps.setLong(ci.index, Long.valueOf(value)); } catch (NumberFormatException e) { //Fallback (temporary) for H2 if the reported long is a big decimal (tree...) ps.setBigDecimal(ci.index, new BigDecimal(value)); } break; case Types.BIT: case Types.CHAR: case Types.BOOLEAN: if (DBG) LOG.info("Boolean " + ci.index + "->" + value); if ("1".equals(value) || "true".equals(value)) ps.setBoolean(ci.index, true); else ps.setBoolean(ci.index, false); break; case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BLOB: case Types.BINARY: ZipEntry bin = zip.getEntry(value); if (bin == null) { LOG.error("Failed to lookup binary [" + value + "]!"); ps.setNull(ci.index, ci.columnType); break; } try { ps.setBinaryStream(ci.index, zip.getInputStream(bin), (int) bin.getSize()); } catch (IOException e) { LOG.error("IOException importing binary [" + value + "]: " + e.getMessage(), e); } break; case Types.CLOB: case Types.LONGVARCHAR: case Types.VARCHAR: case SQL_LONGNVARCHAR: case SQL_NCHAR: case SQL_NCLOB: case SQL_NVARCHAR: if (DBG) LOG.info("String " + ci.index + "->" + value); ps.setString(ci.index, value); break; default: LOG.warn("Unhandled type [" + ci.columnType + "] for column [" + col + "]"); } } } return dataSet; } /** * {@inheritDoc} */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (inElement) sbData.append(ch, start, length); } }; handler.processingInstruction("fx_mode", "insert"); parser.parse(zip.getInputStream(ze), handler); if (updateColumns.length > 0 && executeUpdatePhase) { handler.processingInstruction("fx_mode", "update"); parser.parse(zip.getInputStream(ze), handler); } } finally { Database.closeObjects(GenericDivisionImporter.class, psInsert, psUpdate); } }