List of usage examples for java.net URI toASCIIString
public String toASCIIString()
From source file:org.apache.olingo.client.core.serialization.ODataBinderImpl.java
@Override public ClientEntitySet getODataEntitySet(final ResWrap<EntityCollection> resource) { if (LOG.isDebugEnabled()) { final StringWriter writer = new StringWriter(); try {// w ww.java 2 s . c o m client.getSerializer(ContentType.JSON).write(writer, resource.getPayload()); } catch (final ODataSerializerException e) { LOG.debug("EntitySet -> ODataEntitySet:\n{}", writer.toString()); } writer.flush(); LOG.debug("EntitySet -> ODataEntitySet:\n{}", writer.toString()); } final URI base = resource.getContextURL() == null ? resource.getPayload().getBaseURI() : ContextURLParser.parse(resource.getContextURL()).getServiceRoot(); final URI next = resource.getPayload().getNext(); final ClientEntitySet entitySet = next == null ? client.getObjectFactory().newEntitySet() : client.getObjectFactory().newEntitySet(URIUtils.getURI(base, next.toASCIIString())); if (resource.getPayload().getCount() != null) { entitySet.setCount(resource.getPayload().getCount()); } for (Operation op : resource.getPayload().getOperations()) { ClientOperation operation = new ClientOperation(); operation.setTarget(URIUtils.getURI(base, op.getTarget())); operation.setTitle(op.getTitle()); operation.setMetadataAnchor(op.getMetadataAnchor()); entitySet.getOperations().add(operation); } for (Entity entityResource : resource.getPayload().getEntities()) { add(entitySet, getODataEntity( new ResWrap<Entity>(resource.getContextURL(), resource.getMetadataETag(), entityResource))); } if (resource.getPayload().getDeltaLink() != null) { entitySet.setDeltaLink(URIUtils.getURI(base, resource.getPayload().getDeltaLink())); } odataAnnotations(resource.getPayload(), entitySet); return entitySet; }
From source file:org.dasein.cloud.ibm.sce.SCEMethod.java
public @Nullable Document getAsXML(@Nonnull URI uri, @Nonnull String resource) throws CloudException, InternalException { Logger std = SCE.getLogger(SCEMethod.class, "std"); Logger wire = SCE.getLogger(SCEMethod.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + SCEMethod.class.getName() + ".get(" + uri + ")"); }/* w ww .ja va2 s . com*/ if (wire.isDebugEnabled()) { wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); wire.debug(""); } try { HttpClient client = getClient(); HttpUriRequest get = new HttpGet(uri); get.addHeader("Accept", "text/xml"); if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { APITrace.trace(provider, resource); response = client.execute(get); status = response.getStatusLine(); } catch (IOException e) { std.error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (std.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (std.isDebugEnabled()) { std.debug("get(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { return null; } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { std.error("get(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String body; if (entity == null) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), body); } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } InputStream input; try { input = entity.getContent(); } catch (IOException e) { std.error("get(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); if (std.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } return parseResponse(input, true); } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + SCEMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); } } }
From source file:mSearch.filmlisten.FilmlisteLesen.java
private InputStream getInputStreamForLocation(String source) throws IOException, URISyntaxException { InputStream in;//from w ww. j ava 2s .c o m long size = 0; final URI uri; if (source.startsWith("http")) { uri = new URI(source); //remote address for internet download HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setRequestProperty("User-Agent", Config.getUserAgent()); if (conn.getResponseCode() < 400) { size = conn.getContentLengthLong(); } in = new ProgressMonitorInputStream(conn.getInputStream(), size, new InputStreamProgressMonitor() { private int oldProgress = 0; @Override public void progress(long bytesRead, long size) { final int iProgress = (int) (bytesRead * 100 / size); if (iProgress != oldProgress) { oldProgress = iProgress; notifyProgress(uri.toASCIIString(), "Download", iProgress); } } }); } else { //local file notifyProgress(source, "Download", PROGRESS_MAX); in = new FileInputStream(source); } return in; }
From source file:org.apache.olingo.fit.v4.MediaEntityTestITCase.java
private void create(final ODataFormat format) throws IOException { final String random = RandomStringUtils.random(110); final InputStream input = IOUtils.toInputStream(random); final URI uri = client.newURIBuilder(testDemoServiceRootURL).appendEntitySetSegment("Advertisements") .build();//from w w w. jav a 2s . c o m final ODataMediaEntityCreateRequest<ODataEntity> createReq = client.getCUDRequestFactory() .getMediaEntityCreateRequest(uri, input); final MediaEntityCreateStreamManager<ODataEntity> streamManager = createReq.payloadManager(); final ODataMediaEntityCreateResponse<ODataEntity> createRes = streamManager.getResponse(); assertEquals(201, createRes.getStatusCode()); final Collection<String> location = createRes.getHeader(HeaderName.location); assertNotNull(location); final URI createdLocation = URI.create(location.iterator().next()); final ODataEntity changes = client.getObjectFactory() .newEntity(new FullQualifiedName("ODataDemo.Advertisement")); changes.getProperties() .add(client.getObjectFactory().newPrimitiveProperty("AirDate", getClient().getObjectFactory().newPrimitiveValueBuilder() .setType(EdmPrimitiveTypeKind.DateTimeOffset).setValue(Calendar.getInstance()) .build())); final ODataEntityUpdateRequest<ODataEntity> updateReq = getClient().getCUDRequestFactory() .getEntityUpdateRequest(createdLocation, UpdateType.PATCH, changes); updateReq.setFormat(format); final ODataEntityUpdateResponse<ODataEntity> updateRes = updateReq.execute(); assertEquals(204, updateRes.getStatusCode()); final ODataMediaRequest retrieveReq = client.getRetrieveRequestFactory() .getMediaEntityRequest(client.newURIBuilder(createdLocation.toASCIIString()).build()); final ODataRetrieveResponse<InputStream> retrieveRes = retrieveReq.execute(); assertEquals(200, retrieveRes.getStatusCode()); final byte[] actual = new byte[Integer.parseInt(retrieveRes.getHeader("Content-Length").iterator().next())]; IOUtils.read(retrieveRes.getBody(), actual, 0, actual.length); assertEquals(random, new String(actual)); }
From source file:org.apache.olingo.fit.base.MediaEntityTestITCase.java
private void create(final ContentType contentType) throws IOException { final String random = RandomStringUtils.random(110); final InputStream input = IOUtils.toInputStream(random); final URI uri = client.newURIBuilder(testDemoServiceRootURL).appendEntitySetSegment("Advertisements") .build();/*ww w . j av a2 s . c o m*/ final ODataMediaEntityCreateRequest<ClientEntity> createReq = client.getCUDRequestFactory() .getMediaEntityCreateRequest(uri, input); final MediaEntityCreateStreamManager<ClientEntity> streamManager = createReq.payloadManager(); final ODataMediaEntityCreateResponse<ClientEntity> createRes = streamManager.getResponse(); assertEquals(201, createRes.getStatusCode()); final Collection<String> location = createRes.getHeader(HttpHeader.LOCATION); assertNotNull(location); final URI createdLocation = URI.create(location.iterator().next()); final ClientEntity changes = client.getObjectFactory() .newEntity(new FullQualifiedName("ODataDemo.Advertisement")); changes.getProperties() .add(client.getObjectFactory().newPrimitiveProperty("AirDate", getClient().getObjectFactory().newPrimitiveValueBuilder() .setType(EdmPrimitiveTypeKind.DateTimeOffset).setValue(Calendar.getInstance()) .build())); final ODataEntityUpdateRequest<ClientEntity> updateReq = getClient().getCUDRequestFactory() .getEntityUpdateRequest(createdLocation, UpdateType.PATCH, changes); updateReq.setFormat(contentType); final ODataEntityUpdateResponse<ClientEntity> updateRes = updateReq.execute(); assertEquals(204, updateRes.getStatusCode()); final ODataMediaRequest retrieveReq = client.getRetrieveRequestFactory() .getMediaEntityRequest(client.newURIBuilder(createdLocation.toASCIIString()).build()); final ODataRetrieveResponse<InputStream> retrieveRes = retrieveReq.execute(); assertEquals(200, retrieveRes.getStatusCode()); final byte[] actual = new byte[Integer.parseInt(retrieveRes.getHeader("Content-Length").iterator().next())]; IOUtils.read(retrieveRes.getBody(), actual, 0, actual.length); assertEquals(random, new String(actual)); }
From source file:net.es.sense.rm.api.SenseRmController.java
/** * *********************************************************************** * POST /api/sense/v1/models/{id}/deltas * * *********************************************************************** @param accept * @param accept//w ww. j a v a 2s. co m * @param deltaRequest * @param model * @param id * @return */ @ApiOperation(value = "Submits a proposed model delta to the Resource Manager based on the model identified by id.", notes = "The Resource Manager must verify the proposed model change, confirming (201 Created), rejecting (500 Internal Server Error), or proposing an optional counter-offer (200 OK).", response = DeltaResource.class) @ApiResponses(value = { @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_DELTA_COUNTER_MSG, response = DeltaRequest.class, responseHeaders = { @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class), @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }), @ApiResponse(code = HttpConstants.CREATED_CODE, message = HttpConstants.CREATED_MSG, response = DeltaResource.class, responseHeaders = { @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class), @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }), @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = { @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = { @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = { @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = { @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), @ApiResponse(code = HttpConstants.CONFLICT_CODE, message = HttpConstants.CONFLICT_MSG, response = Error.class, responseHeaders = { @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = { @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), }) @RequestMapping(value = "/models/{" + HttpConstants.ID_NAME + "}/deltas", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<?> propagateModelDelta( @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept, @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model, @PathVariable(HttpConstants.ID_NAME) @ApiParam(value = HttpConstants.ID_MSG, required = true) String id, @RequestBody @ApiParam(value = "A JSON structure-containing the model reduction and/or addition " + " elements. If provided, the model reduction element is applied first, " + " followed by the model addition element.", required = true) DeltaRequest deltaRequest) { log.info("propagateModelDelta: {}", deltaRequest); DeltaResource delta = new DeltaResource(); delta.setId("922f4388-c8f6-4014-b6ce-5482289b0200"); delta.setHref("http://localhost:8080/sense/v1/deltas/922f4388-c8f6-4014-b6ce-5482289b0200"); delta.setLastModified("2016-07-26T13:45:21.001Z"); delta.setModelId("922f4388-c8f6-4014-b6ce-5482289b02ff"); delta.setResult( "H4sIACKIo1cAA+1Y32/aMBB+56+I6NtUx0loVZEV1K6bpkm0m5Y+7NWNTbCa2JEdCP3vZydULYUEh0CnQXlC+O6+O/ u7X1ylgozp3BJ4LH3rcpJlqQ9hnud23rO5iKDnOA50XKgEgAwnJEEnQ8vuXC30eB5XqXnQuYDqfEl+LnGVvAv/3I6CVQiFv FbF7ff7UKF4Hiice2IZmgMml5RZ8sq/0n9p82hcWFCHCtjtQacHH5AkS5qJkNWa6rDUdD2Y8ZTHPHoqtDudy6lgvpLzGclyL h59zBNE2YBIW/0y7FhvPqjw8X5h5LS40TuUEPyDYTqjeIpi6/OKltZ5IDFnkbzn1gqmxMxO0DyiEUp5qoGfj4YVxiZIfqGYCh JmlDMU/+IiW7W7FIvPOCYDOWUMhOLcT5XG4AJ60PVjyh4HKPbk8NTIBmIxSIRXmpgT4EAXOqWVT4YmwgkNX9w4V wZeu1EddEDEjIZkE4YyktNMgbCoyhhTj2Z1vwVK3PoZ3Fz/DqyvN3ddTYoq49o3bd6mLCNCffFsgqeHwZH1sS04gxmQua 3fbI1I8YIkm5xDr3xCInXmVPPAAEqztAaqtwQFtHQ7vBzJiQmeeoAW5KxwxJisP57VrOuRF2xB1ZZ37M9ixIBALCLrSG9ct 0dI8fy74NN02CQ5Yq2WPaVkE5KqaQ5UIRRRnWinq+51huIpkVbXA2dO/6ztjTZhUUXRWEnYHVUPcwY2zaOafHh553fKz dcErXCLyuuYIlnpEBYo4quVVvtzezO6K2Fd0AMG/arMWuoBLQTcWnqZ9tcNOahhX679/8muNX27IrrgWWBRbZvESFjIsV LdXYhHOYcVVAlylKb6LrtjFEvStnY2Gi4ONAn2Mxh9dJr3mYi2bDjmRWHHXaYe7N+wZk0b2FTH2rHC+EJ28NL7Se9aVp Ry9ZwwyNTDa8Uf627LdXcfM8CWk/4BTQBblaMDjb92ND2C+Gun+yNsz6ZbcdPuLBSQfLvwJ1QggDPmF6Uo5IyVt+rnCq es+AaNt7cbsh/jaxtn//6GsWYDgAEdvHddkj8Wv/3/+bCDnW+rf2DW7Xx/ASQO0KQcHgAA"); URI deltaURI; try { deltaURI = new URI("http://localhost:8080/sense/v1/deltas/922f4388-c8f6-4014-b6ce-5482289b0200"); } catch (URISyntaxException ex) { Error error = new Error(HttpStatus.INTERNAL_SERVER_ERROR.toString(), ex.getLocalizedMessage(), null); return new ResponseEntity<>(error, null, HttpStatus.INTERNAL_SERVER_ERROR); } final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri(); log.error("URL: " + location.toASCIIString()); //return Response.created(deltaURI).entity(getProxy().serialize(delta)).build(); final HttpHeaders headers = new HttpHeaders(); headers.setLocation(deltaURI); return new ResponseEntity<>(delta, headers, HttpStatus.CREATED); }
From source file:com.jp.miaulavirtual.DisplayMessageActivity.java
/** * Codifica la URL del archivo, lo descarga (si no existe) y lo guarda en Almacenamiento externo (SDCARD)//Android/data/com.jp.miaulavirtual/files * @return String - Tamao del archivo en formato del SI * @throws IOException/*from ww w.j a v a 2s . c o m*/ */ public int getDoc(Context mycontext, String url_back) throws IOException, SocketTimeoutException { URI uri; int id = 0; Log.d("Document", url); String request = null; // Codificamos la URL del archivo try { uri = new URI("http", "aulavirtual.uv.es", url, null); request = uri.toASCIIString(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("Document", request); // Recheck cookie isn't expire Response resp = Jsoup.connect("http://aulavirtual.uv.es" + url_back).cookies(cookies).method(Method.GET) .timeout(10 * 1000).execute(); res = resp; Log.d("Document", "Respuesta2"); Log.d("Cookie", res.cookies().toString()); // Action in response of cookie checking if (res.hasCookie("ad_user_login")) { // El usuario y la contrasea son correctas al renovar la COOKIE (NO PUEDEN SER INCORRECTOS, YA ESTABA LOGUEADO) Log.d("Cookie", String.valueOf(a)); if (a == 2) { a = 1; new docDownload(url_back).execute(); //REejecutamos la tarea docDownload } } else if (res.hasCookie("fs_block_id")) { id = downloadFile(request); } else if (res.hasCookie("ad_session_id")) { // Cookie Vencida SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mycontext); Editor editor = prefs.edit(); // Cookie Vencida editor.remove("cookies"); editor.commit(); cookies = null; // eliminamos la cookie a = a + 1; // Aumentamos el contador Log.d("Cookie", "COOKIE VENCIDA"); new docDownload(url_back).execute(); //REejecutamos la tarea (POST) } else if (res.hasCookie("tupi_style") || res.hasCookie("zen_style")) { // Cookie correcta, sesin POST ya habilitada. GET correcto. Procede. id = downloadFile(request); } Log.d("ID", String.valueOf(id)); return id; }
From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java
public void parseAnnotations(WorkflowBean annotatedBean, Annotations annotations) throws ReaderException { // logger.fine("Checking annotations for " + annotatedSubject); Map<String, NetSfTavernaT2AnnotationAnnotationAssertionImpl> annotationElems = new HashMap<>(); if (annotations == null || annotations.getAnnotationChainOrAnnotationChain22() == null) return;//from w w w .j a va 2s . c o m for (JAXBElement<AnnotationChain> el : annotations.getAnnotationChainOrAnnotationChain22()) { NetSfTavernaT2AnnotationAnnotationAssertionImpl ann = el.getValue() .getNetSfTavernaT2AnnotationAnnotationChainImpl().getAnnotationAssertions() .getNetSfTavernaT2AnnotationAnnotationAssertionImpl(); String annClass = ann.getAnnotationBean().getClazz(); if (annotationElems.containsKey(annClass) && annotationElems.get(annClass).getDate().compareToIgnoreCase(ann.getDate()) > 0) // ann.getDate() is less than current 'latest' annotation, skip continue; annotationElems.put(annClass, ann); } for (String clazz : annotationElems.keySet()) { NetSfTavernaT2AnnotationAnnotationAssertionImpl ann = annotationElems.get(clazz); Calendar cal = parseDate(ann.getDate()); String value = null; String semanticMediaType = TEXT_TURTLE; for (Object obj : ann.getAnnotationBean().getAny()) { if (!(obj instanceof Element)) continue; Element elem = (Element) obj; if (!(elem.getNamespaceURI() == null)) continue; if (elem.getLocalName().equals("text")) { value = elem.getTextContent().trim(); break; } if (clazz.equals(SEMANTIC_ANNOTATION)) { if (elem.getLocalName().equals("content")) value = elem.getTextContent().trim(); if (elem.getLocalName().equals("mimeType")) semanticMediaType = elem.getTextContent().trim(); } } if (value != null) { // Add the annotation Annotation annotation = new Annotation(); WorkflowBundle workflowBundle = parserState.get().getCurrentWorkflowBundle(); annotation.setParent(workflowBundle); String path = "annotation/" + annotation.getName() + ".ttl"; URI bodyURI = URI.create(path); annotation.setTarget(annotatedBean); annotation.setAnnotatedAt(cal); // annotation.setAnnotator(); annotation.setSerializedBy(t2flowParserURI); annotation.setSerializedAt(new GregorianCalendar()); URI annotatedSubject = uriTools.relativeUriForBean(annotatedBean, annotation); String body; if (clazz.equals(SEMANTIC_ANNOTATION)) { String baseStr = "@base <" + annotatedSubject.toASCIIString() + "> .\n"; body = baseStr + value; } else { // Generate Turtle from 'classic' annotation URI predicate = getPredicatesForClass().get(clazz); if (predicate == null) { if (isStrict()) throw new ReaderException("Unsupported annotation class " + clazz); return; } StringBuilder turtle = new StringBuilder(); turtle.append("<"); turtle.append(annotatedSubject.toASCIIString()); turtle.append("> "); turtle.append("<"); turtle.append(predicate.toASCIIString()); turtle.append("> "); // A potentially multi-line string turtle.append("\"\"\""); // Escape existing \ to \\ String escaped = value.replace("\\", "\\\\"); // Escape existing " to \" (beware Java's escaping of \ and " below) escaped = escaped.replace("\"", "\\\""); turtle.append(escaped); turtle.append("\"\"\""); turtle.append(" ."); body = turtle.toString(); } try { workflowBundle.getResources().addResource(body, path, semanticMediaType); } catch (IOException e) { throw new ReaderException("Could not store annotation body to " + path, e); } annotation.setBody(bodyURI); } } }
From source file:com.wangzhe.autojoin.wangfw.server.jetty9.JettyRunner.java
/** * Setup the basic application "context" for this application at "/" This is * also known as the handler tree (in jetty speak) *///from w w w .j a va2 s .c om private HandlerCollection getWebAppContext(URI baseUri, File scratchDir) { WebAppContext webappCtx = new WebAppContext(); webappCtx.setContextPath("/"); // webappCtx.setDescriptor(param.getWebDir()+"\\WEB-INF\\web.xml"); // webappCtx.setWar(param.getWebDir());//for war webappCtx.setDisplayName("auto join"); webappCtx.setTempDirectory(new File(param.getTempDir())); webappCtx.setWelcomeFiles(new String[] { param.getWebDir() + "\\index.html" });// ? webappCtx.setConfigurationDiscovered(true); webappCtx.setParentLoaderPriority(true); RequestLogHandler logHandler = new RequestLogHandler(); logHandler.setRequestLog(createRequestLog()); webappCtx.setAttribute("javax.servlet.context.tempdir", scratchDir); webappCtx.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/.*taglibs.*\\.jar$"); if (ObjectUtil.isNotEmpty(baseUri)) { webappCtx.setResourceBase(baseUri.toASCIIString());// for dir } else { webappCtx.setResourceBase(param.getWebDir()); } webappCtx.setAttribute("org.eclipse.jetty.containerInitializers", jspInitializers()); webappCtx.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager()); webappCtx.addBean(new ServletContainerInitializersStarter(webappCtx), true); webappCtx.setClassLoader(getUrlClassLoader()); webappCtx.addServlet(jspServletHolder(), "*.jsp"); // Add Application Servlets webappCtx.addServlet(DateServlet.class, "/date/"); webappCtx.addServlet(exampleJspFileMappedServletHolder(), "/test/foo/"); webappCtx.addServlet(defaultServletHolder(baseUri), "/"); setConfigurations(webappCtx); MetaData metaData = webappCtx.getMetaData(); Resource webappInitializer = Resource .newResource(WebAppStrarUpInitializer.class.getProtectionDomain().getCodeSource().getLocation()); metaData.addContainerResource(webappInitializer); HandlerCollection handlerCollection = new HandlerCollection(); GzipHandler gzipHandler = new GzipHandler(); handlerCollection.setHandlers(new Handler[] { webappCtx, logHandler, gzipHandler }); return handlerCollection; }
From source file:org.dasein.cloud.azure.AzureMethod.java
public @Nullable Document getAsXML(@Nonnull String account, @Nonnull URI uri) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + uri + ")"); }//from w ww .j a va 2 s.c o m if (wire.isDebugEnabled()) { wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); wire.debug(""); } try { HttpClient client = getClient(); HttpUriRequest get = new HttpGet(uri); //get.addHeader("Content-Type", "application/xml"); if (uri.toString().indexOf("/services/images") > -1) { get.addHeader("x-ms-version", "2012-08-01"); } else { get.addHeader("x-ms-version", "2012-03-01"); } if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { response = client.execute(get); status = response.getStatusLine(); } catch (IOException e) { logger.error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("get(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) { return null; } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error("get(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String body; if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { return null; } logger.error("get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } InputStream input; try { input = entity.getContent(); } catch (IOException e) { logger.error( "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } return parseResponse(input, true); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> " + uri.toASCIIString()); } } }