List of usage examples for org.apache.http.entity ContentType TEXT_XML
ContentType TEXT_XML
To view the source code for org.apache.http.entity ContentType TEXT_XML.
Click Source Link
From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java
/** * @see org.opentravel.schemacompiler.repository.Repository#recalculateCrc(org.opentravel.schemacompiler.repository.RepositoryItem) */// w w w.j av a 2s . co m @Override public void recalculateCrc(RepositoryItem item) throws RepositoryException { try { validateRepositoryItem(item); // Build the HTTP request for the remote service RepositoryItemIdentityType itemIdentity = createItemIdentity(item); Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller(); HttpPost request = newPostRequest(RECALCULATE_CRC_ENDPOINT); StringWriter xmlWriter = new StringWriter(); marshaller.marshal(objectFactory.createRepositoryItemIdentity(itemIdentity), xmlWriter); request.setEntity(new StringEntity(xmlWriter.toString(), ContentType.TEXT_XML)); // Send the web service request and check the response log.info("Sending recalculate-crc request to HTTP endpoint: " + endpointUrl); HttpResponse response = executeWithAuthentication(request); if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) { throw new RepositoryException(getResponseErrorMessage(response)); } log.info("Recalculate-crc response received - Status OK"); // Update the local cache by deleting the local copy of the item downloadContent(item, true); } catch (JAXBException e) { throw new RepositoryException("The format of the library meta-data is unreadable.", e); } catch (IOException e) { throw new RepositoryException("The remote repository is unavailable.", e); } }
From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java
/** * @see org.opentravel.schemacompiler.repository.Repository#delete(org.opentravel.schemacompiler.repository.RepositoryItem) *//*www.j av a 2 s .co m*/ @Override public void delete(RepositoryItem item) throws RepositoryException { try { validateRepositoryItem(item); // Build the HTTP request for the remote service RepositoryItemIdentityType itemIdentity = createItemIdentity(item); Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller(); HttpPost request = newPostRequest(DELETE_ENDPOINT); StringWriter xmlWriter = new StringWriter(); marshaller.marshal(objectFactory.createRepositoryItemIdentity(itemIdentity), xmlWriter); request.setEntity(new StringEntity(xmlWriter.toString(), ContentType.TEXT_XML)); // Send the web service request and check the response log.info("Sending delete request to HTTP endpoint: " + endpointUrl); HttpResponse response = executeWithAuthentication(request); if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) { throw new RepositoryException(getResponseErrorMessage(response)); } log.info("Delete response received - Status OK"); // Update the local cache with the content that was just modified in the remote // repository File itemMetadata = manager.getFileManager().getLibraryMetadataLocation(item.getBaseNamespace(), item.getFilename(), item.getVersion()); File itemContent = manager.getFileManager().getLibraryContentLocation(item.getBaseNamespace(), item.getFilename(), item.getVersion()); itemMetadata.delete(); itemContent.delete(); } catch (JAXBException e) { throw new RepositoryException("The format of the library meta-data is unreadable.", e); } catch (IOException e) { throw new RepositoryException("The remote repository is unavailable.", e); } }
From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java
/** * Downloads the specified content (and its associated meta-data) from the remote repository * into the local instance. If the refresh policy for this repository does not require an update * (or the remote repository is not accessible), the locally cached copy of the content will be * used.//from w w w. j a v a 2s . c o m * * <p>This method will return true if the local copy was replaced by newer content from the remote * repository. False will be returned if the local copy was up-to-date, even if a refresh was * forced by the caller or the update policy. * * @param baseNamespace * the namespace of the repository item to download * @param filename * the filename of the repository item to download * @param versionIdentifier * the version identifier of the repository item to download * @param forceUpdate * disregards the repository's update policy and forces the remote content to be * downloaded * @return boolean * @throws RepositoryException * thrown if the remote repository cannot be accessed */ @SuppressWarnings("unchecked") public boolean downloadContent(String baseNamespace, String filename, String versionIdentifier, boolean forceUpdate) throws RepositoryException { String baseNS = RepositoryNamespaceUtils.normalizeUri(baseNamespace); LibraryInfoType contentMetadata = null; boolean refreshRequired, isStaleContent = false; Date localLastUpdated; try { contentMetadata = manager.getFileManager().loadLibraryMetadata(baseNS, filename, versionIdentifier); localLastUpdated = XMLGregorianCalendarConverter.toJavaDate(contentMetadata.getLastUpdated()); refreshRequired = forceUpdate || (contentMetadata.getStatus() == LibraryStatus.DRAFT) || // always update draft items (refreshPolicy == RefreshPolicy.ALWAYS); if (!refreshRequired && (refreshPolicy == RefreshPolicy.DAILY)) { refreshRequired = !dateOnlyFormat.format(localLastUpdated) .equals(dateOnlyFormat.format(new Date())); } } catch (RepositoryException e) { localLastUpdated = new Date(0L); // make sure the local date is earlier than anything we will get from the repository refreshRequired = true; } // If the item was previously downloaded, make sure it originated from this remote // repository if ((contentMetadata != null) && !contentMetadata.getOwningRepository().equals(id)) { throw new RepositoryException("The requested content is managed by a different remote repository."); } // If a refresh is required, download the item's metadata and content from the remote web // service if (refreshRequired) { File repositoryContentFile = manager.getFileManager().getLibraryContentLocation(baseNS, filename, versionIdentifier); boolean success = false; try { log.info("Downloading content from repository '" + id + "' - " + baseNS + "; " + filename + "; " + versionIdentifier); manager.getFileManager().startChangeSet(); // Marshal the JAXB content to a string and construct the HTTP requests HttpPost metadataRequest = newPostRequest(REPOSITORY_ITEM_METADATA_ENDPOINT); HttpPost contentRequest = newPostRequest(REPOSITORY_ITEM_CONTENT_ENDPOINT); RepositoryItemIdentityType itemIdentity = new RepositoryItemIdentityType(); Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller(); StringWriter xmlWriter = new StringWriter(); itemIdentity.setBaseNamespace(baseNS); itemIdentity.setFilename(filename); itemIdentity.setVersion(versionIdentifier); marshaller.marshal(objectFactory.createRepositoryItemIdentity(itemIdentity), xmlWriter); metadataRequest.setEntity(new StringEntity(xmlWriter.toString(), ContentType.TEXT_XML)); contentRequest.setEntity(new StringEntity(xmlWriter.toString(), ContentType.TEXT_XML)); // Send the requests for meta-data and content to the remote web service HttpResponse metadataResponse = executeWithAuthentication(metadataRequest); HttpResponse contentResponse = executeWithAuthentication(contentRequest); if (metadataResponse.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) { throw new RepositoryException(getResponseErrorMessage(metadataResponse)); } if (contentResponse.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) { throw new RepositoryException(getResponseErrorMessage(contentResponse)); } // Update the local cache with the content we just received from the remote web // service Unmarshaller unmarshaller = RepositoryFileManager.getSharedJaxbContext().createUnmarshaller(); JAXBElement<LibraryInfoType> jaxbElement = (JAXBElement<LibraryInfoType>) unmarshaller .unmarshal(metadataResponse.getEntity().getContent()); LibraryInfoType libraryMetadata = jaxbElement.getValue(); manager.getFileManager().createNamespaceIdFiles(jaxbElement.getValue().getBaseNamespace()); manager.getFileManager().saveLibraryMetadata(libraryMetadata); manager.getFileManager().saveFile(repositoryContentFile, contentResponse.getEntity().getContent()); success = true; // Compare the last-updated with our previous local value and return true if the // local content was modified. Date remoteLastUpdated = XMLGregorianCalendarConverter.toJavaDate(libraryMetadata.getLastUpdated()); isStaleContent = remoteLastUpdated.after(localLastUpdated); } catch (UnknownHostException e) { // If the remote repository is inaccessible, it is only an error if we are // downloading the // files for the first time. File repositoryMetadataFile = manager.getFileManager().getLibraryMetadataLocation(baseNS, filename, versionIdentifier); if (repositoryMetadataFile.exists() && repositoryContentFile.exists()) { log.warn("Remote repository is unavailable - using cached copy of file '" + filename + "'."); } else { throw new RepositoryUnavailableException("The remote repository is unavailable.", e); } } catch (JAXBException e) { throw new RepositoryException("The format of the library meta-data is unreadable.", e); } catch (IOException e) { throw new RepositoryException("The remote repository is unavailable.", e); } finally { // Commit or roll back the changes based on the result of the operation if (success) { manager.getFileManager().commitChangeSet(); } else { try { manager.getFileManager().rollbackChangeSet(); } catch (Throwable t) { log.error("Error rolling back the current change set.", t); } } } } return isStaleContent; }
From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java
/** * Returns true if the copy of the item in the remote repository has been updated * since the local copy was last downloaded. * //from www. j a v a 2 s. c om * @param item the repository item to check for staleness * @return boolean * @throws RepositoryException thrown if the remote web service is not available */ @SuppressWarnings("unchecked") private boolean isLocalContentStale(RepositoryItem item) throws RepositoryException { try { HttpPost metadataRequest = newPostRequest(REPOSITORY_ITEM_METADATA_ENDPOINT); RepositoryItemIdentityType itemIdentity = new RepositoryItemIdentityType(); Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller(); StringWriter xmlWriter = new StringWriter(); itemIdentity.setBaseNamespace(item.getBaseNamespace()); itemIdentity.setFilename(item.getFilename()); itemIdentity.setVersion(item.getVersion()); marshaller.marshal(objectFactory.createRepositoryItemIdentity(itemIdentity), xmlWriter); metadataRequest.setEntity(new StringEntity(xmlWriter.toString(), ContentType.TEXT_XML)); // Send the request for meta-data to the remote web service HttpResponse metadataResponse = executeWithAuthentication(metadataRequest); if (metadataResponse.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) { throw new RepositoryException(getResponseErrorMessage(metadataResponse)); } Unmarshaller unmarshaller = RepositoryFileManager.getSharedJaxbContext().createUnmarshaller(); JAXBElement<LibraryInfoType> jaxbElement = (JAXBElement<LibraryInfoType>) unmarshaller .unmarshal(metadataResponse.getEntity().getContent()); LibraryInfoType remoteMetadata = jaxbElement.getValue(); // Get the local meta-data for the item and compare the last-updated timestamps LibraryInfoType localMetadata = manager.getFileManager().loadLibraryMetadata(item.getBaseNamespace(), item.getFilename(), item.getVersion()); Date localLastUpdated = XMLGregorianCalendarConverter.toJavaDate(localMetadata.getLastUpdated()); Date remoteLastUpdated = XMLGregorianCalendarConverter.toJavaDate(remoteMetadata.getLastUpdated()); return localLastUpdated.before(remoteLastUpdated); } catch (IOException e) { throw new RepositoryUnavailableException("The remote repository is unavailable.", e); } catch (JAXBException e) { throw new RepositoryException("The format of the library meta-data is unreadable.", e); } }
From source file:org.apache.directory.fortress.core.rest.RestUtils.java
/** * Perform an HTTP Post REST operation.//ww w .j a va 2s .c om * * @param userId * @param password * @param szInput * @param function * @return String containing response * @throws RestException */ public String post(String userId, String password, String szInput, String function) throws RestException { LOG.debug("post uri=[{}], function=[{}], request=[{}]", uri, function, szInput); String szResponse = null; HttpPost post = new HttpPost(uri + function); post.addHeader("Accept", "text/xml"); setMethodHeaders(post); try { HttpEntity entity = new StringEntity(szInput, ContentType.TEXT_XML); post.setEntity(entity); org.apache.http.client.HttpClient httpclient = HttpClientBuilder.create() .setDefaultCredentialsProvider(getCredentialProvider(userId, password)).build(); HttpResponse response = httpclient.execute(post); String error; switch (response.getStatusLine().getStatusCode()) { case HTTP_OK: szResponse = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); LOG.debug("post uri=[{}], function=[{}], response=[{}]", uri, function, szResponse); break; case HTTP_401_UNAUTHORIZED: error = "post uri=[" + uri + "], function=[" + function + "], 401 function unauthorized on host"; LOG.error(error); throw new RestException(GlobalErrIds.REST_UNAUTHORIZED_ERR, error); case HTTP_403_FORBIDDEN: error = "post uri=[" + uri + "], function=[" + function + "], 403 function forbidden on host"; LOG.error(error); throw new RestException(GlobalErrIds.REST_FORBIDDEN_ERR, error); case HTTP_404_NOT_FOUND: error = "post uri=[" + uri + "], function=[" + function + "], 404 not found from host"; LOG.error(error); throw new RestException(GlobalErrIds.REST_NOT_FOUND_ERR, error); default: error = "post uri=[" + uri + "], function=[" + function + "], error received from host: " + response.getStatusLine().getStatusCode(); LOG.error(error); throw new RestException(GlobalErrIds.REST_UNKNOWN_ERR, error); } } catch (IOException ioe) { String error = "post uri=[" + uri + "], function=[" + function + "] caught IOException=" + ioe; LOG.error(error); throw new RestException(GlobalErrIds.REST_IO_ERR, error, ioe); } catch (WebApplicationException we) { String error = "post uri=[" + uri + "], function=[" + function + "] caught WebApplicationException=" + we; LOG.error(error); throw new RestException(GlobalErrIds.REST_WEB_ERR, error, we); } catch (java.lang.NoSuchMethodError e) { String error = "post uri=[" + uri + "], function=[" + function + "] caught Exception=" + e; LOG.error(error); e.printStackTrace(); throw new RestException(GlobalErrIds.REST_UNKNOWN_ERR, error); } finally { // Release current connection to the connection pool. post.releaseConnection(); } return szResponse; }
From source file:org.flowable.cmmn.rest.service.api.CmmnRestResponseFactory.java
public List<DeploymentResourceResponse> createDeploymentResourceResponseList(String deploymentId, List<String> resourceList, ContentTypeResolver contentTypeResolver) { RestUrlBuilder urlBuilder = createUrlBuilder(); // Add additional metadata to the artifact-strings before returning List<DeploymentResourceResponse> responseList = new ArrayList<>(); for (String resourceId : resourceList) { String contentType = null; if (resourceId.toLowerCase().endsWith(".cmmn")) { contentType = ContentType.TEXT_XML.getMimeType(); } else {/*w w w.ja v a2 s . co m*/ contentType = contentTypeResolver.resolveContentType(resourceId); } responseList.add(createDeploymentResourceResponse(deploymentId, resourceId, contentType, urlBuilder)); } return responseList; }
From source file:org.flowable.cmmn.rest.service.api.repository.BaseDeploymentResourceDataResource.java
protected byte[] getDeploymentResourceData(String deploymentId, String resourceName, HttpServletResponse response) {/*from w ww. j ava2 s. c o m*/ if (deploymentId == null) { throw new FlowableIllegalArgumentException("No deployment id provided"); } if (resourceName == null) { throw new FlowableIllegalArgumentException("No resource name provided"); } // Check if deployment exists CmmnDeployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId) .singleResult(); if (deployment == null) { throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", CmmnDeployment.class); } if (restApiInterceptor != null) { restApiInterceptor.accessDeploymentById(deployment); } List<String> resourceList = repositoryService.getDeploymentResourceNames(deploymentId); if (resourceList.contains(resourceName)) { final InputStream resourceStream = repositoryService.getResourceAsStream(deploymentId, resourceName); String contentType = null; if (resourceName.toLowerCase().endsWith(".cmmn")) { contentType = ContentType.TEXT_XML.getMimeType(); } else { contentType = contentTypeResolver.resolveContentType(resourceName); } response.setContentType(contentType); try { return IOUtils.toByteArray(resourceStream); } catch (Exception e) { throw new FlowableException("Error converting resource stream", e); } } else { // Resource not found in deployment throw new FlowableObjectNotFoundException("Could not find a resource with name '" + resourceName + "' in deployment '" + deploymentId + "'.", String.class); } }
From source file:org.kohsuke.stapler.RequestImplTest.java
private byte[] generateMultipartData() throws IOException { MultipartEntityBuilder reqEntityBuilder = MultipartEntityBuilder.create(); reqEntityBuilder.setBoundary("mpboundary"); reqEntityBuilder.addBinaryBody("pomFile", new File("./pom.xml"), ContentType.TEXT_XML, "pom.xml"); reqEntityBuilder.addTextBody("text1", "text1_val"); reqEntityBuilder.addTextBody("text2", "text2_val"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {// w w w . ja va 2 s .c om reqEntityBuilder.build().writeTo(outputStream); outputStream.flush(); return outputStream.toByteArray(); } finally { outputStream.close(); } }
From source file:org.opendatakit.briefcase.util.AggregateUtils.java
public static final boolean uploadFilesToServer(ServerConnectionInfo serverInfo, URI u, String distinguishedFileTagName, File file, List<File> files, DocumentDescription description, SubmissionResponseAction action, TerminationFuture terminationFuture, FormStatus formToTransfer) { boolean allSuccessful = true; formToTransfer.setStatusString("Preparing for upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true); EventBus.publish(new FormStatusEvent(formToTransfer)); boolean first = true; // handles case where there are no media files int lastJ = 0; int j = 0;//from w w w . ja v a 2s.c om while (j < files.size() || first) { lastJ = j; first = false; if (terminationFuture.isCancelled()) { formToTransfer.setStatusString("Aborting upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true); EventBus.publish(new FormStatusEvent(formToTransfer)); return false; } HttpPost httppost = WebUtils.createOpenRosaHttpPost(u); long byteCount = 0L; // mime post MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // add the submission file first... FileBody fb = new FileBody(file, ContentType.TEXT_XML); builder.addPart(distinguishedFileTagName, fb); log.info("added " + distinguishedFileTagName + ": " + file.getName()); byteCount += file.length(); for (; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } // we will be processing every one of these, so // we only need to deal with the content type determination... if (extension.equals("xml")) { fb = new FileBody(f, ContentType.TEXT_XML); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, ContentType.create("image/jpeg")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, ContentType.create("audio/3gpp")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, ContentType.create("video/3gpp")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, ContentType.create("video/mp4")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, ContentType.create("text/csv")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added csv file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, ContentType.create("application/vnd.ms-excel")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added xls file " + f.getName()); } else { fb = new FileBody(f, ContentType.create("application/octet-stream")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.warn("added unrecognized file (application/octet-stream) " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if ((j - lastJ + 1) > 100 || byteCount + files.get(j + 1).length() > 10000000L) { // more than 100 attachments or the next file would exceed the 10MB threshold... log.info("Extremely long post is being split into multiple posts"); try { StringBody sb = new StringBody("yes", ContentType.DEFAULT_TEXT.withCharset(Charset.forName("UTF-8"))); builder.addPart("*isIncomplete*", sb); } catch (Exception e) { log.error("impossible condition", e); throw new IllegalStateException("never happens"); } ++j; // advance over the last attachment added... break; } } } httppost.setEntity(builder.build()); int[] validStatusList = { 201 }; try { if (j != files.size()) { formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and media files " + (lastJ + 1) + " through " + (j + 1) + " of " + files.size() + " media attachments", true); } else if (j == 0) { formToTransfer.setStatusString( "Uploading " + description.getDocumentDescriptionType() + " with no media attachments", true); } else { formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and " + (j - lastJ) + ((lastJ != 0) ? " remaining" : "") + " media attachments", true); } EventBus.publish(new FormStatusEvent(formToTransfer)); httpRetrieveXmlDocument(httppost, validStatusList, serverInfo, false, description, action); } catch (XmlDocumentFetchException e) { allSuccessful = false; log.error("upload failed", e); formToTransfer.setStatusString("UPLOAD FAILED: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(formToTransfer)); if (description.isCancelled()) return false; } } return allSuccessful; }