List of usage examples for java.net URISyntaxException printStackTrace
public void printStackTrace()
From source file:org.mustard.util.HttpManager.java
private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam, File attachment) throws IOException, MustardException, AuthException { URI uri;/* w w w. j ava 2s.c om*/ try { uri = new URI(url); } catch (URISyntaxException e) { throw new IOException("Invalid URL."); } if (MustardApplication.DEBUG) Log.d("HTTPManager", "Requesting " + uri); HttpPost post = new HttpPost(uri); HttpResponse response; // create the multipart request and add the parts to it MultipartEntity requestContent = new MultipartEntity(); long len = attachment.length(); InputStream ins = new FileInputStream(attachment); InputStreamEntity ise = new InputStreamEntity(ins, -1L); byte[] data = EntityUtils.toByteArray(ise); String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG; requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName())); if (params != null) { for (NameValuePair param : params) { len += param.getValue().getBytes().length; requestContent.addPart(param.getName(), new StringBody(param.getValue())); } } post.setEntity(requestContent); Log.d("Mustard", "Length: " + len); if (mHeaders != null) { Iterator<String> headKeys = mHeaders.keySet().iterator(); while (headKeys.hasNext()) { String key = headKeys.next(); post.setHeader(key, mHeaders.get(key)); } } if (consumer != null) { try { consumer.sign(post); } catch (OAuthMessageSignerException e) { } catch (OAuthExpectationFailedException e) { } catch (OAuthCommunicationException e) { } } try { mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); response = mClient.execute(post); } catch (ClientProtocolException e) { e.printStackTrace(); throw new IOException("HTTP protocol error."); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { throw new AuthException(401, "Unauthorized: " + url); } else if (statusCode == 403 || statusCode == 406) { try { JSONObject json = null; try { json = new JSONObject(StreamUtil.toString(response.getEntity().getContent())); } catch (JSONException e) { throw new MustardException(998, "Non json response: " + e.toString()); } throw new MustardException(statusCode, json.getString("error")); } catch (IllegalStateException e) { throw new IOException("Could not parse error response."); } catch (JSONException e) { throw new IOException("Could not parse error response."); } } else if (statusCode != 200) { Log.e("Mustard", response.getStatusLine().getReasonPhrase()); throw new MustardException(999, "Unmanaged response code: " + statusCode); } return response.getEntity().getContent(); }
From source file:io.swagger.v3.parser.util.OpenAPIDeserializer.java
public Server getServer(ObjectNode obj, String location, ParseResult result, String path) { if (obj == null) { return null; }//w ww. ja va 2s .com Server server = new Server(); String value = getString("url", obj, true, location, result); if (StringUtils.isNotBlank(value)) { if (!isValidURL(value) && path != null) { try { final URI absURI = new URI(path); if ("http".equals(absURI.getScheme()) || "https".equals(absURI.getScheme())) { value = absURI.resolve(new URI(value)).toString(); } } catch (URISyntaxException e) { e.printStackTrace(); } } server.setUrl(value); } value = getString("description", obj, false, location, result); if (StringUtils.isNotBlank(value)) { server.setDescription(value); } if (obj.get("variables") != null) { ObjectNode variables = getObject("variables", obj, false, location, result); ServerVariables serverVariables = getServerVariables(variables, String.format("%s.%s", location, "variables"), result); if (serverVariables != null && serverVariables.size() > 0) { server.setVariables(serverVariables); } } Map<String, Object> extensions = getExtensions(obj); if (extensions != null && extensions.size() > 0) { server.setExtensions(extensions); } Set<String> keys = getKeys(obj); for (String key : keys) { if (!SERVER_KEYS.contains(key) && !key.startsWith("x-")) { result.extra(location, key, obj.get(key)); } } return server; }
From source file:org.ehealth_connector.demo.iti.xd.DemoDocSource.java
/** * Executes some demo methods//from ww w .j ava2 s. c o m * */ public void doDemo() { // switch off logging for console output DOMConfigurator.configure(DemoMPIClient.class.getResource("/log4jConfigs/log4j.xml")); log.debug("PerformanceTimestamp: Starting DemoDocSource.doDemo"); // Create reusable elements XDSResponseType response; URI repositoryUnsecureUri; URI repositorySecureUri; InputStream inputStream; // Setup the Endpoint URIs try { repositoryUnsecureUri = new java.net.URI(NIST); repositorySecureUri = new java.net.URI(NIST_SECURED); } catch (URISyntaxException e) { System.out.println("SOURCE URI CANNOT BE SET: \n" + e.getMessage()); return; } // Setup keystore String keystore = prepareKeystore(); // Setup destinations Destination dest = new Destination(ORGANIZATIONAL_ID, repositoryUnsecureUri); Destination destSec = new Destination(ORGANIZATIONAL_ID, repositorySecureUri, keystore, KEY_STORE_PASS); try { ConvenienceCommunication comm = new ConvenienceCommunication(); log.debug("PerformanceTimestamp: DemoDocSource.doDemo: setup complete"); inputStream = getClass().getResourceAsStream(cdaFilePath); // Step 1: Sending CDA document NON-TLS comm.setDestination(dest); DocumentMetadata metaData = comm.addDocument(DocumentDescriptor.CDA_R2, inputStream); completeMetadata(metaData); outStr = outStr.append("1. Sending CDA Document (NON-TLS)..."); response = comm.submit(); outStr = outStr.append("done. Response: " + response.getStatus().getName() + "\n"); // Step 2: Sending CDA document TLS inputStream = getClass().getResourceAsStream(cdaFilePath); comm.setDestination(destSec); comm.clearDocuments(); metaData = comm.addDocument(DocumentDescriptor.CDA_R2, inputStream); completeMetadata(metaData); outStr = outStr.append("2. Sending CDA Document (TLS)..."); response = comm.submit(); outStr = outStr.append("done. Response: " + response.getStatus().getName() + "\n"); // Step 3: Sending PDF document NON-TLS inputStream = getClass().getResourceAsStream(pdfFilePath); comm.setDestination(dest); comm.clearDocuments(); metaData = comm.addDocument(DocumentDescriptor.PDF, inputStream); completeMetadata2(metaData); outStr = outStr.append("3. Sending PDF Document (NON-TLS)..."); response = comm.submit(); outStr = outStr.append("done. Response: " + response.getStatus().getName() + "\n"); // Step 4: Sending PDF document TLS inputStream = getClass().getResourceAsStream(pdfFilePath); comm.setDestination(destSec); comm.clearDocuments(); metaData = comm.addDocument(DocumentDescriptor.PDF, inputStream); completeMetadata2(metaData); outStr = outStr.append("4. Sending PDF Document (TLS)..."); response = comm.submit(); outStr = outStr.append("done. Response: " + response.getStatus().getName() + "\n"); } catch (Exception e) { e.printStackTrace(); } log.debug("PerformanceTimestamp: DemoDocSource.doDemo finished"); }
From source file:edu.jhu.pha.vosync.rest.DropboxService.java
@Path("search/{root:dropbox|sandbox}/{path:.+}") @GET/*from www . j av a2s . c o m*/ @RolesAllowed({ "user", "rwshareuser", "roshareuser" }) public byte[] search(@PathParam("root") String root, @PathParam("path") String fullPath, @QueryParam("query") String query, @QueryParam("file_limit") @DefaultValue("1000") int fileLimit, @QueryParam("include_deleted") @DefaultValue("false") boolean includeDeleted) { SciDriveUser user = ((SciDriveUser) security.getUserPrincipal()); if (null == query || query.length() < 3) { throw new BadRequestException("Wrong query parameter"); } VospaceId identifier; try { identifier = new VospaceId(new NodePath(fullPath, user.getRootContainer())); } catch (URISyntaxException e) { throw new BadRequestException("InvalidURI"); } Node node; try { node = NodeFactory.getNode(identifier, user.getName()); } catch (edu.jhu.pha.vospace.api.exceptions.NotFoundException ex) { throw new NotFoundException(identifier.getNodePath().getNodeStoragePath()); } if (!(node instanceof ContainerNode)) { throw new NotFoundException("Not a container"); } List<VospaceId> nodesList = ((ContainerNode) node).search(query, fileLimit, includeDeleted); TokenBuffer g = new TokenBuffer(null); try { g.writeStartArray(); for (VospaceId childNodeId : nodesList) { Node childNode = NodeFactory.getNode(childNodeId, user.getName()); JsonNode jnode = (JsonNode) childNode.export("json-dropbox-object", Detail.min); g.writeTree(jnode); /*CharBuffer cBuffer = Charset.forName("ISO-8859-1").decode(ByteBuffer.wrap((byte[])childNode.export("json-dropbox", Detail.min))); while(cBuffer.remaining() > 0) g.writeRaw(cBuffer.get()); if(ind++ < nodesList.size()-1) g.writeRaw(',');*/ } g.writeEndArray(); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); MappingJsonFactory f = new MappingJsonFactory(); JsonGenerator g2 = f.createJsonGenerator(byteOut).useDefaultPrettyPrinter(); g.serialize(g2); g2.close(); byteOut.close(); return byteOut.toByteArray(); } catch (JsonGenerationException e) { e.printStackTrace(); throw new InternalServerErrorException("Error generationg JSON: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new InternalServerErrorException("Error generationg JSON: " + e.getMessage()); } finally { try { g.close(); } catch (IOException ex) { } } }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
/** * Gets the complete filesystem path to the default base folder (which * contains the 'forms' and/* w w w. ja va 2s . co m*/ * 'WEB-INF') folders. * * @return */ private String getDefaultBaseFolder() { String dirPath = null; try { File mappingFile = null; URL url = AlfrescoController.class.getResource("/mapping.xml"); mappingFile = new File(new URI(url.toString())); dirPath = mappingFile.getAbsolutePath(); // @Amenel: I am not comfortable with the assumption about the path to // mapping.xml: although true today, it may not be so in the future, depending // on OS or JVM. String subPath = File.separator + "WEB-INF" + File.separator + "classes" + File.separator + "mapping.xml"; // subPath is "/WEB-INF/classes/mapping.xml" on Mac OS, Unix, Linux // subPath is "\WEB-INF\classes\mapping.xml" on Windows dirPath = StringUtils.replace(dirPath, subPath, ""); } catch (URISyntaxException e) { e.printStackTrace(); } return dirPath; }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
public boolean loadRedirectionTable(String filePath) { if (logger.isDebugEnabled()) { logger.debug("Reading redirection configuration file."); }/*w ww. j a v a2s . co m*/ String actualFilePath = ""; // the path where the stream is successfully open FileInputStream stream = null; if (StringUtils.trimToNull(filePath) != null) { try { actualFilePath = filePath; File file = new File(actualFilePath); stream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); // continue anyway } } if (stream == null) { if (StringUtils.trimToNull(redirectXmlPath) != null) { try { actualFilePath = redirectXmlPath; File file = new File(actualFilePath); stream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); // continue anyway } } URL url = AlfrescoController.class.getResource("/redirect.xml"); if (url == null) { if (logger.isErrorEnabled()) { logger.error("Redirection file not found. Redirection will not be available."); } return false; } File file; try { URI fileURI = new URI(url.toString()); file = new File(fileURI); actualFilePath = fileURI.getSchemeSpecificPart(); stream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (URISyntaxException e1) { e1.printStackTrace(); return false; } } else { redirectXmlPath = filePath; } String formName; String url; boolean autoAdvance; boolean addParams; Document document = DOMUtil.getDocumentFromStream(stream); if (document == null) { return false; } HashMap<String, RedirectionBean> localTable = new HashMap<String, RedirectionBean>(); // we won't check the tag name for the root element Element root = document.getDocumentElement(); List<Element> entries = DOMUtil.getChildren(root, MsgId.INT_REDIRECTION_ENTRY.getText()); // for each entry of the file, store the info for (Element entry : entries) { Element nameElt = DOMUtil.getChild(entry, MsgId.INT_REDIRECTION_NAME.getText()); if (nameElt != null) { try { formName = nameElt.getTextContent(); Element urlElt = DOMUtil.getChild(entry, MsgId.INT_REDIRECTION_URL.getText()); url = urlElt.getTextContent(); Element autoElt = DOMUtil.getChild(entry, MsgId.INT_REDIRECTION_AUTO_ADVANCE.getText()); autoAdvance = StringUtils.equals(autoElt.getTextContent(), "true"); Element addElt = DOMUtil.getChild(entry, MsgId.INT_REDIRECTION_ADD_PARAMS.getText()); addParams = StringUtils.equals(addElt.getTextContent(), "true"); RedirectionBean bean = new RedirectionBean(url, autoAdvance, addParams); localTable.put(formName, bean); } catch (NullPointerException ne) { logger.error("Caught a null pointer exception while loading the redirection file at '" + actualFilePath + "'. The file is probably not correctly formatted.", ne); return false; } } else { // // get rid of everything previously read // targetTable = new HashMap<String, RedirectionBean>(); // return false; } } if (logger.isDebugEnabled()) { logger.debug("Redirection configuration file successfully read."); } targetTable = localTable; return true; }
From source file:com.algolia.search.saas.APIClient.java
private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json, HashMap<String, String> errors) throws AlgoliaException { req.reset();//from w w w .j a va 2 s .co m // set URL try { req.setURI(new URI("https://" + host + url)); } catch (URISyntaxException e) { // never reached throw new IllegalStateException(e); } // set auth headers req.setHeader("X-Algolia-Application-Id", this.applicationID); if (forwardAdminAPIKey == null) { req.setHeader("X-Algolia-API-Key", this.apiKey); } else { req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey); req.setHeader("X-Forwarded-For", this.forwardEndUserIP); req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey); } for (Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } // set user agent req.setHeader("User-Agent", "Algolia for Java " + version); // set JSON entity if (json != null) { if (!(req instanceof HttpEntityEnclosingRequestBase)) { throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity"); } req.setHeader("Content-type", "application/json"); try { StringEntity se = new StringEntity(json, "UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); ((HttpEntityEnclosingRequestBase) req).setEntity(se); } catch (UnsupportedEncodingException e) { throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$ } } RequestConfig config = RequestConfig.custom().setSocketTimeout(httpSocketTimeoutMS) .setConnectTimeout(httpConnectTimeoutMS).setConnectionRequestTimeout(httpConnectTimeoutMS).build(); req.setConfig(config); HttpResponse response; try { response = httpClient.execute(req); } catch (IOException e) { // on error continue on the next host errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage())); return null; } try { int code = response.getStatusLine().getStatusCode(); if (code / 100 == 4) { String message = ""; try { message = EntityUtils.toString(response.getEntity()); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (code == 400) { throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request"); } else if (code == 403) { throw new AlgoliaException(code, message.length() > 0 ? message : "Invalid Application-ID or API-Key"); } else if (code == 404) { throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist"); } else { throw new AlgoliaException(code, message.length() > 0 ? message : "Error"); } } if (code / 100 != 2) { try { errors.put(host, EntityUtils.toString(response.getEntity())); } catch (IOException e) { errors.put(host, String.valueOf(code)); } // KO, continue return null; } try { InputStream istream = response.getEntity().getContent(); InputStreamReader is = new InputStreamReader(istream, "UTF-8"); JSONTokener tokener = new JSONTokener(is); JSONObject res = new JSONObject(tokener); is.close(); return res; } catch (IOException e) { return null; } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } } finally { req.releaseConnection(); } }
From source file:org.lilyproject.indexer.admin.cli.BaseIndexerAdminCli.java
@Override protected int processOptions(CommandLine cmd) throws Exception { int result = super.processOptions(cmd); if (result != 0) return result; if (cmd.hasOption(nameOption.getOpt())) { indexName = cmd.getOptionValue(nameOption.getOpt()); }//from www .j av a2 s.co m if (cmd.hasOption(solrShardsOption.getOpt())) { solrShards = new HashMap<String, String>(); String[] solrShardEntries = cmd.getOptionValue(solrShardsOption.getOpt()).split(","); Set<String> addresses = new HashSet<String>(); // Be helpful to the user and validate the URIs are syntactically correct for (String shardEntry : solrShardEntries) { int sep = shardEntry.indexOf(':'); if (sep == -1) { System.out.println( "SOLR shards should be specified as 'name:URL' pairs, which the following is not:"); System.out.println(shardEntry); return 1; } String shardName = shardEntry.substring(0, sep).trim(); if (shardName.length() == 0) { System.out.println("Zero-length shard name in the following shard entry:"); System.out.println(shardEntry); return 1; } if (shardName.equals("http")) { System.out.println("You forgot to specify a shard name for the SOLR shard " + shardEntry); return 1; } String shardAddress = shardEntry.substring(sep + 1).trim(); try { URI uri = new URI(shardAddress); if (!uri.isAbsolute()) { System.out.println("Not an absolute URI: " + shardAddress); return 1; } } catch (URISyntaxException e) { System.out.println("Invalid SOLR shard URI: " + shardAddress); System.out.println(e.getMessage()); return 1; } if (solrShards.containsKey(shardName)) { System.out.println("Duplicate shard name: " + shardName); return 1; } if (addresses.contains(shardAddress)) { if (!cmd.hasOption(forceOption.getOpt())) { System.out.println("You have two shards pointing to the same URI:"); System.out.println(shardAddress); System.out.println(); System.out.println("If this is what you want, use the --" + forceOption.getLongOpt() + " option to bypass this check."); return 1; } } addresses.add(shardAddress); solrShards.put(shardName, shardAddress); } if (solrShards.isEmpty()) { // Probably cannot occur System.out.println("No SOLR shards specified though option is used."); return 1; } } if (cmd.hasOption(shardingConfigurationOption.getOpt())) { File configurationFile = new File(cmd.getOptionValue(shardingConfigurationOption.getOpt())); if (!configurationFile.exists()) { System.out.println("Specified sharding configuration file not found:"); System.out.println(configurationFile.getAbsolutePath()); return 1; } shardingConfiguration = FileUtils.readFileToByteArray(configurationFile); } if (cmd.hasOption(configurationOption.getOpt())) { File configurationFile = new File(cmd.getOptionValue(configurationOption.getOpt())); if (!configurationFile.exists()) { System.out.println("Specified indexer configuration file not found:"); System.out.println(configurationFile.getAbsolutePath()); return 1; } indexerConfiguration = FileUtils.readFileToByteArray(configurationFile); if (!cmd.hasOption(forceOption.getOpt())) { LilyClient lilyClient = null; try { lilyClient = new LilyClient(zkConnectionString, 10000); IndexerConfBuilder.build(new ByteArrayInputStream(indexerConfiguration), lilyClient.getRepository()); } catch (Exception e) { System.out.println(); // separator line because LilyClient might have produced some error logs System.out.println("Failed to parse & build the indexer configuration."); System.out.println(); System.out.println("If this problem occurs because no Lily node is available"); System.out.println("or because certain field types or record types do not exist,"); System.out.println( "then you can skip this validation using the option --" + forceOption.getLongOpt()); System.out.println(); if (e instanceof IndexerConfException) { printExceptionMessages(e); } else { e.printStackTrace(); } return 1; } finally { Closer.close(lilyClient); } } } if (cmd.hasOption(generalStateOption.getOpt())) { String stateName = cmd.getOptionValue(generalStateOption.getOpt()); try { generalState = IndexGeneralState.valueOf(stateName.toUpperCase()); } catch (IllegalArgumentException e) { System.out.println("Invalid index state: " + stateName); return 1; } } if (cmd.hasOption(updateStateOption.getOpt())) { String stateName = cmd.getOptionValue(updateStateOption.getOpt()); try { updateState = IndexUpdateState.valueOf(stateName.toUpperCase()); } catch (IllegalArgumentException e) { System.out.println("Invalid index update state: " + stateName); return 1; } } if (cmd.hasOption(buildStateOption.getOpt())) { String stateName = cmd.getOptionValue(buildStateOption.getOpt()); try { buildState = IndexBatchBuildState.valueOf(stateName.toUpperCase()); } catch (IllegalArgumentException e) { System.out.println("Invalid index build state: " + stateName); return 1; } if (buildState != IndexBatchBuildState.BUILD_REQUESTED) { System.out.println("The build state can only be set to " + IndexBatchBuildState.BUILD_REQUESTED); return 1; } } if (cmd.hasOption(outputFileOption.getOpt())) { outputFileName = cmd.getOptionValue(outputFileOption.getOpt()); File file = new File(outputFileName); if (!cmd.hasOption(forceOption.getOpt()) && file.exists()) { System.out.println("The specified output file already exists:"); System.out.println(file.getAbsolutePath()); System.out.println(); System.out.println("Use --" + forceOption.getLongOpt() + " to overwrite it."); } } return 0; }
From source file:com.pianobakery.complsa.MainGui.java
public void helpMethod() { //Get file from resources folder try {//from w w w . jav a 2 s .c om openWebpage(new URI(helpURL)); } catch (URISyntaxException e) { e.printStackTrace(); } }
From source file:com.pianobakery.complsa.MainGui.java
public void updateMethod() { //Get file from resources folder try {//from w ww . j a va 2s . c o m openWebpage(new URI(updateURL)); } catch (URISyntaxException e) { e.printStackTrace(); } }