List of usage examples for java.lang NumberFormatException printStackTrace
public void printStackTrace(PrintStream s)
From source file:lu.tudor.santec.dicom.gui.header.Dcm2Xml.java
public static void main(String[] args) { CommandLine cl = parse(args);// www . j a va 2 s . com Dcm2Xml dcm2xml = new Dcm2Xml(); File ifile = new File((String) cl.getArgList().get(0)); File ofile = null; if (cl.hasOption("o")) { ofile = new File(cl.getOptionValue("o")); dcm2xml.setBaseDir(ofile.getAbsoluteFile().getParentFile()); } if (cl.hasOption("d")) { dcm2xml.setBaseDir(new File(cl.getOptionValue("d"))); } boolean x = cl.hasOption("X"); if (cl.hasOption("x")) { String[] tagStr = cl.getOptionValues("x"); int[] excludes = new int[x ? tagStr.length + 1 : tagStr.length]; for (int i = 0; i < tagStr.length; i++) { try { excludes[i] = (int) Long.parseLong(tagStr[i], 16); } catch (NumberFormatException e) { excludes[i] = Tag.forName(tagStr[i]); } } if (x) { excludes[tagStr.length] = Tag.PixelData; } dcm2xml.setExclude(excludes); } else if (x) { dcm2xml.setExclude(new int[] { Tag.PixelData }); } if (cl.hasOption("T")) { final String xslurl = cl.getOptionValue("T"); try { dcm2xml.setXslt(new URL(xslurl)); } catch (MalformedURLException e) { System.err.println("dcm2xml: invalid xsl URL: " + xslurl); System.exit(1); } dcm2xml.setXsltInc(cl.hasOption("I")); dcm2xml.setXsltParams(cl.getOptionValues("P")); } dcm2xml.setComments(cl.hasOption("C")); dcm2xml.setIndent(!cl.hasOption("c")); long t1 = System.currentTimeMillis(); try { dcm2xml.convert(ifile, ofile); } catch (TransformerConfigurationException e) { System.err.println("dcm2xml: Configuration Error: " + e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println("dcm2xml: Failed to convert " + ifile + ": " + e.getMessage()); e.printStackTrace(System.err); System.exit(1); } long t2 = System.currentTimeMillis(); if (ofile != null) System.out.println("Finished conversion of " + ifile + "to " + ofile + " in " + (t2 - t1) + "ms"); }
From source file:net.sf.webissues.core.WebIssuesRepositoryConnector.java
private Map<String, ITask> doFolder(TaskRepository repository, TaskDataCollector resultCollector, ISynchronizationSession session, IProgressMonitor monitor, WebIssuesClient client, WebIssuesFilterQueryAdapter search, Map<String, ITask> taskById, Folder folder) throws HttpException, IOException, ProtocolException, CoreException { Collection<? extends Issue> folderIssues = client.getFolderIssues(folder, 0, monitor); for (Issue issue : folderIssues) { boolean matches = true; for (Condition condition : search.getAllConditions()) { String val = condition.getValue(); Attribute attr = condition.getAttribute(); try { String issueAttributeValue = null; switch (attr.getId()) { case IssueType.PROJECT_ATTR_ID: issueAttributeValue = issue.getFolder().getProject().getName(); break; case IssueType.FOLDER_ATTR_ID: issueAttributeValue = issue.getFolder().getName(); break; case IssueType.NAME_ATTR_ID: issueAttributeValue = issue.getName(); break; case IssueType.CREATED_DATE_ATTR_ID: issueAttributeValue = String.valueOf((issue.getCreatedDate().getTimeInMillis() / 1000)); break; case IssueType.MODIFIED_DATE_ATTR_ID: issueAttributeValue = String.valueOf((issue.getModifiedDate().getTimeInMillis() / 1000)); break; case IssueType.CREATED_BY_ATTR_ID: issueAttributeValue = issue.getCreatedUser().getLogin(); break; case IssueType.MODIFIED_BY_ATTR_ID: issueAttributeValue = issue.getCreatedUser().getLogin(); break; default: issueAttributeValue = issue.get(attr); }//from ww w. j a v a 2 s. co m if (issueAttributeValue == null) { issueAttributeValue = ""; } matches = match(issue, matches, condition, val, issueAttributeValue); } catch (NumberFormatException nfe) { nfe.printStackTrace(System.out); matches = false; } if (!matches) { break; } } if (matches) { TaskData taskData = taskDataHandler.createTaskDataFromIssue(client, repository, issue, monitor); taskData.setPartial(true); if (session != null && !session.isFullSynchronization()) { if (taskById == null) { taskById = new HashMap<String, ITask>(); for (ITask task : session.getTasks()) { taskById.put(task.getTaskId(), task); } } ITask task = taskById.get(String.valueOf(issue.getId())); if (task != null && hasTaskChanged(repository, task, taskData)) { session.markStale(task); } } resultCollector.accept(taskData); } } return taskById; }
From source file:net.iponweb.hadoop.streaming.parquet.TextRecordWriterWrapper.java
@Override public void write(Text key, Text value) throws IOException { Group grp = factory.newGroup(); String[] strK = key.toString().split(TAB, -1); String[] strV = value == null ? new String[0] : value.toString().split(TAB, -1); String kv_combined[] = (String[]) ArrayUtils.addAll(strK, strV); Iterator<PathAction> ai = recorder.iterator(); Stack<Group> groupStack = new Stack<>(); groupStack.push(grp);/*from w ww.j av a2 s . c om*/ int i = 0; try { while (ai.hasNext()) { PathAction a = ai.next(); switch (a.getAction()) { case GROUPEND: grp = groupStack.pop(); break; case GROUPSTART: groupStack.push(grp); grp = grp.addGroup(a.getName()); break; case FIELD: String s = null; PrimitiveType.PrimitiveTypeName primType = a.getType(); String colName = a.getName(); if (i < kv_combined.length) s = kv_combined[i++]; if (s == null) { if (a.getRepetition() == Type.Repetition.OPTIONAL) { i++; continue; } s = primType == PrimitiveType.PrimitiveTypeName.BINARY ? "" : "0"; } // If we have 'repeated' field, assume that we should expect JSON-encoded array // Convert array and append all values int repetition = 1; boolean repeated = false; ArrayList<String> s_vals = null; if (a.getRepetition() == Type.Repetition.REPEATED) { repeated = true; s_vals = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(s); Iterator<JsonNode> itr = node.iterator(); repetition = 0; while (itr.hasNext()) { String o; switch (primType) { case BINARY: o = itr.next().getTextValue(); // No array-of-objects! break; case BOOLEAN: o = String.valueOf(itr.next().getBooleanValue()); break; default: o = String.valueOf(itr.next().getNumberValue()); } s_vals.add(o); repetition++; } } for (int j = 0; j < repetition; j++) { if (repeated) // extract new s s = s_vals.get(j); try { switch (primType) { case INT32: grp.append(colName, new Double(Double.parseDouble(s)).intValue()); break; case INT64: case INT96: grp.append(colName, new Double(Double.parseDouble(s)).longValue()); break; case DOUBLE: grp.append(colName, Double.parseDouble(s)); break; case FLOAT: grp.append(colName, Float.parseFloat(s)); break; case BOOLEAN: grp.append(colName, s.equalsIgnoreCase("true") || s.equals("1")); break; case BINARY: grp.append(colName, Binary.fromString(s)); break; default: throw new RuntimeException("Can't handle type " + primType); } } catch (NumberFormatException e) { grp.append(colName, 0); } } } } realWriter.write(null, (SimpleGroup) grp); } catch (InterruptedException e) { Thread.interrupted(); throw new IOException(e); } catch (Exception e) { ByteArrayOutputStream out = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(out)); throw new RuntimeException("Failed on record " + grp + ", schema=" + schema + ", path action=" + recorder + " exception = " + e.getClass() + ", msg=" + e.getMessage() + ", cause=" + e.getCause() + ", trace=" + out.toString()); } }
From source file:dk.dma.ais.abnormal.analyzer.AbnormalAnalyzerAppModule.java
private List<BoundingBox> parseGeoMaskXmlInputStream(InputStream is) { List<BoundingBox> boundingBoxes = new ArrayList<>(); try {/* w ww. j a va 2 s . c o m*/ DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = documentBuilder.parse(is); document.normalizeDocument(); final NodeList areaPolygons = document.getElementsByTagName("area_polygon"); final int numAreaPolygons = areaPolygons.getLength(); for (int i = 0; i < numAreaPolygons; i++) { Node areaPolygon = areaPolygons.item(i); LOG.debug( "XML reading area_polygon " + areaPolygon.getAttributes().getNamedItem("name").toString()); NodeList polygons = areaPolygon.getChildNodes(); int numPolygons = polygons.getLength(); for (int p = 0; p < numPolygons; p++) { Node polygon = polygons.item(p); if (polygon instanceof Element) { NodeList items = polygon.getChildNodes(); int numItems = items.getLength(); BoundingBox boundingBox = null; try { for (int j = 0; j < numItems; j++) { Node item = items.item(j); if (item instanceof Element) { final double lat = Double .parseDouble(item.getAttributes().getNamedItem("lat").getNodeValue()); final double lon = Double .parseDouble(item.getAttributes().getNamedItem("lon").getNodeValue()); if (boundingBox == null) { boundingBox = BoundingBox.create(Position.create(lat, lon), Position.create(lat, lon), CoordinateSystem.CARTESIAN); } else { boundingBox = boundingBox.include(Position.create(lat, lon)); } } } LOG.info("Blocking messages in bbox " + areaPolygon.getAttributes().getNamedItem("name").toString() + ": " + boundingBox.toString() + " " + (boundingBox.getMaxLat() - boundingBox.getMinLat()) + " " + (boundingBox.getMaxLon() - boundingBox.getMinLon())); boundingBoxes.add(boundingBox); } catch (NumberFormatException e) { LOG.error(e.getMessage(), e); } } } } } catch (ParserConfigurationException e) { e.printStackTrace(System.err); } catch (SAXException e) { e.printStackTrace(System.err); } catch (IOException e) { e.printStackTrace(System.err); } return boundingBoxes; }
From source file:com.blackducksoftware.integration.hub.jenkins.PostBuildScanDescriptor.java
public void updateByXml(final Source source) throws IOException, TransformerException, ParserConfigurationException, SAXException { final TransformerFactory tFactory = TransformerFactory.newInstance(); final Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); final StreamResult result = new StreamResult(byteOutput); transformer.transform(source, result); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final InputSource is = new InputSource(new StringReader(byteOutput.toString("UTF-8"))); final Document doc = builder.parse(is); final HubServerInfo serverInfo = new HubServerInfo(); if (doc.getElementsByTagName("hubServerInfo").getLength() > 0) { final Node hubServerInfoNode = doc.getElementsByTagName("hubServerInfo").item(0); if (hubServerInfoNode != null && hubServerInfoNode.getNodeType() == Node.ELEMENT_NODE) { final Element hubServerInfoElement = (Element) hubServerInfoNode; final Node credentialsNode = hubServerInfoElement.getElementsByTagName("credentialsId").item(0); String credentialId = ""; if (credentialsNode != null && credentialsNode.getChildNodes() != null && credentialsNode.getChildNodes().item(0) != null) { credentialId = credentialsNode.getChildNodes().item(0).getNodeValue(); if (credentialId != null) { credentialId = credentialId.trim(); }//from w w w .j a v a 2 s . c om } final Node serverUrlNode = hubServerInfoElement.getElementsByTagName("serverUrl").item(0); String serverUrl = ""; if (serverUrlNode != null && serverUrlNode.getChildNodes() != null && serverUrlNode.getChildNodes().item(0) != null) { serverUrl = serverUrlNode.getChildNodes().item(0).getNodeValue(); if (serverUrl != null) { serverUrl = serverUrl.trim(); } } final Node timeoutNode = hubServerInfoElement.getElementsByTagName("hubTimeout").item(0); String hubTimeout = String.valueOf(HubServerInfo.getDefaultTimeout()); // default timeout if (timeoutNode != null && timeoutNode.getChildNodes() != null && timeoutNode.getChildNodes().item(0) != null) { hubTimeout = timeoutNode.getChildNodes().item(0).getNodeValue(); if (hubTimeout != null) { hubTimeout = hubTimeout.trim(); } } serverInfo.setCredentialsId(credentialId); serverInfo.setServerUrl(serverUrl); int serverTimeout = 300; try { serverTimeout = Integer.valueOf(hubTimeout); } catch (final NumberFormatException e) { System.err.println( "Could not convert the provided timeout : " + hubTimeout + ", to an int value."); e.printStackTrace(System.err); } serverInfo.setTimeout(serverTimeout); } } hubServerInfo = serverInfo; save(); HubServerInfoSingleton.getInstance().setServerInfo(hubServerInfo); }
From source file:net.sf.webphotos.gui.util.FtpClient.java
/** * Executa o comando FTP. Utiliza o mtodo * {@link net.sf.webphotos.sync.Sync#loadSyncCache() loadSyncCache}() para * fazer o load do arquivos com os comandos de FTP. Checa se existem * comandos a executar, caso positivo, tenta a conexo com FTP e executa os * comandos (UPLOAD, DELETE ou DOWNLOAD). *//*from w w w . j av a 2 s. co m*/ @Override public void run() { String acao; String albumID; String arquivo; long tamanho; String arqOrigem; String arqDestino; Object streamOrigem = null; Object streamDestino = null; String ultimoID = ""; int i, j = 0; String diretorioDownload = null; // loadSyncCache arquivo ftp.loadSyncCache(); modeloTabela.refresh(ftp.getListaArquivos()); modeloTabela.fireTableDataChanged(); // tem algum comando executar ? if (tabela.getRowCount() == 0) { ftp.disconnect("No h comandos ftp"); return; } // tenta a conexao com FTP if (!ftp.connect()) { return; } preProcessBatch(); modeloTabela.refresh(ftp.getListaArquivos()); modeloTabela.fireTableDataChanged(); barra.setMaximum(Integer.parseInt(Long.toString(totalBytes))); // executa os comandos for (i = 0; i < tabela.getRowCount(); i++) { lblArquivos.setText(i + 1 + " / " + tabela.getRowCount()); tabela.setRowSelectionInterval(i, i); tabela.scrollRectToVisible(tabela.getCellRect(i + 1, 0, true)); tabela.repaint(); acao = tabela.getValueAt(i, 1).toString(); albumID = tabela.getValueAt(i, 2).toString(); arquivo = tabela.getValueAt(i, 4).toString(); // ajusta o diretrio para /ftpRoot/albumID // recebe a lista de arquivos if (!ultimoID.equals(albumID)) { Util.log("Mudando para o diretrio " + albumID); try { ftp.cd(albumID); remoteFiles = ftp.listFiles(); diretorioDownload = null; } catch (IOException ioE) { Util.log("[FtpClient.run]/ERRO: comando no foi aceito ao listar o diretrio " + albumID + " desconectando"); ftp.disconnect("no foi possivel entrar no diretorio"); } catch (SyncException se) { Util.log(se.getMessage()); ftp.disconnect("no foi possivel entrar no diretorio"); } } // UPLOAD switch (acao) { case "enviar": if (diretorioDownload == null) { diretorioDownload = albunsRoot.getAbsolutePath() + File.separator + albumID; } arqOrigem = diretorioDownload + File.separator + arquivo; Util.out.println(arqOrigem + " -> " + arquivo); try { streamOrigem = new FileInputStream(arqOrigem); streamDestino = new BufferedOutputStream(ftp.storeFileStream(arquivo), ftp.getBufferSize()); this.transfereArquivo((InputStream) streamOrigem, (OutputStream) streamDestino, Long.parseLong(tabela.getValueAt(i, 5).toString())); tabela.setValueAt("ok", i, 0); } catch (FileNotFoundException ioE) { Util.log("[FtpClient.run]/AVISO: " + arqOrigem + " no foi encontrado."); tabela.setValueAt("ok - ne", i, 0); } catch (IOException ioE) { Util.log("[FtpClient.run]/ERRO: erro na transmisso de " + arqOrigem); ioE.printStackTrace(Util.out); tabela.setValueAt("erro", i, 0); } catch (NumberFormatException e) { Util.err.println("Erro inexperado: " + e.getMessage()); e.printStackTrace(Util.out); tabela.setValueAt("erro", i, 0); } finally { try { ftp.printWorkingDirectory(); } catch (IOException e) { } try { ((OutputStream) streamDestino).close(); ((InputStream) streamOrigem).close(); } catch (Exception e) { } } posTransfer(i); // DELETE break; case "apagar": // apaga o diretorio inteiro if (arquivo.equals("* todos")) { try { for (FTPFile remote : remoteFiles) { ftp.deleteFile(remote.getName()); Util.log("Removendo arquivo remoto " + remote.getName()); transmitido += remote.getSize(); Util.out.println("Processado " + transmitido + " de " + totalBytes); barra.setValue((int) transmitido); lblKbytes.setText(Math.round((float) transmitido / 1024) + " Kb"); } // Volta para o diretrio principal ftp.changeWorkingDirectory(ftpRoot); // finalmente remove o diretorio ftp.removeDirectory(albumID); tabela.setValueAt("ok", i, 0); } catch (Exception e) { tabela.setValueAt("erro", i, 0); log.error(e); } // apaga somente uma foto } else { for (FTPFile remote : remoteFiles) { if (remote.getName().equals(arquivo)) { remoteFile = remote; break; } } //remoteFile=RemoteFile.findRemoteFile(remoteFiles,arquivo); if (remoteFile == null) { tabela.setValueAt("ok - ne", i, 0); } else { tabela.setValueAt(Long.toString(remoteFile.getSize()), i, 5); try { ftp.deleteFile(arquivo); tabela.setValueAt("ok", i, 0); posTransfer(i); } catch (IOException | NumberFormatException e) { tabela.setValueAt("erro", i, 0); } } } // DOWNLOAD - recebe os arquivos (pr listado e calculado) break; // fim if case "receber": try { // cada vez que muda o diretrio, a varivel diretrioDownload nula if (diretorioDownload == null) { diretorioDownload = albunsRoot.getAbsolutePath() + File.separator + albumID; File temp = new File(diretorioDownload); if (!temp.isDirectory()) { temp.mkdir(); Util.log("Criando diretrio " + diretorioDownload); } temp = null; } arqDestino = diretorioDownload + File.separator + arquivo; Util.out.println(arquivo + " -> " + arqDestino); streamOrigem = new BufferedInputStream(ftp.retrieveFileStream(arquivo), ftp.getBufferSize()); streamDestino = new FileOutputStream(arqDestino); this.transfereArquivo((InputStream) streamOrigem, (OutputStream) streamDestino, Long.parseLong(tabela.getValueAt(i, 5).toString())); tabela.setValueAt("ok", i, 0); // calcula porcentagem e atualiza barra posTransfer(i); } catch (IOException ioE) { Util.err.println("Erro de transmisso: " + ioE.getMessage() + " " + ((CopyStreamException) ioE).getIOException().getMessage()); tabela.setValueAt("erro", i, 0); log.error(ioE); } catch (NumberFormatException e) { Util.err.println("Erro: "); log.error(e); tabela.setValueAt("erro", i, 0); } finally { try { ftp.printWorkingDirectory(); } catch (IOException e) { } try { ((InputStream) streamOrigem).close(); ((OutputStream) streamDestino).close(); } catch (IOException e) { } } break; } ultimoID = albumID; } // fim for ftp.disconnect("transmisso terminada"); }
From source file:InlineSchemaValidator.java
/** Main program entry point. */ public static void main(String[] argv) { // is there anything to do? if (argv.length == 0) { printUsage();/*from w w w. j a v a2 s . c o m*/ System.exit(1); } // variables Vector schemas = null; Vector instances = null; HashMap prefixMappings = null; HashMap uriMappings = null; String docURI = argv[argv.length - 1]; String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE; int repetition = DEFAULT_REPETITION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; boolean memoryUsage = DEFAULT_MEMORY_USAGE; // process arguments for (int i = 0; i < argv.length - 1; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("l")) { // get schema language name if (++i == argv.length) { System.err.println("error: Missing argument to -l option."); } else { schemaLanguage = argv[i]; } continue; } if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number (" + number + ")."); } continue; } if (arg.equals("-a")) { // process -a: xpath expressions for schemas if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: xpath expressions for instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (arg.equals("-nm")) { String prefix; String uri; while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-") && !(uri = argv[i + 2]).startsWith("-")) { if (prefixMappings == null) { prefixMappings = new HashMap(); uriMappings = new HashMap(); } prefixMappings.put(prefix, uri); HashSet prefixes = (HashSet) uriMappings.get(uri); if (prefixes == null) { prefixes = new HashSet(); uriMappings.put(uri, prefixes); } prefixes.add(prefix); i += 2; } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option (" + option + ")."); continue; } } try { // Create new instance of inline schema validator. InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings, uriMappings); // Parse document containing schemas and validation roots DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(inlineSchemaValidator); Document doc = db.parse(docURI); // Create XPath factory for selecting schema and validation roots XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(inlineSchemaValidator); // Select schema roots from the DOM NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0]; for (int i = 0; i < schemaNodes.length; ++i) { XPathExpression xpathSchema = xpath.compile((String) schemas.elementAt(i)); schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET); } // Select validation roots from the DOM NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0]; for (int i = 0; i < instanceNodes.length; ++i) { XPathExpression xpathInstance = xpath.compile((String) instances.elementAt(i)); instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET); } // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage); factory.setErrorHandler(inlineSchemaValidator); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Build Schema from sources Schema schema; { DOMSource[] sources; int size = 0; for (int i = 0; i < schemaNodes.length; ++i) { size += schemaNodes[i].getLength(); } sources = new DOMSource[size]; if (size == 0) { schema = factory.newSchema(); } else { int count = 0; for (int i = 0; i < schemaNodes.length; ++i) { NodeList nodeList = schemaNodes[i]; int nodeListLength = nodeList.getLength(); for (int j = 0; j < nodeListLength; ++j) { sources[count++] = new DOMSource(nodeList.item(j)); } } schema = factory.newSchema(sources); } } // Setup validator and input source. Validator validator = schema.newValidator(); validator.setErrorHandler(inlineSchemaValidator); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } // Validate instance documents for (int i = 0; i < instanceNodes.length; ++i) { NodeList nodeList = instanceNodes[i]; int nodeListLength = nodeList.getLength(); for (int j = 0; j < nodeListLength; ++j) { DOMSource source = new DOMSource(nodeList.item(j)); source.setSystemId(docURI); inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage); } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } }
From source file:gr.forth.ics.isl.Index.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .j ava2 s . co m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String id = request.getParameter("id"); String sourceFile = request.getParameter("sourceFile"); // String sourceFilename = request.getParameter("sourceFilename"); String generator = request.getParameter("generator"); String uuidSize = request.getParameter("uuidSize"); String outputFormat = request.getParameter("output"); int uuidSizeInt = 2; if (uuidSize != null) { try { uuidSizeInt = Integer.parseInt(uuidSize); } catch (NumberFormatException ex) { } } Mapper map = new Mapper(); try { String serverIP = request.getLocalAddr(); if (serverIP.equals("0:0:0:0:0:0:0:1")) {//Localhost serverIP = "localhost"; } System.out.println("http://" + serverIP + ":" + request.getLocalPort() + "/3MEditor/Services?id=" + id + "&output=text/xml&method=export"); X3MLEngine engine = map.engine("http://" + serverIP + ":" + request.getLocalPort() + "/3MEditor/Services?id=" + id + "&output=text/xml&method=export"); X3MLEngine.Output output = engine.execute(map.documentFromString(sourceFile), map.policy(generator, uuidSizeInt)); if (X3MLEngine.exceptionMessagesList.length() > 0) { out.println(X3MLEngine.exceptionMessagesList .replaceAll("(?<!\\A)eu\\.delving\\.x3ml\\.X3MLEngine\\$X3MLException:", "\n$0")); } if (outputFormat == null || outputFormat.equals("RDF/XML")) { OutputStream os = new WriterOutputStream(out); PrintStream ps = new PrintStream(os); output.writeXML(ps); } else if (outputFormat.equals("N-triples")) { out.println(output.toString()); } else if (outputFormat.equals("Turtle")) { OutputStream os = new WriterOutputStream(out); PrintStream ps = new PrintStream(os); output.write(ps, "text/turtle"); } } catch (X3MLEngine.X3MLException ex) { ex.printStackTrace(out); } catch (Exception ex) { ex.printStackTrace(out); } out.close(); }
From source file:com.funambol.email.content.ContentProviderServlet.java
/** * Print a debug page in the response/*from w w w. java 2 s .c o m*/ * @param request The HttpServletRequest * @param response The HttpServletResponse * @throws java.io.IOException */ private void printDebugPage(HttpServletRequest request, HttpServletResponse response) throws IOException { ContentProviderManager contentServiceManager = new ContentProviderManager(); PrintWriter out = response.getWriter(); try { response.setContentType("text/html;charset=UTF-8"); out.println("<html>"); out.println("<head>"); out.println("<title>Content Provider Errorr</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet AttachmentProvider at " + request.getContextPath() + "</h1>"); String authToken = request.getParameter(PARAMETER_AUTH); if (authToken == null || "".equals(authToken)) { out.println("<p>Empty authorization token name received</p>"); return; } String username = request.getParameter(PARAMETER_USER); if (username == null || "".equals(username)) { out.println("<p>Empty user name received</p>"); return; } String attachIdx = request.getParameter(PARAMETER_INDEX); if (attachIdx == null || "".equals(attachIdx)) { out.println("<p>Empty Attachment id received</p>"); return; } int attachmentIndex = 0; try { attachmentIndex = Integer.parseInt(attachIdx); } catch (NumberFormatException ex) { out.println("<p>NumberFormatException: " + ex.toString() + "</p>"); return; } out.println("<p>Authorization token: " + authToken + "</p>"); out.println("<p>User name: " + username + "</p>"); out.println("<p>Attachment index: " + attachIdx + "</p>"); MailServerAccount mailServerAccount = contentServiceManager.retrieveMailServerAccount(username); if (mailServerAccount == null) { out.println("<p>Unable to retrieve the mail server account for user: " + username + "</p>"); return; } out.println("<p>Retrieved mail server account</p>"); String mailServerProtocol = mailServerAccount.getMailServer().getProtocol(); if (mailServerProtocol == null || "".equals(mailServerProtocol)) { out.println("<p>Invalid mail server protocol</p>"); return; } out.println("<p>Mail server protocol: " + mailServerProtocol + "</p>"); contentServiceManager.openConnection(mailServerAccount); out.println("<p>Connection opened</p>"); String mailGUID = contentServiceManager.authorize(username, authToken); if (mailGUID == null) { out.println("<p>Request not authorized</p>"); return; } String messageid = Utility.getKeyPart(mailGUID, 2); if (messageid == null || "".equals(messageid)) { out.println("<p>Unable to retrieve the message id from the GUID</p>"); return; } out.println("<p>Mail message id: " + messageid + "</p>"); Message message = contentServiceManager.getMessage(messageid); if (message == null) { out.println("<p>Unable to retrieve the mail message</p>"); return; } out.println("<p>Mail message retrieved</p>"); List partsList = MessageParser.getAllPartsOfMessage(message, false); if (partsList != null && partsList.size() > attachmentIndex) { InternalPart part = (InternalPart) partsList.get(attachmentIndex); if (part == null || part.getDHandler() == null || part.getDHandler().getInputStream() == null) { out.println("<p>Unable to retrieve the mail part</p>"); return; } } } catch (EmailAccessException ex) { out.println("<p>EmailAccessException: " + ex.toString() + "</p>"); } catch (EntityException ex) { out.println("<p>EntityException: "); ex.printStackTrace(out); out.println("</p>"); } catch (Exception ex) { out.println("<p>Exception: " + ex.toString() + "</p>"); } catch (Throwable ex) { out.println("<p>Throwable: " + ex.toString() + "</p>"); } finally { try { contentServiceManager.closeConnection(); } catch (ContentProviderException ex) { out.println("<p>AttachmentException: " + ex.toString() + "</p>"); } out.println("<p>Connection closed</p>"); out.println("</body>"); out.println("</html>"); out.flush(); out.close(); // // Since the session is not really useful, we force that a request is // served by a new session and that a session serves just one request. // In such way, we don't have useless sessions. As drawback for every // request a new session is created. // Comparing advantages vs drawbacks, we prefer one session - one request. // request.getSession().invalidate(); } }
From source file:de.interactive_instruments.ShapeChange.Target.ArcGISWorkspace.ArcGISWorkspace.java
public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly) throws ShapeChangeAbortException { appSchemaPkg = p;//from ww w .ja v a2s . c om model = m; options = o; result = r; // initialize mappings this.lengthMappingByTypeName.put("esriFieldTypeInteger", 0); this.lengthMappingByTypeName.put("esriFieldTypeDouble", 0); this.lengthMappingByTypeName.put("esriFieldTypeDate", 0); this.precisionMappingByTypeName.put("esriFieldTypeString", 0); this.precisionMappingByTypeName.put("esriFieldTypeInteger", 9); this.precisionMappingByTypeName.put("esriFieldTypeDouble", 10); this.precisionMappingByTypeName.put("esriFieldTypeDate", 0); this.scaleMappingByTypeName.put("esriFieldTypeString", 0); this.scaleMappingByTypeName.put("esriFieldTypeInteger", 0); this.scaleMappingByTypeName.put("esriFieldTypeDouble", 6); this.scaleMappingByTypeName.put("esriFieldTypeDate", 0); // get output location outputDirectory = options.parameter(this.getClass().getName(), PARAM_OUTPUT_DIR); if (outputDirectory == null) outputDirectory = options.parameter("outputDirectory"); if (outputDirectory == null) outputDirectory = options.parameter("."); String outputFilename = appSchemaPkg.name().replace("/", "_").replace(" ", "_") + ".eap"; // parse default length parameter String defaultLengthParamValue = options.parameter(this.getClass().getName(), PARAM_LENGTH_TAGGED_VALUE_DEFAULT); if (defaultLengthParamValue != null) { try { int length = Integer.parseInt(defaultLengthParamValue); this.lengthTaggedValueDefault = length; } catch (NumberFormatException e) { result.addError(this, 13); } } // Check if we can use the output directory; create it if it // does not exist outputDirectoryFile = new File(outputDirectory); boolean exi = outputDirectoryFile.exists(); if (!exi) { try { FileUtils.forceMkdir(outputDirectoryFile); } catch (IOException e) { result.addError(this, 5, e.getMessage()); e.printStackTrace(System.err); } exi = outputDirectoryFile.exists(); } boolean dir = outputDirectoryFile.isDirectory(); boolean wrt = outputDirectoryFile.canWrite(); boolean rea = outputDirectoryFile.canRead(); if (!exi || !dir || !wrt || !rea) { result.addFatalError(this, 1, outputDirectory); throw new ShapeChangeAbortException(); } File outputFile = new File(outputDirectoryFile, outputFilename); // check if output file already exists - if so, attempt to delete it exi = outputFile.exists(); if (exi) { result.addInfo(this, 2, outputFilename, outputDirectory); try { FileUtils.forceDelete(outputFile); result.addInfo(this, 3); } catch (IOException e) { result.addInfo(this, 4, e.getMessage()); e.printStackTrace(System.err); } } // read workspace template // String pathToWorkspaceTemplateFileInput = options.parameter(this // .getClass().getName(), PARAM_WORKSPACE_TEMPLATE); // File workspaceTemplateFileInput = null; // // if (pathToWorkspaceTemplateFileInput == null) { // result.addFatalError(this, 6); // throw new ShapeChangeAbortException(); // } else { // workspaceTemplateFileInput = new File( // pathToWorkspaceTemplateFileInput); // if (!workspaceTemplateFileInput.canRead()) { // result.addFatalError(this, 7, pathToWorkspaceTemplateFileInput); // throw new ShapeChangeAbortException(); // } // } workspaceTemplateFilePath = options.parameter(this.getClass().getName(), PARAM_WORKSPACE_TEMPLATE); if (workspaceTemplateFilePath == null) { workspaceTemplateFilePath = options.parameter(PARAM_WORKSPACE_TEMPLATE); } // if no path is provided, use the directory of the default template if (workspaceTemplateFilePath == null) { workspaceTemplateFilePath = WORKSPACE_TEMPLATE_URL; result.addInfo(this, 9, PARAM_WORKSPACE_TEMPLATE, WORKSPACE_TEMPLATE_URL); } // copy template file either from remote or local URI if (workspaceTemplateFilePath.toLowerCase().startsWith("http")) { try { URL templateUrl = new URL(workspaceTemplateFilePath); FileUtils.copyURLToFile(templateUrl, outputFile); } catch (MalformedURLException e1) { result.addFatalError(this, 6, workspaceTemplateFilePath, e1.getMessage()); throw new ShapeChangeAbortException(); } catch (IOException e2) { result.addFatalError(this, 8, e2.getMessage()); throw new ShapeChangeAbortException(); } } else { File workspacetemplate = new File(workspaceTemplateFilePath); if (workspacetemplate.exists()) { try { FileUtils.copyFile(workspacetemplate, outputFile); } catch (IOException e) { result.addFatalError(this, 8, e.getMessage()); throw new ShapeChangeAbortException(); } } else { result.addFatalError(this, 7, workspacetemplate.getAbsolutePath()); throw new ShapeChangeAbortException(); } } // File workspaceTemplateFileInput = new File( // workspaceTemplateFilePath); // if (!workspaceTemplateFileInput.canRead()) { // result.addFatalError(this, 7, pathToWorkspaceTemplateFileInput); // throw new ShapeChangeAbortException(); // } // // copy template to outputFile // try { // FileUtils.copyFile(workspaceTemplateFileInput, outputFile); // } catch (IOException e) { // result.addFatalError(this, 8, e.getMessage()); // e.printStackTrace(System.err); // throw new ShapeChangeAbortException(); // } // connect to EA repository in outputFile absolutePathOfOutputEAPFile = outputFile.getAbsolutePath(); rep = new Repository(); if (!rep.OpenFile(absolutePathOfOutputEAPFile)) { String errormsg = rep.GetLastError(); r.addError(null, 30, errormsg, outputFilename); rep = null; throw new ShapeChangeAbortException(); } // get template packages rep.RefreshModelView(0); Collection<Package> c = rep.GetModels(); Package root = c.GetAt((short) 0); Collection<Package> modelPkgs = root.GetPackages(); if (modelPkgs.GetCount() == 0 || !modelPkgs.GetAt((short) 0).GetStereotypeEx().equalsIgnoreCase("ArcGIS")) { result.addError(this, 9); throw new ShapeChangeAbortException(); } else { Package workspacePkg = modelPkgs.GetAt((short) 0); this.workspacePkgId = workspacePkg.GetPackageID(); // eaPkgByModelPkg.put(appSchemaPkg, workspacePkg); } Integer features = EAModelUtil.getEAChildPackageByName(rep, workspacePkgId, TEMPLATE_PKG_FEATURES_NAME); if (features == null) { result.addError(this, 102, TEMPLATE_PKG_FEATURES_NAME); throw new ShapeChangeAbortException(); } else { this.featuresPkgId = features; this.eaPkgIdByModelPkg_byWorkspaceSubPkgId.put(featuresPkgId, new HashMap<PackageInfo, Integer>()); } Integer domains = EAModelUtil.getEAChildPackageByName(rep, workspacePkgId, TEMPLATE_PKG_DOMAINS_NAME); if (domains == null) { result.addError(this, 102, TEMPLATE_PKG_DOMAINS_NAME); throw new ShapeChangeAbortException(); } else { this.domainsPkgId = domains; this.eaPkgIdByModelPkg_byWorkspaceSubPkgId.put(domainsPkgId, new HashMap<PackageInfo, Integer>()); } Integer tables = EAModelUtil.getEAChildPackageByName(rep, workspacePkgId, TEMPLATE_PKG_TABLES_NAME); if (tables == null) { result.addError(this, 102, TEMPLATE_PKG_TABLES_NAME); throw new ShapeChangeAbortException(); } else { this.tablesPkgId = tables; this.eaPkgIdByModelPkg_byWorkspaceSubPkgId.put(tablesPkgId, new HashMap<PackageInfo, Integer>()); } Integer assocClasses = EAModelUtil.getEAChildPackageByName(rep, workspacePkgId, TEMPLATE_PKG_ASSOCIATION_CLASSES_NAME); if (assocClasses == null) { result.addError(this, 102, TEMPLATE_PKG_ASSOCIATION_CLASSES_NAME); throw new ShapeChangeAbortException(); } else { this.assocClassesPkgId = assocClasses; this.eaPkgIdByModelPkg_byWorkspaceSubPkgId.put(assocClassesPkgId, new HashMap<PackageInfo, Integer>()); } ProcessConfiguration pc = o.getCurrentProcessConfig(); // parse map entries List<ProcessMapEntry> mapEntries = pc.getMapEntries(); Map<String, ProcessMapEntry> mes = new HashMap<String, ProcessMapEntry>(); for (ProcessMapEntry pme : mapEntries) { // TODO ignores value of 'rule' attribute in map entry, so if there // were map entries for different rules with same 'type' attribute // value, this needs to be updated if (pme.hasTargetType()) { mes.put(pme.getType(), pme); } else { result.addError(this, 11, pme.getType()); } } this.processMapEntries = mes; // initialize set with esri types suited for numeric range constraints esriTypesSuitedForRangeConstraint.add("esriFieldTypeInteger"); esriTypesSuitedForRangeConstraint.add("esriFieldTypeDouble"); // parse numeric range delta parameter String numRangeDeltaParamValue = options.parameter(this.getClass().getName(), PARAM_VALUE_RANGE_DELTA); if (numRangeDeltaParamValue != null) { try { double delta = Double.parseDouble(numRangeDeltaParamValue); this.numRangeDelta = delta; } catch (NumberFormatException e) { result.addError(this, 12); } } // change the default documentation template? documentationTemplate = options.parameter(this.getClass().getName(), PARAM_DOCUMENTATION_TEMPLATE); documentationNoValue = options.parameter(this.getClass().getName(), PARAM_DOCUMENTATION_NOVALUE); }