List of usage examples for java.net URISyntaxException printStackTrace
public void printStackTrace()
From source file:org.apache.hama.ml.perception.SmallMultiLayerPerceptron.java
/** * Read the model meta-data from the specified location. * //from w w w. j av a 2 s . c om * @throws IOException */ @Override protected void readFromModel() throws IOException { Configuration conf = new Configuration(); try { URI uri = new URI(modelPath); FileSystem fs = FileSystem.get(uri, conf); FSDataInputStream is = new FSDataInputStream(fs.open(new Path(modelPath))); this.readFields(is); if (!this.MLPType.equals(this.getClass().getName())) { throw new IllegalStateException( String.format("Model type incorrect, cannot load model '%s' for '%s'.", this.MLPType, this.getClass().getName())); } } catch (URISyntaxException e) { e.printStackTrace(); } }
From source file:org.dasein.cloud.terremark.TerremarkMethod.java
public Document invoke(boolean debug) throws TerremarkException, CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + TerremarkMethod.class.getName() + ".invoke(" + debug + ")"); }/* w w w . j a v a2 s. co m*/ try { if (logger.isDebugEnabled()) { logger.debug("Talking to server at " + url); } if (parameters != null) { URIBuilder uri = null; try { uri = new URIBuilder(url); } catch (URISyntaxException e) { e.printStackTrace(); } for (NameValuePair parameter : parameters) { uri.addParameter(parameter.getName(), parameter.getValue()); } url = uri.toString(); } HttpUriRequest method = null; if (methodType.equals(HttpMethodName.GET)) { method = new HttpGet(url); } else if (methodType.equals(HttpMethodName.POST)) { method = new HttpPost(url); } else if (methodType.equals(HttpMethodName.DELETE)) { method = new HttpDelete(url); } else if (methodType.equals(HttpMethodName.PUT)) { method = new HttpPut(url); } else if (methodType.equals(HttpMethodName.HEAD)) { method = new HttpHead(url); } else { method = new HttpGet(url); } HttpResponse status = null; try { HttpClient client = new DefaultHttpClient(); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); attempts++; String proxyHost = provider.getProxyHost(); if (proxyHost != null) { int proxyPort = provider.getProxyPort(); boolean ssl = url.startsWith("https"); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http")); } for (Map.Entry<String, String> entry : headers.entrySet()) { method.addHeader(entry.getKey(), entry.getValue()); } if (body != null && body != "" && (methodType.equals(HttpMethodName.PUT) || methodType.equals(HttpMethodName.POST))) { try { HttpEntity entity = new StringEntity(body, "UTF-8"); ((HttpEntityEnclosingRequestBase) method).setEntity(entity); } catch (UnsupportedEncodingException e) { logger.warn(e); } } if (wire.isDebugEnabled()) { wire.debug(methodType.name() + " " + method.getURI()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } if (body != null) { wire.debug(body); } } try { status = client.execute(method); if (wire.isDebugEnabled()) { wire.debug("HTTP STATUS: " + status); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int statusCode = status.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_ACCEPTED) { try { InputStream input = status.getEntity().getContent(); try { return parseResponse(input); } finally { input.close(); } } catch (IOException e) { logger.error("Error parsing response from Teremark: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, statusCode, null, e.getMessage()); } } else if (statusCode == HttpStatus.SC_NO_CONTENT) { logger.debug("Recieved no content in response. Creating an empty doc."); DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return docBuilder.newDocument(); } else if (statusCode == HttpStatus.SC_FORBIDDEN) { String msg = "OperationNotAllowed "; try { msg += parseResponseToString(status.getEntity().getContent()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } wire.error(msg); throw new TerremarkException(statusCode, "OperationNotAllowed", msg); } else { String response = "Failed to parse response."; ParsedError parsedError = null; try { response = parseResponseToString(status.getEntity().getContent()); parsedError = parseErrorResponse(response); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("Received " + status + " from " + url); } if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { if (attempts >= 5) { String msg; wire.warn(response); if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) { msg = "Cloud service is currently unavailable."; } else { msg = "The cloud service encountered a server error while processing your request."; try { msg = msg + "Response from server was:\n" + response; } catch (RuntimeException runException) { logger.warn(runException); } catch (Error error) { logger.warn(error); } } wire.error(response); logger.error(msg); if (parsedError != null) { throw new TerremarkException(parsedError); } else { throw new CloudException("HTTP Status " + statusCode + msg); } } else { try { Thread.sleep(5000L); } catch (InterruptedException e) { /* ignore */ } return invoke(); } } wire.error(response); if (parsedError != null) { throw new TerremarkException(parsedError); } else { String msg = "\nResponse from server was:\n" + response; logger.error(msg); throw new CloudException("HTTP Status " + statusCode + msg); } } } finally { try { if (status != null) { EntityUtils.consume(status.getEntity()); } } catch (IOException e) { e.printStackTrace(); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT - " + TerremarkMethod.class.getName() + ".invoke()"); } } }
From source file:org.epop.dataprovider.acmdigital.ACMDigitalLibrarySearch.java
@Override /**getHTMLDoc//from w w w .j a v a 2 s. c o m * connect to the server and return the response at the query, call the method "getParameters" * in order to have parameters to create the uri * @return responseBody A string that contains the response at the query */ protected Reader getHTMLDoc(String htmlParams, int pageTurnLimit, boolean initialWait) { boolean exit = false; // flag to exit if the author was not found URI uri; String responseBody = ""; try { if (initialWait) Thread.sleep(DELAY); uri = new URI(BASE_URL + "?" + htmlParams); HTMLPage page = new HTMLPage(uri); responseBody = page.getRawCode(); if (pageTurnLimit == 0) return new StringReader(responseBody); int counter = 1; // there are 20 records for page String newResponseBody = responseBody; // Verifies if the author was not found if (responseBody.contains("was not found.")) { exit = true; } // take all the pages if the author was found while (newResponseBody.contains("next</a>") && !exit) { Thread.sleep(DELAY); URI newUri = new URI(BASE_URL + "?" + htmlParams + "&start=" + String.valueOf((counter * 20) + 1)); newResponseBody = new HTMLPage(newUri).getRawCode(); responseBody = responseBody + newResponseBody; if (pageTurnLimit == counter) return new StringReader(responseBody); counter++; } } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } // logger.debug("responseBody =\n" + responseBody); // return the response return new StringReader(responseBody); }
From source file:org.epop.dataprovider.msacademic.MicrosoftAcademicSearch.java
private Literature extractPaper(Element element) { LiteratureBuilder litBuilder = new LiteratureBuilder(); URI pageURI = null;//w ww.j ava2 s .c o m for (Element s : element.getAllElements(HTMLElementName.DIV)) { Attribute classAttr = s.getStartTag().getAttributes().get("class"); if (classAttr != null) { if (classAttr.getValue().equals("title-fullwidth") || classAttr.getValue().equals("title")) { String id = s.getStartTag().getAttributes().get("id").getValue().replace("divTitle", ""); for (Element a : s.getAllElements(HTMLElementName.A)) { // System.out.println(a.toString()); Attribute classAttr2 = a.getStartTag().getAttributes().get("id"); if (classAttr2 != null) { if (classAttr2.getValue().equals(id + "Title")) { Source htmlSource = new Source(a.getContent().toString()); String paperTitle = StringUtils .formatInLineSingleSpace(htmlSource.getTextExtractor().toString()); litBuilder.setTitle(paperTitle); String pageURLString = "http://academic.research.microsoft.com" + a.getAttributeValue("href").substring(2); if (litBuilder.getWebsiteURLs() == null) litBuilder.setWebsiteURLs(new HashSet<Link>()); try { pageURI = new URI(pageURLString); litBuilder.getWebsiteURLs().add(new Link("MS Academic", pageURI)); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } Matcher idMatcher = ID_PATTERN.matcher(pageURLString); if (idMatcher.find()) litBuilder.setMsAcademicID(idMatcher.group(1)); // else // TODO error handling } else if (classAttr2.getValue().equals(id + "Citation")) { Source htmlSource = new Source(a.getContent().toString()); String citedInfo = StringUtils.formatInLineSingleSpace( htmlSource.getTextExtractor().toString().replaceAll("Citations: ", "")); try { Integer numCitations = Integer.parseInt(citedInfo); litBuilder.setMsAcademicNumCitations(numCitations); } catch (NumberFormatException e) { // TODO error handling e.printStackTrace(); } } } } } else if (classAttr.getValue().equals("content")) { // authors String[] parts = s.getContent().toString().split("<span class=\"span-break\"\\s?>, </span>"); for (String part : parts) { AuthorBuilder authBuilder = new AuthorBuilder(); // ID Source htmlSource = new Source(part); if (htmlSource.getFirstElement("a") != null) { String authorURL = htmlSource.getFirstElement("a").getAttributeValue("href"); java.util.regex.Matcher m = AUTHOR_ID_PATTERN.matcher(authorURL); if (m.find()) { authBuilder.setMsAcademicID(m.group(1)); } else { // TODO feedback } } // name String nameString = htmlSource.getTextExtractor().toString(); try { Utils.setFirstMiddleLastNameFromNameString(authBuilder, nameString); if (litBuilder.getAuthors() == null) litBuilder.setAuthors(new HashSet<Author>()); litBuilder.getAuthors().add(authBuilder.getObject()); } catch (PatternMismatchException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else if (classAttr.getValue().equals("conference")) { Source htmlSource = new Source(s.getContent().toString()); if (htmlSource.getFirstElementByClass("conference-name") != null) litBuilder.setPublicationContext( htmlSource.getFirstElementByClass("conference-name").getTextExtractor().toString()); if (htmlSource.getFirstElement("span") != null) { String contextType = htmlSource.getFirstElement("span").getTextExtractor().toString(); if (contextType.equals("Journal:")) litBuilder.setType(LiteratureType.JOURNAL_PAPER); if (contextType.equals("Conference:")) litBuilder.setType(LiteratureType.CONFERENCE_PAPER); } for (Element q : s.getAllElements(HTMLElementName.SPAN)) { // System.out.println(q.toString()); Attribute classAttr3 = q.getStartTag().getAttributes().get("class"); if (classAttr3 != null && classAttr3.getValue().equals("year")) { htmlSource = new Source(q.getContent().toString()); String venueYearStr = StringUtils .formatInLineSingleSpace(htmlSource.getTextExtractor().toString()); venueYearStr = venueYearStr.substring(venueYearStr.lastIndexOf(",") + 1).trim(); Integer venueYear; try { venueYear = Integer.parseInt(venueYearStr); } catch (NumberFormatException ae) { venueYear = null; } litBuilder.setYear(venueYear); break; } // class="year" } } } } if (pageURI != null) { HTMLPage page; try { try { Thread.sleep(1861); } catch (InterruptedException e1) { e1.printStackTrace(); } page = new HTMLPage(pageURI); try { Node abstractTextNode = page.getNodeByXPath(".//div[@class='abstract']/span"); if (abstractTextNode != null) litBuilder.setAbstractText(abstractTextNode.getTextContent()); } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { String doiString = page .getStringByXPath(".//*[@id='ctl00_MainContent_PaperItem_hypDOIText']/text()"); if (!doiString.isEmpty()) litBuilder.setDOI(doiString); } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException | ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return litBuilder.getObject(); }
From source file:org.epop.dataprovider.googlescholar.GoogleScholarProvider.java
@Override protected List<Literature> parsePage(Reader page) throws DatalayerException { List<Literature> papers = new ArrayList<Literature>(); Document doc = null;/* w w w.j a va2s . c o m*/ try { StringBuilder builder = new StringBuilder(); int charsRead = -1; char[] chars = new char[100]; do { charsRead = page.read(chars, 0, chars.length); // if we have valid chars, append them to end of string. if (charsRead > 0) builder.append(chars, 0, charsRead); } while (charsRead > 0); doc = Jsoup.parse(builder.toString()); } catch (IOException e) { e.printStackTrace(); } // for (Document doc : docs) { for (Element article : doc.select(".gs_r")) { try { LiteratureBuilder litBuilder = new LiteratureBuilder(); // type String typeString = article.select(".gs_ct2").text(); if (typeString == null) typeString = ""; if (typeString.equals("[C]")) continue; // skip citations litBuilder.setType(getLiteratureType(typeString)); // title String title = article.select(".gs_rt a").text(); title = title.replaceAll("\u0097", "-"); title = title.replaceAll("", "..."); if (title.isEmpty()) throw new DatalayerException("title retrieved by parsing is empty"); litBuilder.setTitle(title); // website URL if (litBuilder.getWebsiteURLs() == null) litBuilder.setWebsiteURLs(new HashSet<Link>()); try { String linkURL = article.select(".gs_rt a").attr("href"); litBuilder.getWebsiteURLs().add(new Link(linkURL)); } catch (URISyntaxException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } try { // cluster link String googleLinkURL = "http://scholar.google.com" + article.select(".gs_fl .gs_nph").attr("href"); litBuilder.getWebsiteURLs().add(new Link("Google Scholar", googleLinkURL)); // scholar ID Matcher idMatcher = ID_PATTERN.matcher(googleLinkURL); if (idMatcher.find()) litBuilder.setgScholarID(idMatcher.group(1)); // else // TODO error handling } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String abstractText = article.select(".gs_rs").text(); litBuilder.setAbstractText(abstractText); String rawHTML = article.select(".gs_a").html(); if (rawHTML.isEmpty()) // no authors continue; // split by " - " (authors - publication, year - publisher) String[] splits = rawHTML.split(" - "); // if (splits.length != 3) // throw new DatalayerException( // "dashTokenizer should have three sections (authors - publication, year - publisher), found " // + splits.length // + "; maybe Google Scholar layout has changed"); String namesHTML = "", publicationHTML = "", publisherHTML = ""; if (splits.length > 0) { namesHTML = splits[0]; namesHTML = namesHTML.replace(", ", ""); } if (splits.length == 2) { publisherHTML = splits[1]; } if (splits.length > 3) { publicationHTML = splits[1]; publisherHTML = splits[2]; } // authors try { List<Author> authors = getAuthorsFromHTMLSection(namesHTML); litBuilder.setAuthors(new HashSet<>(authors)); } catch (PatternMismatchException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // publication String[] commaSplit = publicationHTML.split(", "); if (commaSplit.length == 2) { String publication = commaSplit[0]; publication = publication.replaceAll("\u0097", "-"); publication = publication.replaceAll("", "..."); litBuilder.setPublicationContext(publication); try { Integer year = Integer.parseInt(commaSplit[1]); litBuilder.setYear(year); } catch (NumberFormatException e) { // throw new ServiceException( // "publicationHTML subsection has invalid format: failed to parse publication year"); // TODO (low) logging } } else { // TODO logging/notify user } // publisher litBuilder.setPublisher(publisherHTML); // citations String citedby = article.select(".gs_fl a[href*=cites]").text(); Matcher cm = CITES_PATTERN.matcher(citedby); try { int cites = cm.find() ? Integer.parseInt(cm.group(1)) : 0; litBuilder.setgScholarNumCitations(cites); } catch (NumberFormatException e) { // TODO } // fulltext String fulltextURL = article.select("div.gs_md_wp.gs_ttss a").attr("href"); Set<Link> fullLinks = new HashSet<>(); try { fullLinks.add(new Link(fulltextURL)); litBuilder.setFulltextURLs(fullLinks); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } papers.add(litBuilder.getObject()); } catch (Exception e) { malformed.add(e.getMessage()); } } // } // if (headerContent.startsWith("User profiles")) { // // only the first part // Element hrefPart = seg.getAllElements().get(0); // String link = hrefPart.getAttributeValue("href"); // assert link.startsWith("/citations"); // String[] data = link.split("[?|&|=]"); // System.out.println("id found for user " + data[2]); // return GoogleScholarGetterFromId.getFromId(data[2]); // // docs.clear(); System.err.println(malformed + " " + malformed.size()); return papers; }
From source file:net.micode.fileexplorer.FileViewActivity.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mActivity = getActivity();/*from w ww .jav a 2s. c o m*/ // getWindow().setFormat(android.graphics.PixelFormat.RGBA_8888); mRootView = inflater.inflate(R.layout.file_explorer_list, container, false); ActivitiesManager.getInstance().registerActivity(ActivitiesManager.ACTIVITY_FILE_VIEW, mActivity); mFileCagetoryHelper = new FileCategoryHelper(mActivity); mFileViewInteractionHub = new FileViewInteractionHub(this); Intent intent = mActivity.getIntent(); String action = intent.getAction(); if (!TextUtils.isEmpty(action) && (action.equals(Intent.ACTION_PICK) || action.equals(Intent.ACTION_GET_CONTENT))) { mFileViewInteractionHub.setMode(Mode.Pick); boolean pickFolder = intent.getBooleanExtra(PICK_FOLDER, false); if (!pickFolder) { String[] exts = intent.getStringArrayExtra(EXT_FILTER_KEY); if (exts != null) { mFileCagetoryHelper.setCustomCategory(exts); } } else { mFileCagetoryHelper.setCustomCategory(new String[] {} /*folder only*/); mRootView.findViewById(R.id.pick_operation_bar).setVisibility(View.VISIBLE); mRootView.findViewById(R.id.button_pick_confirm).setOnClickListener(new OnClickListener() { public void onClick(View v) { try { Intent intent = Intent.parseUri(mFileViewInteractionHub.getCurrentPath(), 0); mActivity.setResult(Activity.RESULT_OK, intent); mActivity.finish(); } catch (URISyntaxException e) { e.printStackTrace(); } } }); mRootView.findViewById(R.id.button_pick_cancel).setOnClickListener(new OnClickListener() { public void onClick(View v) { mActivity.finish(); } }); } } else { mFileViewInteractionHub.setMode(Mode.View); } mFileListView = (ListView) mRootView.findViewById(R.id.file_path_list); mFileIconHelper = new FileIconHelper(mActivity); mAdapter = new FileListAdapter(mActivity, R.layout.file_browser_item, mFileNameList, mFileViewInteractionHub, mFileIconHelper); boolean baseSd = intent.getBooleanExtra(GlobalConsts.KEY_BASE_SD, !FileExplorerPreferenceActivity.isReadRoot(mActivity)); Log.i(LOG_TAG, "baseSd = " + baseSd); String rootDir = intent.getStringExtra(ROOT_DIRECTORY); if (!TextUtils.isEmpty(rootDir)) { if (baseSd && this.sdDir.startsWith(rootDir)) { rootDir = this.sdDir; } } else { rootDir = baseSd ? this.sdDir : GlobalConsts.ROOT_PATH; } mFileViewInteractionHub.setRootPath(rootDir); String currentDir = FileExplorerPreferenceActivity.getPrimaryFolder(mActivity); Uri uri = intent.getData(); if (uri != null) { if (baseSd && this.sdDir.startsWith(uri.getPath())) { currentDir = this.sdDir; } else { currentDir = uri.getPath(); } } mFileViewInteractionHub.setCurrentPath(currentDir); Log.i(LOG_TAG, "CurrentDir = " + currentDir); mBackspaceExit = (uri != null) && (TextUtils.isEmpty(action) || (!action.equals(Intent.ACTION_PICK) && !action.equals(Intent.ACTION_GET_CONTENT))); mFileListView.setAdapter(mAdapter); mFileViewInteractionHub.refreshFileList(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addDataScheme("file"); mActivity.registerReceiver(mReceiver, intentFilter); updateUI(); setHasOptionsMenu(true); return mRootView; }
From source file:org.eclipse.om2m.comm.coap.CoapServer.java
/** * Converts a {@link CoapServerRequest} to a {@link RequestIndication} and uses it to invoke the SCL service. * Converts the received {@link ResponseConfirm} to a {@link CoapServerResponse} and returns it back. *///from ww w . j a va 2 s . c o m public Response service(Request request) throws SocketException, IOException { logServiceTracker = new ServiceTracker( FrameworkUtil.getBundle(CoapMessageDeliverer.class).getBundleContext(), org.osgi.service.log.LogService.class.getName(), null); logServiceTracker.open(); logservice = (LogService) logServiceTracker.getService(); // store the MId and the Token int mid = request.getMID(); byte[] token = request.getToken(); /**Construct a requestIndication Object from the coap request*/ RequestIndication requestIndication = new RequestIndication(); ResponseConfirm responseConfirm = new ResponseConfirm(); OptionSet options = request.getOptions(); URI uri = null; try { uri = new URI(request.getURI()); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } String targetID = ""; if (uri.getPath().split(context + "/")[1] != null) { ; targetID = uri.getPath().split(context)[1]; } String base = ""; String representation = request.getPayloadString(); requestIndication.setBase(base); requestIndication.setTargetID(targetID); requestIndication.setRepresentation(representation); //Get the method out of the code of CoAP CoAP.Code code = request.getCode(); String coapMethod = null; switch (code) { case GET: coapMethod = "RETRIEVE"; break; case POST: if (request.getPayloadString().isEmpty()) { coapMethod = "EXECUTE"; } else { coapMethod = "CREATE"; } break; case PUT: coapMethod = "UPDATE"; break; case DELETE: coapMethod = "DELETE"; break; } //Get the Method requestIndication.setMethod(coapMethod); //Get the request parameters String queryString = options.getURIQueryString(); Map<String, List<String>> parameters = getParamsFromQuery(queryString); if (options.getURIQueryString() != null) { requestIndication.setParameters(parameters); } //set the options from the requestIndication parameters if (parameters.containsKey("Authorization")) { requestIndication.setRequestingEntity(parameters.get("Authorization").get(0)); } if (parameters.containsKey("authorization")) { requestIndication.setRequestingEntity(parameters.get("authorization").get(0)); } //sending the standard request to the Scl and getting a standard response if (scl != null) { responseConfirm = scl.doRequest(requestIndication); LOGGER.info("check point: requestIndication sent and waiting for responseConfirm"); logservice.log(LogService.LOG_ERROR, "check point: requestIndication sent and waiting for responseConfirm"); } else { responseConfirm = new ResponseConfirm(StatusCode.STATUS_SERVICE_UNAVAILABLE, "SCL service not installed"); } boolean isEmptyResponse = false; // check if we have a payload if (responseConfirm.getRepresentation() == null || responseConfirm.getRepresentation().isEmpty()) { isEmptyResponse = true; } double statusCode = getCoapStatusCode(responseConfirm.getStatusCode(), isEmptyResponse); LOGGER.info("check point : The code is " + statusCode); logservice.log(LogService.LOG_ERROR, "check point : The code is " + statusCode); /**transformation of the code to create the CoAP response to be returned*/ ResponseCode resCode = ResponseCode.VALID; switch (responseConfirm.getStatusCode()) { case STATUS_OK: resCode = ResponseCode.CHANGED; break; case STATUS_DELETED: resCode = ResponseCode.DELETED; break; case STATUS_BAD_REQUEST: resCode = ResponseCode.BAD_REQUEST; break; case STATUS_CREATED: resCode = ResponseCode.CREATED; break; case STATUS_NOT_FOUND: resCode = ResponseCode.NOT_FOUND; break; case STATUS_FORBIDDEN: resCode = ResponseCode.FORBIDDEN; break; case STATUS_METHOD_NOT_ALLOWED: resCode = ResponseCode.METHOD_NOT_ALLOWED; break; case STATUS_UNSUPPORTED_MEDIA_TYPE: resCode = ResponseCode.UNSUPPORTED_CONTENT_FORMAT; break; case STATUS_PERMISSION_DENIED: resCode = ResponseCode.UNAUTHORIZED; break; case STATUS_INTERNAL_SERVER_ERROR: resCode = ResponseCode.INTERNAL_SERVER_ERROR; break; case STATUS_NOT_IMPLEMENTED: resCode = ResponseCode.NOT_IMPLEMENTED; break; case STATUS_AUTHORIZATION_NOT_ADDED: resCode = ResponseCode.UNAUTHORIZED; break; default: resCode = ResponseCode.SERVICE_UNAVAILABLE; } LOGGER.info("the responseConfirm: " + responseConfirm); logservice.log(LogService.LOG_ERROR, "the responseConfirm: " + responseConfirm); // creation of the CoAP Response Response response = new Response(resCode); if (responseConfirm.getRepresentation() != null) { //filling in the fields of the Coap response response.setPayload(responseConfirm.getRepresentation()); } response.setMID(mid); //request.getOptions().setContentFormat(MediaTypeRegistry.TEXT_XML); if (!(token == null)) { response.setToken(token); } if (request.getType().equals(CoAP.Type.CON)) { CoAP.Type coapType = CoAP.Type.ACK; response.setType(coapType); } LOGGER.info("CoAP Response parameters set"); logservice.log(LogService.LOG_ERROR, "CoAP Response parameters set"); return response; }
From source file:org.lobid.lodmill.PipeLobidOrganisationEnrichment.java
private void startQREncodeEnrichment() { if (this.postalcode == null || this.street == null || this.locality == null) return;//from w ww .j av a2s. co m String qrCodeText = createQrCodeText(); try { String isil = (new URI(super.subject)).getPath().replaceAll("/.*/", ""); QRENCODER.createQRImage(qrFilePath + isil, qrCodeText, (int) (java.lang.Math.sqrt(qrCodeText.length() * 10) + 20) * 2); this.model.add(this.model.createResource(super.subject), this.model.createProperty(LV_CONTACTQR), this.model.asRDFNode(NodeFactory .createURI(QR_URI_PATH + isil + QREncoder.FILE_SUFFIX + "." + QREncoder.FILE_TYPE))); } catch (URISyntaxException e) { e.printStackTrace(); } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.basho.riak.client.http.util.ClientHelper.java
/** * Perform and HTTP request and return the resulting response using the * internal HttpClient./* www .j a v a2 s . c om*/ * * @param bucket * Bucket of the object receiving the request. * @param key * Key of the object receiving the request or null if the request * is for a bucket. * @param httpMethod * The HTTP request to perform; must not be null. * @param meta * Extra HTTP headers to attach to the request. Query parameters * are ignored; they should have already been used to construct * <code>httpMethod</code> and query parameters. * @param streamResponse * If true, the connection will NOT be released. Use * HttpResponse.getHttpMethod().getResponseBodyAsStream() to get * the response stream; HttpResponse.getBody() will return null. * * @return The HTTP response returned by Riak from executing * <code>httpMethod</code>. * * @throws RiakIORuntimeException * If an error occurs during communication with the Riak server * (i.e. HttpClient threw an IOException) */ HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta, boolean streamResponse) { if (meta != null) { Map<String, String> headers = meta.getHeaders(); for (String header : headers.keySet()) { httpMethod.addHeader(header, headers.get(header)); } Map<String, String> queryParams = meta.getQueryParamMap(); if (!queryParams.isEmpty()) { URI originalURI = httpMethod.getURI(); List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name()); List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery); for (Map.Entry<String, String> qp : queryParams.entrySet()) { newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue())); } // For this, HC4.1 authors, I hate you URI newURI; try { newURI = new URIBuilder(originalURI).setQuery(URLEncodedUtils.format(newQuery, "UTF-8")) .build(); } catch (URISyntaxException e) { e.printStackTrace(); throw new RiakIORuntimeException(e); } httpMethod.setURI(newURI); } } HttpEntity entity = null; try { org.apache.http.HttpResponse response = httpClient.execute(httpMethod); int status = 0; if (response.getStatusLine() != null) { status = response.getStatusLine().getStatusCode(); } Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders()); byte[] body = null; InputStream stream = null; entity = response.getEntity(); if (streamResponse) { stream = entity.getContent(); } else { if (null != entity) { body = EntityUtils.toByteArray(entity); } } key = extractKeyFromResponseIfItWasNotAlreadyProvided(key, response); return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod); } catch (IOException e) { httpMethod.abort(); return toss(new RiakIORuntimeException(e)); } finally { if (!streamResponse && entity != null) { try { EntityUtils.consume(entity); } catch (IOException e) { // NO-OP } } } }
From source file:it.cnr.icar.eric.server.security.authorization.RegistryAttributeFinderModule.java
/** Get the object from the specified subject attribute id. * * @param context//w w w . ja v a 2 s . c om * @param subjectAttributeId * @param subjectCategory * @return */ private Object getSubjectObject(EvaluationCtx context, String subjectAttributeId, URI subjectCategory) { Object obj = null; try { EvaluationResult result = context.getSubjectAttribute(new URI(ObjectAttribute.identifier), new URI(subjectAttributeId), subjectCategory); AttributeValue attrValue = result.getAttributeValue(); BagAttribute bagAttr = (BagAttribute) attrValue; if (bagAttr.size() == 1) { Iterator<?> iter = bagAttr.iterator(); ObjectAttribute objAttr = (ObjectAttribute) iter.next(); if (objAttr != null) { obj = objAttr.getValue(); } } } catch (URISyntaxException e) { e.printStackTrace(); } return obj; }