List of usage examples for java.net URISyntaxException printStackTrace
public void printStackTrace()
From source file:com.ibm.caas.CaaSResource.java
/** * Fetch content from MACM instance by doing a HTTP GET request and set * Cookies/*from w ww .j a v a 2 s.c o m*/ * * @param url * {@link String} MACM content url * @return {@link InputStream} */ public InputStream openStream(String url) throws IOException { urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setUseCaches(false); HttpURLConnection.setFollowRedirects(true); if (COOKIES != null) { for (String cookie : CaaSResource.COOKIES) { urlConnection.addRequestProperty("Cookie", cookie.split(";", 1)[0]); } } if (urlConnection.getResponseCode() == 401 || urlConnection.getResponseCode() == 400) { try { connect(); } catch (URISyntaxException e) { e.printStackTrace(); } finally { openStream(url); } } return urlConnection.getInputStream(); }
From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java
@SuppressWarnings("deprecation") private void doProxy(String remoteUrl, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible try {//from w w w . ja v a 2 s . com this.targetUri = new URI(remoteUrl); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Need to handle https, but think about "restricted" layers for now. Some institutions don't really have good protection for restricted layers. Does this open up potential for security //problems for those folks? if (servletRequest.getScheme().equals("https")) { //actually, what matters the most is if the remote url is https } BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest( servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest)); copyRequestHeaders(servletRequest, proxyRequest); // Add the input entity (streamed) then execute the request. HttpResponse proxyResponse = null; InputStream servletRequestInputStream = servletRequest.getInputStream(); try { try { proxyRequest.setEntity( new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength())); // Execute the request logger.debug("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); } finally { closeQuietly(servletRequestInputStream); } // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); logger.info("Status from remote server: " + Integer.toString(statusCode)); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; throw new RuntimeException(e); } }
From source file:com.cloud.network.bigswitch.BigSwitchBcfUtils.java
public TopologyData getTopology(long physicalNetworkId) { List<NetworkVO> networks; List<NicVO> nics;/* w ww . j a v a2s.co m*/ networks = _networkDao.listByPhysicalNetworkTrafficType(physicalNetworkId, TrafficType.Guest); TopologyData topo = new TopologyData(); // networks: // - all user created networks (VPC or non-VPC) // - one external network // routers: // - per VPC (handle in network loop) // - per stand-alone network (handle in network loop) // - one external router // handle external network first, only if NAT service is enabled if (networks != null) { if (!(networks.isEmpty()) && isNatEnabled()) { // get public net info - needed to set up source nat gateway NetworkVO pubNet = getPublicNetwork(physicalNetworkId); // locate subnet info SearchCriteria<VlanVO> sc = _vlanDao.createSearchCriteria(); sc.setParameters("network_id", pubNet.getId()); VlanVO vlanVO = _vlanDao.findOneBy(sc); // add tenant external network external TopologyData.Network network = topo.new Network(); network.setId("external"); network.setName("external"); network.setTenantId("external"); network.setTenantName("external"); String pubVlan = null; try { pubVlan = BroadcastDomainType.getValue(vlanVO.getVlanTag()); if (StringUtils.isNumeric(pubVlan)) { network.setVlan(Integer.valueOf(pubVlan)); } else { // untagged pubVlan = "0"; } } catch (URISyntaxException e) { e.printStackTrace(); } topo.addNetwork(network); } } // routerMap used internally for multiple updates to same tenant's router // add back to topo.routers after loop HashMap<String, RouterData> routerMap = new HashMap<String, RouterData>(); for (NetworkVO netVO : networks) { TopologyData.Network network = topo.new Network(); network.setId(netVO.getUuid()); network.setName(netVO.getName()); Integer vlan = null; if (netVO.getBroadcastUri() != null) { String vlanStr = BroadcastDomainType.getValue(netVO.getBroadcastUri()); if (StringUtils.isNumeric(vlanStr)) { vlan = Integer.valueOf(vlanStr); } else { // untagged vlan = 0; } } network.setVlan(vlan); network.setState(netVO.getState().name()); nics = _nicDao.listByNetworkId(netVO.getId()); List<Port> ports = new ArrayList<Port>(); String tenantId = null; String tenantName = null; // if VPC network, assign BCF tenant id with vpc uuid Vpc vpc = null; if (netVO.getVpcId() != null) { vpc = _vpcDao.acquireInLockTable(netVO.getVpcId()); } if (vpc != null) { tenantId = vpc.getUuid(); tenantName = vpc.getName(); } else { tenantId = netVO.getUuid(); tenantName = netVO.getName(); } for (NicVO nic : nics) { NetworkData netData = new NetworkData(); TopologyData.Port p = topo.new Port(); p.setAttachmentInfo(netData.new AttachmentInfo(nic.getUuid(), nic.getMacAddress())); VMInstanceVO vm = _vmDao.findById(nic.getInstanceId()); HostVO host = _hostDao.findById(vm.getHostId()); // if host not found, ignore this nic if (host == null) { continue; } String hostname = host.getName(); long zoneId = netVO.getDataCenterId(); String vmwareVswitchLabel = _networkModel.getDefaultGuestTrafficLabel(zoneId, HypervisorType.VMware); String[] labelArray = null; String vswitchName = null; if (vmwareVswitchLabel != null) { labelArray = vmwareVswitchLabel.split(","); vswitchName = labelArray[0]; } // hypervisor type: // kvm: ivs port name // vmware: specific portgroup naming convention String pgName = ""; if (host.getHypervisorType() == HypervisorType.KVM) { pgName = hostname; } else if (host.getHypervisorType() == HypervisorType.VMware) { pgName = hostname + "-" + vswitchName; } p.setHostId(pgName); p.setSegmentInfo(netData.new SegmentInfo(BroadcastDomainType.Vlan.name(), vlan)); p.setOwner(BigSwitchBcfApi.getCloudstackInstanceId()); List<AttachmentData.Attachment.IpAddress> ipList = new ArrayList<AttachmentData.Attachment.IpAddress>(); ipList.add(new AttachmentData().getAttachment().new IpAddress(nic.getIPv4Address())); p.setIpAddresses(ipList); p.setId(nic.getUuid()); p.setMac(nic.getMacAddress()); netData.getNetwork().setId(network.getId()); netData.getNetwork().setName(network.getName()); netData.getNetwork().setTenantId(tenantId); netData.getNetwork().setTenantName(tenantName); netData.getNetwork().setState(netVO.getState().name()); p.setNetwork(netData.getNetwork()); ports.add(p); } network.setTenantId(tenantId); network.setTenantName(tenantName); network.setPorts(ports); topo.addNetwork(network); // add router for network RouterData routerData; if (tenantId != null) { if (!routerMap.containsKey(tenantId)) { routerData = new RouterData(tenantId); routerMap.put(tenantId, routerData); } else { routerData = routerMap.get(tenantId); } routerData.getRouter().getAcls().addAll(listACLbyNetwork(netVO)); if (vpc != null) { routerData.getRouter().addExternalGateway(getPublicIpByVpc(vpc)); } else { routerData.getRouter().addExternalGateway(getPublicIpByNetwork(netVO)); } RouterInterfaceData intf = new RouterInterfaceData(tenantId, netVO.getGateway(), netVO.getCidr(), netVO.getUuid(), netVO.getName()); routerData.getRouter().addInterface(intf); } } for (RouterData rd : routerMap.values()) { topo.addRouter(rd.getRouter()); } return topo; }
From source file:org.hfoss.posit.android.sync.Communicator.java
/** * A wrapper(does some cleanup too) for sending HTTP GET requests to the URI * // w w w.j a va 2s . c o m * @param Uri * @return the request from the remote server */ public static String doHTTPGET(String Uri) { BasicHttpParams mHttpParams = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(mHttpParams, CONNECTION_TIMEOUT); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(mHttpParams, SOCKET_TIMEOUT); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); ThreadSafeClientConnManager mConnectionManager = new ThreadSafeClientConnManager(mHttpParams, registry); DefaultHttpClient mHttpClient = new DefaultHttpClient(mConnectionManager, mHttpParams); if (Uri == null) throw new NullPointerException("The URL has to be passed"); String responseString = null; HttpGet httpGet = new HttpGet(); try { httpGet.setURI(new URI(Uri)); } catch (URISyntaxException e) { Log.e(TAG, "doHTTPGet " + e.getMessage()); e.printStackTrace(); return "[Error] " + e.getMessage(); } Log.i(TAG, "doHTTPGet Uri = " + Uri); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { responseString = mHttpClient.execute(httpGet, responseHandler); } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException" + e.getMessage()); return "[Error] " + e.getMessage(); } catch (SocketTimeoutException e) { Log.e(TAG, "[Error: SocketTimeoutException]" + e.getMessage()); return "[Error] " + e.getMessage(); } catch (IOException e) { Log.e(TAG, e.getMessage()); return "[Error] " + e.getMessage(); } catch (Exception e) { Log.e(TAG, e.getMessage() + "what"); return "[Error] " + e.getMessage(); } Log.i(TAG, "doHTTPGet Response: " + responseString); return responseString; }
From source file:fr.eolya.utils.http.HttpLoader.java
private HttpGet getHttpGet(String url) { if (simulateHttps) url = url.replace("https://", "http://"); URI uri;//from ww w . j av a2s . co m try { uri = new URI(url); } catch (URISyntaxException e1) { e1.printStackTrace(); return null; } HttpGet httpGet = new HttpGet(uri); // Conditional Get if (!StringUtils.isEmpty(condGetLastModified) && !StringUtils.isEmpty(condGetETag)) { httpGet.addHeader(new BasicHeader("If-None-Match", condGetETag)); httpGet.addHeader(new BasicHeader("If-Modified-Since", condGetLastModified)); //httpGet.addHeader(new BasicHeader("Date", DateUtils.formatDate(new Date())); } return httpGet; }
From source file:org.apache.ode.test.BPELTestAbstract.java
protected File makeDeployDir(String deployDir) { String deployxml = deployDir + "/deploy.xml"; URL deployxmlurl = getClass().getResource(deployxml); if (deployxmlurl == null) { Assert.fail("Resource not found: " + deployxml); }/*w w w .j av a 2 s. c o m*/ try { return new File(deployxmlurl.toURI().getPath()).getParentFile(); } catch (URISyntaxException e) { e.printStackTrace(); Assert.fail(e.getMessage()); return null; } }
From source file:app.HadoopImporterWindowTopComponent.java
public static String loadNetworkLayersForTMN(String networkName, HadoopImporterWindowTopComponent comp) { StringBuffer q = new StringBuffer(); CloseableHttpClient httpClient = null; HttpGet httpGet = null;//from w ww. j av a 2s . co m CloseableHttpResponse response = null; try { httpClient = HttpClients.createDefault(); httpGet = new HttpGet(); String query = "[[Modification date::+]]|?Modification date|sort=Modification date|order=Ddesc"; String queryForLayerSQL = "[[Category:TMN_layer]][[belongs_to_TMN::" + networkName + "]]|?TMN_layer_name"; URI uri = new URI("http://semanpix.de/oldtimer/wiki/api.php?action=ask&format=json&query=" + encodeQuery(queryForLayerSQL)); String uri2 = "http://semanpix.de/oldtimer/wiki/api.php?action=ask&format=json&query=" + queryForLayerSQL; httpGet.setURI(uri); System.out.println("[Request:]\n" + uri2); if (comp != null) { comp.setQuery(uri2); } response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); StringBuffer sb = new StringBuffer(); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); sb.append(output); } if (comp != null) { comp.setResponse(sb.toString()); } JSONObject obj1 = new JSONObject(sb.toString()); JSONObject obj2 = obj1.getJSONObject("query"); JSONObject obj3 = obj2.getJSONObject("results"); Iterator<String> it = obj3.keys(); while (it.hasNext()) { String key = it.next(); JSONObject obj = obj3.getJSONObject(key); JSONObject obj4 = obj.getJSONObject("printouts"); String nln = obj4.optString("TMN layer name"); System.out.println(nln); q.append(nln.substring(2, nln.length() - 2) + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException ex) { Exceptions.printStackTrace(ex); } catch (JSONException ex) { Exceptions.printStackTrace(ex); } finally { try { if (response != null) { response.close(); } httpClient.close(); } catch (Exception ex) { ex.printStackTrace(); } } return q.toString(); }
From source file:app.HadoopImporterWindowTopComponent.java
static public String loadTMNListeFromMetastore(HadoopImporterWindowTopComponent comp) { StringBuffer q = new StringBuffer(); CloseableHttpClient httpClient = null; HttpGet httpGet = null;/*from w w w. j a va 2 s .c o m*/ CloseableHttpResponse response = null; try { httpClient = HttpClients.createDefault(); httpGet = new HttpGet(); String query = "[[Modification date::+]]|?Modification date|sort=Modification date|order=Ddesc"; String queryForLayerSQL = "[[Category:TMN]]|?TMN_name"; URI uri = new URI("http://semanpix.de/oldtimer/wiki/api.php?action=ask&format=json&query=" + encodeQuery(queryForLayerSQL)); String uri2 = "http://semanpix.de/oldtimer/wiki/api.php?action=ask&format=json&query=" + queryForLayerSQL; httpGet.setURI(uri); System.out.println("[Request:]\n" + uri2); if (comp != null) { comp.setQuery(uri2); } response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); StringBuffer sb = new StringBuffer(); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); sb.append(output); } if (comp != null) { comp.setResponse(sb.toString()); } JSONObject obj1 = new JSONObject(sb.toString()); JSONObject obj2 = obj1.getJSONObject("query"); JSONObject obj3 = obj2.getJSONObject("results"); Iterator it = obj3.keys(); while (it.hasNext()) { String key = (String) it.next(); JSONObject obj = obj3.getJSONObject(key); String nlnfull = obj.optString("fulltext"); JSONObject obj4 = obj.getJSONObject("printouts"); String nln = obj4.optString("TMN name"); System.out.println(nln); q.append(nln.substring(2, nln.length() - 2) + " : " + nlnfull + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException ex) { Exceptions.printStackTrace(ex); } catch (JSONException ex) { Exceptions.printStackTrace(ex); } finally { try { if (response != null) { response.close(); } httpClient.close(); } catch (Exception ex) { ex.printStackTrace(); } } return q.toString(); }
From source file:com.pearson.dashboard.util.Util.java
private static List<Release> retrieveRelease(RallyRestApi restApi, Configuration configuration) throws Exception { List<Release> releases = new ArrayList<Release>(); QueryRequest query = new QueryRequest("Release"); QueryFilter queryFilter = new QueryFilter("State", "=", "Active") .or(new QueryFilter("State", "=", "Planning")); query.setQueryFilter(queryFilter);//from ww w . j a v a2s .c o m QueryResponse projectDefects = null; boolean dataNotReceived = true; while (dataNotReceived) { try { projectDefects = restApi.query(query); dataNotReceived = false; JsonArray releasesArray = projectDefects.getResults(); for (int i = 0; i < releasesArray.size(); i++) { Release release = new Release(); JsonElement elements = releasesArray.get(i); JsonObject object = elements.getAsJsonObject(); if (!isReleaseAlreadyAdded(releases, object.get("_refObjectName").getAsString())) { release.setReleaseEndDate(object.get("ReleaseDate").getAsString()); release.setReleaseName(object.get("_refObjectName").getAsString()); release.setReleaseStartDate(object.get("ReleaseStartDate").getAsString()); releases.add(release); } } } catch (HttpHostConnectException connectException) { if (restApi != null) { restApi.close(); } try { restApi = loginRally(configuration); } catch (URISyntaxException e) { e.printStackTrace(); } } } return releases; }
From source file:org.seadpdt.impl.ROServicesImpl.java
@POST @Path("/") @Consumes(MediaType.APPLICATION_JSON)/* ww w. j av a2 s . c om*/ @Produces(MediaType.APPLICATION_JSON) public Response startROPublicationProcess(String publicationRequestString, @QueryParam("requestUrl") String requestURL, @QueryParam("oreId") String oreId) throws URISyntaxException { String messageString = ""; Document request = Document.parse(publicationRequestString); Document content = (Document) request.get("Aggregation"); if (content == null) { messageString += "Missing Aggregation "; } Document preferences = (Document) request.get("Preferences"); if (preferences == null) { messageString += "Missing Preferences "; } Object repository = request.get("Repository"); if (repository == null) { messageString += "Missing Respository "; } else { FindIterable<Document> iter = repositoriesCollection.find(new Document("orgidentifier", repository)); if (iter.first() == null) { messageString += "Unknown Repository: " + repository + " "; } } if (messageString.equals("")) { // Get organization from profile(s) // Add to base document Object creatorObject = content.get("Creator"); String ID = (String) content.get("Identifier"); BasicBSONList affiliations = new BasicBSONList(); if (creatorObject != null) { if (creatorObject instanceof ArrayList) { Iterator<String> iter = ((ArrayList<String>) creatorObject).iterator(); while (iter.hasNext()) { String creator = iter.next(); List<String> orgs = getOrganizationforPerson(creator); if (!orgs.isEmpty()) { affiliations.addAll(orgs); } } } else { // BasicDBObject - single value List<String> orgs = getOrganizationforPerson((String) creatorObject); if (!orgs.isEmpty()) { affiliations.addAll(orgs); } } } request.append("Affiliations", affiliations); // Add first status message List<DBObject> statusreports = new ArrayList<DBObject>(); DBObject status = BasicDBObjectBuilder.start() .add("date", DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis()))) .add("reporter", Constants.serviceName).add("stage", "Receipt Acknowledged") .add("message", "request recorded and processing will begin").get(); statusreports.add(status); request.append("Status", statusreports); // Create initial status message - add // Add timestamp // Generate ID - by calling Workflow? // Add doc, return 201 String newMapURL = requestURL + "/" + ID + "/oremap"; URI uri = new URI(newMapURL); uri = uri.normalize(); content.put("@id", uri.toString() + "#aggregation"); content.put("authoratativeMap", oreId); publicationsCollection.insertOne(request); URI resource = null; try { resource = new URI("./" + ID); } catch (URISyntaxException e) { // Should not happen given simple ids e.printStackTrace(); } return Response.created(resource).entity(new Document("identifier", ID)).build(); } else { return Response.status(ClientResponse.Status.BAD_REQUEST).entity(messageString).build(); } }