List of usage examples for java.net URISyntaxException toString
public String toString()
From source file:org.opendatakit.common.security.spring.Oauth2ResourceFilter.java
private Map<String, Object> getJsonResponse(String url, String accessToken) { Map<String, Object> nullData = new HashMap<String, Object>(); // OK if we got here, we have a valid token. // Issue the request... URI nakedUri;/*from w w w.j a v a 2s . c o m*/ try { nakedUri = new URI(url); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return nullData; } List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("access_token", accessToken)); URI uri; try { uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(), nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null); } catch (URISyntaxException e1) { e1.printStackTrace(); logger.error(e1.toString()); return nullData; } // DON'T NEED clientId on the toke request... // addCredentials(clientId, clientSecret, nakedUri.getHost()); // setup request interceptor to do preemptive auth // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client HttpClient client = httpClientFactory.createHttpClient(httpParams); HttpGet httpget = new HttpGet(uri); logger.info(httpget.getURI().toString()); HttpResponse response = null; try { response = client.execute(httpget, new BasicHttpContext()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("not 200: " + statusCode); return nullData; } else { HttpEntity entity = response.getEntity(); if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) { BufferedReader reader = null; InputStreamReader isr = null; try { reader = new BufferedReader(isr = new InputStreamReader(entity.getContent())); @SuppressWarnings("unchecked") Map<String, Object> userData = mapper.readValue(reader, Map.class); return userData; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } } if (isr != null) { try { isr.close(); } catch (IOException e) { // ignore } } } } else { logger.error("unexpected body"); return nullData; } } } catch (IOException e) { logger.error(e.toString()); return nullData; } catch (Exception e) { logger.error(e.toString()); return nullData; } }
From source file:net.issarlk.androbunny.inkbunny.API.java
public void scrapeUserPage(User argUser) throws IOException { argUser.profile = "Couldn't read user profile"; String data = ""; try {// w ww. ja v a 2 s . c o m data = AndrobunnyAppSingleton.androbunnyapp.readUri(new URI("https://inkbunny.net/" + argUser.name)); } catch (URISyntaxException e2) { Log.e(TAG, e2.toString()); } // Extract profile Pattern pattern = Pattern.compile(".*<div class='title'>Profile</div>.*?(<.*)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); argUser.profile = extractTree(pattern, data); // Extract user icon pattern = Pattern.compile( "<img [^>]*? src='([^']*)' [^>]*? alt='" + argUser.name + "' title='" + argUser.name + "'[^>]*?/>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(data); if (matcher.find()) { //Found the user icon try { argUser.icons[0] = new Icon(Icon.LARGE, new URI(matcher.group(1))); } catch (URISyntaxException e) { Log.e(TAG, e.toString()); } } }
From source file:org.wikidata.wdtk.wikibaseapi.WikibaseDataFetcher.java
/** * Returns the URL string for a wbgetentities request to the Wikibase API, * or null if it was not possible to build such a string with the current * settings./* ww w.jav a 2 s. c o m*/ * * @param parameters * map of possible parameters (e.g. ("sites", "enwiki"), * ("titles", titles of entities to retrieve), ("ids", ids of * entities to retrieve). See * WikibaseDataFetcher.getWbGetEntitiesUrl(List<String> * entityIds) as an example. * @return URL string */ String getWbGetEntitiesUrl(Map<String, String> parameters) { URIBuilder uriBuilder; try { uriBuilder = new URIBuilder(this.apiBaseUrl); } catch (URISyntaxException e1) { logger.error("Error in API URL \"" + this.apiBaseUrl + "\": " + e1.toString()); return null; } uriBuilder.setParameter("action", "wbgetentities"); uriBuilder.setParameter("format", "json"); setRequestProps(uriBuilder); setRequestLanguages(uriBuilder); setRequestSitefilter(uriBuilder); for (String parameter : parameters.keySet()) { String value = parameters.get(parameter); uriBuilder.setParameter(parameter, value); } return uriBuilder.toString(); }
From source file:com.cyberway.issue.crawler.writer.WARCWriterProcessor.java
protected URI getRecordID() throws IOException { URI result;//from w w w .j ava 2s. c o m try { result = GeneratorFactory.getFactory().getRecordID(); } catch (URISyntaxException e) { throw new IOException(e.toString()); } return result; }
From source file:com.cyberway.issue.crawler.writer.WARCWriterProcessor.java
protected URI qualifyRecordID(final URI base, final String key, final String value) throws IOException { URI result;/*from www . java 2 s .c o m*/ Map<String, String> qualifiers = new HashMap<String, String>(1); qualifiers.put(key, value); try { result = GeneratorFactory.getFactory().qualifyRecordID(base, qualifiers); } catch (URISyntaxException e) { throw new IOException(e.toString()); } return result; }
From source file:eionet.gdem.utils.InputFile.java
/** * Stores the URL of remote file./*from w w w . java2s.c o m*/ * * @param strUrl URL of input file * @throws MalformedURLException Invalid URL. */ private void setURL(String strUrl) throws MalformedURLException { try { URI uri = new URI(escapeSpaces(strUrl)); parseUri(uri); this.url = uri.toURL(); } catch (URISyntaxException ue) { throw new MalformedURLException(ue.toString()); } catch (IllegalArgumentException ae) { throw new MalformedURLException(ae.toString()); } }
From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java
@Override public void uploadTestRun(String testSpecificationId, FilePath workspace, String includes, String excludes, Map<String, Object> metadata, PrintStream logger) throws IOException, InterruptedException { if (testSpecificationId == null || testSpecificationId.isEmpty()) { throw new IllegalArgumentException( "No test specification id specified. Does the test specification still exist in XL TestView?"); }/*w ww . j av a 2s . c o m*/ try { logInfo(logger, format("Collecting files from '%s' using include pattern: '%s' and exclude pattern '%s'", workspace.getRemote(), includes, excludes)); DirScanner scanner = new DirScanner.Glob(includes, excludes); ObjectMapper objectMapper = new ObjectMapper(); RequestBody body = new MultipartBuilder().type(MultipartBuilder.MIXED) .addPart(RequestBody.create(MediaType.parse(APPLICATION_JSON_UTF_8), objectMapper.writeValueAsString(metadata))) .addPart(new ZipRequestBody(workspace, scanner, logger)).build(); Request request = new Request.Builder() .url(createSensibleURL(API_IMPORT + "/" + testSpecificationId, serverUrl)) .header("User-Agent", getUserAgent()).header("Accept", APPLICATION_JSON_UTF_8) .header("Authorization", createCredentials()).header("Transfer-Encoding", "chunked").post(body) .build(); Response response = client.newCall(request).execute(); ObjectMapper mapper = createMapper(); ImportError importError; switch (response.code()) { case 200: logInfo(logger, "Sent data successfully"); return; case 304: logWarn(logger, "No new results were detected. Nothing was imported."); throw new IllegalStateException("No new results were detected. Nothing was imported."); case 400: importError = mapper.readValue(response.body().byteStream(), ImportError.class); throw new IllegalStateException(importError.getMessage()); case 401: throw new AuthenticationException(String.format( "User '%s' and the supplied password are unable to log in", credentials.getUsername())); case 402: throw new PaymentRequiredException("The XL TestView server does not have a valid license"); case 404: throw new ConnectionException("Cannot find test specification '" + testSpecificationId + ". Please check if the XL TestView server is " + "running and the test specification exists."); case 422: logWarn(logger, "Unable to process results."); logWarn(logger, "Are you sure your include/exclude pattern provides all needed files for the test tool?"); importError = mapper.readValue(response.body().byteStream(), ImportError.class); throw new IllegalStateException(importError.getMessage()); default: throw new IllegalStateException("Unknown error. Status code: " + response.code() + ". Response message: " + response.toString()); } } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } catch (IOException e) { e.printStackTrace(); LOG.warn("I/O error uploading test run data to {} {}\n{}", serverUrl.toString(), e.toString(), e); throw new IOException( "I/O error uploading test run data to " + serverUrl.toString() + " " + e.toString(), e); } }
From source file:com.cisco.oss.foundation.http.AbstractHttpClient.java
protected S updateRequestUri(S request, InternalServerProxy serverProxy) { URI origUri = request.getUri(); String host = serverProxy.getHost(); String scheme = origUri.getScheme() == null ? (request.isHttpsEnabled() ? "https" : "http") : origUri.getScheme();// w w w . j a va 2 s. com int port = serverProxy.getPort(); String urlPath = ""; if (origUri.getRawPath() != null && origUri.getRawPath().startsWith("/")) { urlPath = origUri.getRawPath(); } else { urlPath = "/" + origUri.getRawPath(); } URI newURI = null; try { if (autoEncodeUri) { String query = origUri.getQuery(); newURI = new URI(scheme, origUri.getUserInfo(), host, port, urlPath, query, origUri.getFragment()); } else { String query = origUri.getRawQuery(); if (query != null) { newURI = new URI(scheme + "://" + host + ":" + port + urlPath + "?" + query); } else { newURI = new URI(scheme + "://" + host + ":" + port + urlPath); } } } catch (URISyntaxException e) { throw new ClientException(e.toString()); } S req = (S) request.replaceUri(newURI); // try { // req = (S) this.clone(); // } catch (CloneNotSupportedException e) { // throw new IllegalArgumentException(e); // } // req.uri = newURI; return req; }
From source file:jp.ne.sakura.kkkon.java.net.socketimpl.testapp.android.SocketImplHookTestApp.java
/** Called when the activity is first created. */ @Override/* w ww .j a v a 2 s . c o m*/ public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { SocketImplHookFactory.initialize(); } { ProxySelector proxySelector = ProxySelector.getDefault(); Log.d(TAG, "proxySelector=" + proxySelector); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { Log.d(TAG, e.toString()); } List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { Log.d(TAG, " proxy=" + proxy); } } } } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("ExceptionHandler"); layout.addView(tv); Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); { Button btn = new Button(this); btn.setText("upload http AsyncTask"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(0.0.0.0)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { destHost = InetAddress.getByName("0.0.0.0"); if (null != destHost) { try { if (destHost.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + destHost.toString() + " reachable"); } else { Log.d(TAG, "destHost=" + destHost.toString() + " not reachable"); } } catch (IOException e) { } } } catch (UnknownHostException e) { } Log.d(TAG, "destHost=" + destHost); } }); thread.start(); try { thread.join(1000); } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(www.google.com)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { InetAddress dest = InetAddress.getByName("www.google.com"); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); } destHost = dest; } catch (IOException e) { } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp"); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); } destHost = dest; } catch (IOException e) { } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } setContentView(layout); }
From source file:com.visionspace.jenkins.vstart.plugin.VSPluginPerformer.java
public boolean logToWorkspace(Long reportId, AbstractBuild build, BuildListener listener) { try {/*from ww w . j a va2 s . co m*/ org.json.JSONObject report = vstObject.getReport(reportId); FilePath jPath = new FilePath(build.getWorkspace(), build.getWorkspace().toString() + "/VSTART_JSON"); if (!jPath.exists()) { jPath.mkdirs(); } String filePath = jPath + "/VSTART_JSON_" + build.getId() + ".json"; JSONArray reports; try { String content = new String(Files.readAllBytes(Paths.get(filePath))); reports = new JSONArray(content); } catch (IOException e) { Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.WARNING, null, e); reports = new JSONArray(); } reports.put(report); PrintWriter wj = new PrintWriter(filePath); wj.println(reports.toString()); wj.close(); //TODO: check test case result /* if (report.getString("status").equals("PASSED")) { */ return true; /* } */ } catch (URISyntaxException ex) { Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex); listener.getLogger().println("Error on performing the workspace logging -> " + ex.getReason()); } catch (IOException ex) { Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex); listener.getLogger().println("Error on performing the workspace logging -> " + ex.toString()); } catch (InterruptedException ex) { Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex); listener.getLogger().println("Error on performing the workspace logging -> " + ex.getMessage()); } return false; }