List of usage examples for java.net URISyntaxException printStackTrace
public void printStackTrace()
From source file:i5.las2peer.services.videoAdapter.AdapterClass.java
protected static String[] getVideoURLs(String[] objectIds, int size) { String[] videos = new String[size]; CloseableHttpResponse response = null; URI request = null;/*from w w w .j a v a 2s .c om*/ try { for (int k = 0; k < size; k++) { // Get video details request = new URI("http://eiche:7071/video-details/videos/" + objectIds[k] + "?part=url,language"); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet get = new HttpGet(request); response = httpClient.execute(get); // Parse the response BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder content = new StringBuilder(); String line; while (null != (line = rd.readLine())) { content.append(line); } JSONObject object = new JSONObject(content.toString()); // Save in a String array videos[k] = new String(object.getString("url")); } } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return videos; }
From source file:com.adamrosenfield.wordswithcrosses.versions.DefaultUtil.java
private void downloadHelper(URL url, String scrubbedUrl, Map<String, String> headers, HttpContext httpContext, OutputStream output) throws IOException { HttpGet httpget;//from w w w .j av a 2s .c om try { httpget = new HttpGet(url.toURI()); } catch (URISyntaxException e) { e.printStackTrace(); throw new IOException("Invalid URL: " + url); } httpget.setHeader("Accept-Encoding", "gzip, deflate"); for (Entry<String, String> e : headers.entrySet()) { httpget.setHeader(e.getKey(), e.getValue()); } HttpResponse response = mHttpClient.execute(httpget, httpContext); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (status != 200) { LOG.warning("Download failed: " + scrubbedUrl + " status=" + status); if (entity != null) { entity.consumeContent(); } throw new HTTPException(status); } if (entity != null) { // If we got a compressed entity, create the proper decompression // stream wrapper InputStream content = entity.getContent(); Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null) { if ("gzip".equals(contentEncoding.getValue())) { content = new GZIPInputStream(content); } else if ("deflate".equals(contentEncoding.getValue())) { content = new InflaterInputStream(content, new Inflater(true)); } } try { IO.copyStream(content, output); } finally { entity.consumeContent(); } } }
From source file:com.xyproto.archfriend.Web.java
@Override protected String doInBackground(String... params) { String url = params[0];//from w w w.j av a2 s. c o m int bufsize = 2048; HttpGet mRequest = new HttpGet(); HttpClient mClient = getNewHttpClient(); mReader = null; StringBuilder mBuffer = new StringBuilder(bufsize); String mNewLine = System.getProperty("line.separator"); mBuffer.setLength(0); try { mRequest.setURI(new URI(url)); HttpResponse response = mClient.execute(mRequest); mReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), bufsize); String line; while ((line = mReader.readLine()) != null) { mBuffer.append(line); mBuffer.append(mNewLine); } } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { closeReader(); } return mBuffer.toString(); }
From source file:de.raion.xmppbot.hipchat.TfsLinkBeautifierInterceptor.java
@Override public void interceptPacket(Packet packet) { // PacketFilter is set to MessageType Message xmppMessage = (Message) packet; PluginManager pluginManager = getContext().getPluginManager(); if (apiConfig == null) { apiConfig = getContext().loadConfig(HipChatAPIConfig.class); String authToken = apiConfig.getAuthenticationToken(); if (authToken == null || authToken.equals("")) { log.warn("no authToken configured for Hipchat, please update your hipchatapiconfig.json"); return; }// ww w . j a v a2 s.c om } if (pluginManager.isEnabled(TfsIssuePlugin.class)) { TfsIssuePlugin plugin = getContext().getPluginManager().get(TfsIssuePlugin.class); if (plugin.matches(xmppMessage.getBody())) { JsonNode issue = plugin.getIssueNode(); if (issue != null) { String issueKey = issue.findValue("__wrappedArray").get(0).findValue("fields").findValue("-3") .textValue(); String messageText; try { messageText = createMessageText(issue, plugin.getConfig()); } catch (URISyntaxException e) { e.printStackTrace(); messageText = xmppMessage.getBody(); } // todo do better String roomId = getRoomId(); if (roomId == null) { return; } // nickname used by the bot for the configuration 'hipchat' String nickName = getContext().getBot() .getNickName(getClass().getAnnotation(PacketInterceptor.class).service()); WebResource resource = client.resource("https://api.hipchat.com/v1/rooms/message") .queryParam("room_id", roomId).queryParam("from", nickName) .queryParam("message", messageText).queryParam("message_format", "html") .queryParam("auth_token", apiConfig.getAuthenticationToken()); ClientResponse response = resource.post(ClientResponse.class); if (response.getClientResponseStatus() == Status.OK) { log.info("sent message for issue [{}] to room {}", issueKey, roomId); // this is a hack :( xmppMessage.setBody(null); throw new IllegalArgumentException( "TfsLinkBeautifier: preventing message sending via xmpp. message already sent via hipchat web api"); } else { log.warn("sending message for {} failed, status = {}", "[" + issueKey + "] to " + roomId, response.getStatus()); log.warn(response.getEntity(String.class)); } } } } }
From source file:info.rmapproject.core.model.impl.openrdf.ORMapEventInactivationTest.java
/** * Test method for {@link info.rmapproject.core.model.impl.openrdf.ORMapEventInactivation#ORMapEventInactivation(info.rmapproject.core.model.RMapIri, info.rmapproject.core.model.event.RMapEventTargetType, info.rmapproject.core.model.RMapValue)}. * @throws RMapDefectiveArgumentException * @throws RMapException /* w w w . j a v a 2s . c om*/ * @throws URISyntaxException */ @Test public void testORMapEventInactivationRMapIriRMapEventTargetTypeRMapValue() throws RMapException, RMapDefectiveArgumentException, URISyntaxException { RMapIri associatedAgent = null; try { associatedAgent = new RMapIri(new java.net.URI("http://orcid.org/0000-0000-0000-0000")); } catch (URISyntaxException e1) { e1.printStackTrace(); fail("could not create agent"); } RMapLiteral desc = new RMapLiteral("This is an inactivation event"); RMapRequestAgent requestAgent = new RMapRequestAgent(associatedAgent.getIri(), new URI("ark:/29297/testkey")); ORMapEventInactivation event = new ORMapEventInactivation(requestAgent, RMapEventTargetType.DISCO, desc); Model model = event.getAsModel(); assertEquals(7, model.size()); java.net.URI id1 = null; try { // id for old disco (source object) id1 = rmapIdService.createId(); } catch (Exception e) { e.printStackTrace(); fail("unable to create id"); } IRI inactivatedObject = ORAdapter.uri2OpenRdfIri(id1); event.setInactivatedObjectStmt(inactivatedObject); model = event.getAsModel(); assertEquals(8, model.size()); Date end = new Date(); event.setEndTime(end); model = event.getAsModel(); assertEquals(9, model.size()); RMapIri iIri = event.getInactivatedObjectId(); assertEquals(inactivatedObject.stringValue(), iIri.getStringValue()); assertEquals(RMapEventType.INACTIVATION, event.getEventType()); assertEquals(RMapEventTargetType.DISCO, event.getEventTargetType()); Statement tStmt = event.getTypeStatement(); assertEquals(RMAP.EVENT, tStmt.getObject()); }
From source file:com.rest4j.ApiFactory.java
/** * This method can be used to just read the API description XML into a DOM. The XML is schema-validated * and preprocessed with the preprocessors that were added with {@link #addPreprocessor(Preprocessor)}. * * @return The validated and preprocessed DOM. *///w w w. j ava 2 s . com public Document getDocument() throws ParserConfigurationException, SAXException, IOException, ConfigurationException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document xml = null; try { xml = documentBuilder.parse(apiDescriptionXml.toURI().toString()); } catch (URISyntaxException e) { e.printStackTrace(); } for (Preprocessor pre : preprocessors) { pre.process(this, xml); } return xml; }
From source file:ezbake.azkaban.manager.ScheduleManager.java
/** * Class for scheduling a flow in Azkaban * * @param sessionId The Azkaban sessionId of a logged in user for the project * @param azkabanUri The Azkaban URL//from w w w .j a v a 2 s .c om */ public ScheduleManager(String sessionId, URI azkabanUri) { this.sessionId = sessionId; try { this.schedulerUri = new URIBuilder(azkabanUri).setPath("/schedule").build(); } catch (URISyntaxException e) { e.printStackTrace(); } }
From source file:io.ticofab.cm_android_sdk.library.views.CloudMatchView.java
/** * Initializes the CloudMatch. Always call it at the beginning of your application. * * @param activity Provides the context where the application runs. * @param clientListener Implementation of the OnCloudMatchEvent interface. Will be used to notify any network communication. * @param locationProvider Implementation of LocationProvider, needs to serve coordinates when needed * @param clientInterface Implementation of the CloudMatchViewInterface * @throws PackageManager.NameNotFoundException Exception thrown if credentials were not found. *//*ww w. java 2s . c om*/ public void initCloudMatch(final Activity activity, final CloudMatchEventListener clientListener, final LocationProvider locationProvider, final CloudMatchViewInterface clientInterface) throws PackageManager.NameNotFoundException { mActivity = activity; mListener = clientListener; mClientInterface = clientInterface; if (mActivity == null) { throw new CloudMatchNotInitializedException("Activity cannot be null."); } // initialize socket final ServerMessagesHandler myMessagesHandler = new ServerMessagesHandler(mActivity, mListener); final CloudMatchListener myListener = new CloudMatchListener(mActivity, mListener, myMessagesHandler); Connector connector = new Connector(mActivity, StringHelper.getApiKey(mActivity), StringHelper.getAppId(mActivity)); final URI uri; try { uri = connector.getConnectionUri(); mWSClient = new WebSocketClient(uri, myListener, null); mMatcher = new Matcher(mWSClient, locationProvider); } catch (URISyntaxException e) { e.printStackTrace(); } }
From source file:eu.optimis.ecoefficiencytool.rest.client.EcoEfficiencyToolValidatorRESTClient.java
/** * Logs a conditional-action-obtained forecast for further validation. * * @param deltaT Increment of time for which the forecast has been performed * with respect to the current time.//from www. j a v a 2 s .c om * @param value Forecasted value. * @param reason Potential action which was evaluated when performing the * forecast. Choose one of the provided: VM_DEPLOYMENT, VM_MIGRATION, * VM_CANCELLATION, SERVICE_DEPLOYMENT */ public void logConditionalAction(Long deltaT, Double value, String reason) { try { WebResource resource = client.resource(this.getAddress()).path("conditional"); if (deltaT != null) { resource = resource.queryParam("deltaT", deltaT.toString()); } else { log.error("Parameter \"deltaT\" must be specified."); return; } if (value != null) { resource = resource.queryParam("value", value.toString()); } else { log.error("Parameter \"value\" must be specified."); return; } if (reason != null) { resource = resource.queryParam("reason", reason); } else { log.error("Parameter \"reason\" must be specified."); return; } resource.post(); } catch (UniformInterfaceException ex) { ClientResponse cr = ex.getResponse(); log.error(cr.getStatus()); ex.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.opendatakit.aggregate.servlet.MultimodeLoginPageServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { CallingContext cc = ContextFactory.getCallingContext(this, req); // Check to make sure we are using the canonical server name. // If not, redirect to that name. This ensures that authentication // cookies will have the proper realm(s) established for them. String newUrl = cc.getServerURL() + BasicConsts.FORWARDSLASH + ADDR; String query = req.getQueryString(); if (query != null && query.length() != 0) { newUrl += "?" + query; }// ww w.j a v a2 s. c o m URL url = new URL(newUrl); if (!url.getHost().equalsIgnoreCase(req.getServerName())) { logger.info("Incoming servername: " + req.getServerName() + " expected: " + url.getHost() + " -- redirecting."); // try to get original destination URL from Spring... String redirectUrl = getRedirectUrl(req, ADDR); try { URI uriChangeable = new URI(redirectUrl); URI newUri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), uriChangeable.getPath(), uriChangeable.getQuery(), uriChangeable.getFragment()); newUrl = newUri.toString(); } catch (URISyntaxException e) { e.printStackTrace(); } // go to the proper page (we'll most likely be redirected back to here for authentication) resp.sendRedirect(newUrl); return; } // OK. We are using the canonical server name. String redirectParamString = getRedirectUrl(req, AggregateHtmlServlet.ADDR); // we need to appropriately cleanse this string for the OpenID login // strip off the server pathname portion if (redirectParamString.startsWith(cc.getSecureServerURL())) { redirectParamString = redirectParamString.substring(cc.getSecureServerURL().length()); } else if (redirectParamString.startsWith(cc.getServerURL())) { redirectParamString = redirectParamString.substring(cc.getServerURL().length()); } while (redirectParamString.startsWith("/")) { redirectParamString = redirectParamString.substring(1); } // check for XSS attacks. The redirect string is emitted within single and double // quotes. It is a URL with :, /, ? and # characters. But it should not contain // quotes, parentheses or semicolons. String cleanString = redirectParamString.replaceAll(BAD_PARAMETER_CHARACTERS, ""); if (!cleanString.equals(redirectParamString)) { logger.warn("XSS cleanup -- redirectParamString has forbidden characters: " + redirectParamString); redirectParamString = cleanString; } logger.info("Invalidating login session " + req.getSession().getId()); // Invalidate session. HttpSession s = req.getSession(); if (s != null) { s.invalidate(); } // Display page. resp.setContentType(HtmlConsts.RESP_TYPE_HTML); resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE); resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); resp.setHeader("Pragma", "no-cache"); resp.addHeader(HtmlConsts.X_FRAME_OPTIONS, HtmlConsts.X_FRAME_SAMEORIGIN); PrintWriter out = resp.getWriter(); out.print( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" + "<html>" + "<head>" + "<meta http-equiv=\"cache-control\" content=\"no-store, no-cache, must-revalidate\"/>" + "<meta http-equiv=\"expires\" content=\"Mon, 26 Jul 1997 05:00:00 GMT\"/>" + "<meta http-equiv=\"pragma\" content=\"no-cache\"/>" + "<link rel=\"icon\" href=\"favicon.ico\"/>" + "<title>Log onto Aggregate</title>" + "<link type=\"text/css\" rel=\"stylesheet\" href=\"AggregateUI.css\">" + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/button.css\">" + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/table.css\">" + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/navigation.css\">" + "<script type=\"text/javascript\">" + "window.onbeforeunload=function() {\n" + "var e=document.getElementById(\"stale\");\n" + "e.value=\"yes\";\n" + "}\n" + "window.onload=function(){\n" + "var e=document.getElementById(\"stale\");\n" + "if(e.value==\"yes\") {window.location.reload(true);}\n" + "}\n" + "</script>" + "</head>" + "<body>" + "<input type=\"hidden\" id=\"stale\" value=\"no\">" + "<table width=\"100%\" cellspacing=\"30\"><tr>" + "<td align=\"LEFT\" width=\"10%\"><img src=\"odk_color.png\" id=\"odk_aggregate_logo\" /></td>" + "<td align=\"LEFT\" width=\"90%\"><font size=\"7\">Log onto Aggregate</font></td></tr></table>" + "<table cellspacing=\"20\">" + "<tr><td valign=\"top\">" + "<form action=\"local_login.html\" method=\"get\">" + "<script type=\"text/javascript\">" + "<!--\n" + "document.write('<input name=\"redirect\" type=\"hidden\" value=\"" + redirectParamString + "' + window.location.hash + '\"/>');" + "\n-->" + "</script>" + "<input class=\"gwt-Button\" type=\"submit\" value=\"Sign in with Aggregate password\"/>" + "</form></td>" + "<td valign=\"top\">Click this button to log onto Aggregate using the username " + "and password that have been assigned to you by the Aggregate site administrator.</td></tr>" + "<tr><td valign=\"top\">" + "<script type=\"text/javascript\">" + "<!--\n" + "document.write('<form action=\"" + redirectParamString + "' + window.location.hash + '\" method=\"get\">');" + "document.write('<input class=\"gwt-Button\" type=\"submit\" value=\"Anonymous Access\"/></form>');" + "\n-->" + "</script>" + "</td>" + "<td valign=\"top\">Click this button to access Aggregate without logging in.</td></tr>" + "</table>" + "</body>" + "</html>"); }