List of usage examples for java.security DigestOutputStream DigestOutputStream
public DigestOutputStream(OutputStream stream, MessageDigest digest)
From source file:de.blizzy.backup.backup.BackupRun.java
private String getChecksum(IFile file) throws IOException { final MessageDigest[] digest = new MessageDigest[1]; IOutputStreamProvider outputStreamProvider = new IOutputStreamProvider() { @Override/* w ww. j a v a2s . c o m*/ public OutputStream getOutputStream() { try { digest[0] = MessageDigest.getInstance("SHA-256"); //$NON-NLS-1$ return new DigestOutputStream(new NullOutputStream(), digest[0]); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } }; file.copy(outputStreamProvider); return toHexString(digest[0]); }
From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java
/** * Writes a .SF file with a digest to the manifest. */// w w w .ja va 2 s. c o m private void writeSignatureFile(OutputStream out) throws IOException, GeneralSecurityException { Manifest sf = new Manifest(); Attributes main = sf.getMainAttributes(); main.putValue("Signature-Version", "1.0"); main.putValue("Created-By", "1.0 (Android)"); MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM); PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, SdkConstants.UTF_8); // Digest of the entire manifest mManifest.write(print); print.flush(); main.putValue(DIGEST_MANIFEST_ATTR, new String(Base64.encode(md.digest()), "ASCII")); Map<String, Attributes> entries = mManifest.getEntries(); for (Map.Entry<String, Attributes> entry : entries.entrySet()) { // Digest of the manifest stanza for this entry. print.print("Name: " + entry.getKey() + "\r\n"); for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) { print.print(att.getKey() + ": " + att.getValue() + "\r\n"); } print.print("\r\n"); print.flush(); Attributes sfAttr = new Attributes(); sfAttr.putValue(DIGEST_ATTR, new String(Base64.encode(md.digest()), "ASCII")); sf.getEntries().put(entry.getKey(), sfAttr); } CountOutputStream cout = new CountOutputStream(out); sf.write(cout); // A bug in the java.util.jar implementation of Android platforms // up to version 1.6 will cause a spurious IOException to be thrown // if the length of the signature file is a multiple of 1024 bytes. // As a workaround, add an extra CRLF in this case. if ((cout.size() % 1024) == 0) { cout.write('\r'); cout.write('\n'); } }
From source file:com.jpeterson.littles3.StorageEngine.java
/** * Write//from w w w .ja va 2 s. com * * @param req * the HttpServletRequest object that contains the request the * client made of the servlet * @param resp * the HttpServletResponse object that contains the response the * servlet returns to the client * @throws IOException * if an input or output error occurs while the servlet is * handling the PUT request * @throws ServletException * if the request for the PUT cannot be handled */ @SuppressWarnings("unchecked") public void methodPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { OutputStream out = null; try { S3ObjectRequest or; try { or = S3ObjectRequest.create(req, resolvedHost(), (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR)); } catch (InvalidAccessKeyIdException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId"); return; } catch (InvalidSecurityException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } catch (RequestTimeTooSkewedException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed"); return; } catch (SignatureDoesNotMatchException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch"); return; } catch (AuthenticatorException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } logger.debug("S3ObjectRequest: " + or); CanonicalUser requestor = or.getRequestor(); if (or.getKey() != null) { String value; long contentLength; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); DigestOutputStream digestOutputStream = null; S3Object oldS3Object = null; S3Object s3Object; StorageService storageService; Bucket bucket; String bucketName = or.getBucket(); String key = or.getKey(); if (!isValidKey(key)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "KeyTooLong"); return; } storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); if (req.getParameter(PARAMETER_ACL) != null) { // write access control policy Acp acp; CanonicalUser owner; s3Object = storageService.load(bucketName, key); if (s3Object == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey"); return; } acp = s3Object.getAcp(); try { acp.canWrite(requestor); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } // save owner owner = acp.getOwner(); try { acp = Acp.decode(req.getInputStream()); } catch (IOException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError"); return; } // maintain owner acp.setOwner(owner); s3Object.setAcp(acp); storageService.store(s3Object); } else { // make sure requestor can "WRITE" to the bucket try { bucket = storageService.loadBucket(bucketName); bucket.canWrite(requestor); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } try { oldS3Object = storageService.load(bucket.getName(), key); } catch (DataRetrievalFailureException e) { // ignore } // create a new S3Object for this request to store an object try { s3Object = storageService.createS3Object(bucket, key, requestor); } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } out = s3Object.getOutputStream(); digestOutputStream = new DigestOutputStream(out, messageDigest); // Used instead of req.getContentLength(); because Amazon // limit is 5 gig, which is bigger than an int value = req.getHeader("Content-Length"); if (value == null) { resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED, "MissingContentLength"); return; } contentLength = Long.valueOf(value).longValue(); if (contentLength > 5368709120L) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "EntityTooLarge"); return; } long written = 0; int count; byte[] b = new byte[4096]; ServletInputStream in = req.getInputStream(); while (((count = in.read(b, 0, b.length)) > 0) && (written < contentLength)) { digestOutputStream.write(b, 0, count); written += count; } digestOutputStream.flush(); if (written != contentLength) { // transmission truncated if (out != null) { out.close(); out = null; } if (digestOutputStream != null) { digestOutputStream.close(); digestOutputStream = null; } // clean up storageService.remove(s3Object); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "IncompleteBody"); return; } s3Object.setContentDisposition(req.getHeader("Content-Disposition")); s3Object.setContentLength(contentLength); s3Object.setContentMD5(req.getHeader("Content-MD5")); value = req.getContentType(); logger.debug("Put - Content-Type: " + value); if (value == null) { value = S3Object.DEFAULT_CONTENT_TYPE; } s3Object.setContentType(value); logger.debug("Put - get content-type: " + s3Object.getContentType()); s3Object.setLastModified(System.currentTimeMillis()); // metadata int prefixLength = HEADER_PREFIX_USER_META.length(); String name; for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) { String headerName = (String) headerNames.nextElement(); if (headerName.startsWith(HEADER_PREFIX_USER_META)) { name = headerName.substring(prefixLength).toLowerCase(); for (Enumeration headers = req.getHeaders(headerName); headers.hasMoreElements();) { value = (String) headers.nextElement(); s3Object.addMetadata(name, value); } } } // calculate ETag, hex encoding of MD5 value = new String(Hex.encodeHex(digestOutputStream.getMessageDigest().digest())); resp.setHeader("ETag", value); s3Object.setETag(value); grantCannedAccessPolicies(req, s3Object.getAcp(), requestor); // NOTE: This could be reengineered to have a two-phase // commit. if (oldS3Object != null) { storageService.remove(oldS3Object); } storageService.store(s3Object); } } else if (or.getBucket() != null) { StorageService storageService; Bucket bucket; storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); if (req.getParameter(PARAMETER_ACL) != null) { // write access control policy Acp acp; CanonicalUser owner; logger.debug("User is providing new ACP for bucket " + or.getBucket()); try { bucket = storageService.loadBucket(or.getBucket()); } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } acp = bucket.getAcp(); try { acp.canWrite(requestor); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } // save owner owner = acp.getOwner(); try { acp = Acp.decode(req.getInputStream()); } catch (IOException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError"); return; } // maintain owner acp.setOwner(owner); bucket.setAcp(acp); logger.debug("Saving bucket ACP"); logger.debug("ACP: " + Acp.encode(bucket.getAcp())); storageService.storeBucket(bucket); } else { // validate bucket String bucketName = or.getBucket(); if (!isValidBucketName(bucketName)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidBucketName"); return; } try { bucket = storageService.createBucket(bucketName, requestor); } catch (BucketAlreadyExistsException e) { resp.sendError(HttpServletResponse.SC_CONFLICT, "BucketAlreadyExists"); return; } grantCannedAccessPolicies(req, bucket.getAcp(), requestor); storageService.storeBucket(bucket); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); logger.error("Unable to use MD5", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "InternalError"); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (out != null) { out.close(); out = null; } } }
From source file:com.stimulus.archiva.store.MessageStore.java
public byte[] writeEmail(Email message, File file, boolean compress, boolean encrypt) throws MessageStoreException { logger.debug("writeEmail"); OutputStream fos = null;/*from ww w . ja v a 2 s . c o m*/ try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); fos = getRawMessageOutputStream(file, compress, encrypt); DigestOutputStream dos = new DigestOutputStream(fos, sha); message.writeTo(dos); byte[] digest = sha.digest(); if (digest == null) { throw new MessageStoreException("failed to generate email digest. digest is null.", logger, ChainedException.Level.DEBUG); } return digest; } catch (Exception e) { if (file.exists()) { boolean deleted = file.delete(); if (!deleted) { try { //Mod Start Seolhwa.kim 2017-04-13 //file.renameTo(File.createTempFile("ma", "tmp")); File tmpfile = File.createTempFile("ma", "tmp"); Files.move(Paths.get(file.getAbsolutePath()), Paths.get(tmpfile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); //Mod End Seolhwa.kim 2017-04-13 Config.getFileSystem().getTempFiles().markForDeletion(file); } catch (Exception e3) { } } } throw new MessageStoreException("failed to write email {filename='" + file.getAbsolutePath() + "'", e, logger); } finally { try { if (fos != null) fos.close(); } catch (Exception e) { logger.error("failed to close email file:" + e.getMessage()); } } /* try { //System.out.println("WRITEMAIL:"+message.getContent()+"XXXXXXXXXXXXXXXXXXXXXX"); FileOutputStream fos2 = new FileOutputStream("c:\\test.eml"); message.writeTo(fos2); fos2.close(); } catch (Exception e) { e.printStackTrace(); logger.error(e); }*/ }
From source file:com.cloudbees.plugins.credentials.CredentialsProvider.java
/** * Retrieves the {@link Fingerprint} for a specific credential. * * @param c the credential.//from w w w. j av a 2 s . c om * @return the {@link Fingerprint} or {@code null} if the credential has no fingerprint associated with it. * @throws IOException if the credential's fingerprint hash could not be computed. * @since 2.1.1 */ @CheckForNull public static Fingerprint getFingerprintOf(@NonNull Credentials c) throws IOException { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); DigestOutputStream out = new DigestOutputStream(new NullOutputStream(), md5); try { FINGERPRINT_XML.toXML(c, new OutputStreamWriter(out, Charset.forName("UTF-8"))); } finally { IOUtils.closeQuietly(out); } return Jenkins.getActiveInstance().getFingerprintMap().get(Util.toHexString(md5.digest())); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("JLS mandates MD5 as a supported digest algorithm"); } }
From source file:com.cloudbees.plugins.credentials.CredentialsProvider.java
/** * Creates a fingerprint that can be used to track the usage of a specific credential. * * @param c the credential to fingerprint. * @return the Fingerprint.//from ww w.j a va 2 s. c o m * @throws IOException if the credential's fingerprint hash could not be computed. * @since 2.1.1 */ @NonNull public static Fingerprint getOrCreateFingerprintOf(@NonNull Credentials c) throws IOException { String pseudoFilename = String.format("Credential id=%s name=%s", c instanceof IdCredentials ? ((IdCredentials) c).getId() : "unknown", CredentialsNameProvider.name(c)); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); DigestOutputStream out = new DigestOutputStream(new NullOutputStream(), md5); try { FINGERPRINT_XML.toXML(c, new OutputStreamWriter(out, Charset.forName("UTF-8"))); } finally { IOUtils.closeQuietly(out); } return Jenkins.getActiveInstance().getFingerprintMap().getOrCreate(null, pseudoFilename, md5.digest()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("JLS mandates MD5 as a supported digest algorithm"); } }
From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java
@SuppressWarnings("serial") private <T, U> T invoke(Class<T> clazz, Map<String, String> parameters, U request) throws MarketplaceWebServiceException { String actionName = parameters.get("Action"); T response = null;//from w w w . j av a2s . co m String responseBodyString = null; ResponseHeaderMetadata responseHeaderMetadata = null; Method responseHeaderMetadataSetter = null; HttpPost method = null; try { responseHeaderMetadataSetter = clazz.getMethod("setResponseHeaderMetadata", ResponseHeaderMetadata.class); if (!config.isSetServiceURL()) { throw new MarketplaceWebServiceException( "Missing serviceUrl configuration value. You may obtain a list of valid MWS URLs by consulting the MWS Developer's Guide, or reviewing the sample code published along side this library.", -1, "InvalidServiceUrl", "Sender", null, null, null) { }; } // SubmitFeed will be the only MWS API function that will stream requests to the server. if (request instanceof SubmitFeedRequest) { // For SubmitFeed, HTTP body is reserved for the Feed Content and the function parameters // are contained within the HTTP header SubmitFeedRequest sfr = (SubmitFeedRequest) request; method = new HttpPost(config.getServiceURL() + "?" + getSubmitFeedUrlParameters(parameters)); method.setEntity(new InputStreamEntity(sfr.getFeedContent(), -1)); String contentMD5 = sfr.getContentMD5(); if (contentMD5 != null) { method.addHeader(new BasicHeader("Content-MD5", contentMD5)); } /* Set content type and encoding - encoding and charset are ignored right now because * octet-stream is the only supported transport of MWS feeds. */ method.addHeader(new BasicHeader("Content-Type", sfr.getContentType().toString())); } else { method = new HttpPost(config.getServiceURL()); log.debug("Adding required parameters..."); addRequiredParametersToRequest(method, parameters); /* Set content type and encoding */ log.debug("Setting content-type to application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase()); method.addHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase())); log.debug("Done adding additional required parameters. Parameters now: " + parameters); } for (Header head : defaultHeaders) { method.addHeader(head); } } catch (Throwable t) { throw new MarketplaceWebServiceException(t); } int status = -1; log.debug("Invoking" + actionName + " request. Current parameters: " + parameters); try { boolean shouldRetry = true; int retries = 0; do { log.debug("Sending Request to host: " + config.getServiceURL()); try { /* Submit request */ HttpResponse postResponse; postResponse = httpClient.execute(method, httpContext); status = postResponse.getStatusLine().getStatusCode(); responseHeaderMetadata = getResponseHeaderMetadata(postResponse); // GetFeedSubmissionResult and GetReport will be the only MWS API functions that will stream // server responses. boolean isStreamingResponse = (request instanceof GetFeedSubmissionResultRequest || request instanceof GetReportRequest); if (!isStreamingResponse) { // SubmitFeed responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent()); assert (responseBodyString != null); } /* Successful response. Attempting to unmarshal into the <Action>Response type */ if (status == HttpStatus.SC_OK && responseBodyString != null) { shouldRetry = false; log.debug("Received Response. Status: " + status + ". " + "Response Body: " + responseBodyString); log.debug("Attempting to unmarshal into the " + actionName + "Response type..."); response = clazz.cast(getUnmarshaller() .unmarshal(new StreamSource(new StringReader(responseBodyString)))); responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata); log.debug("Unmarshalled response into " + actionName + "Response type."); } else if (status == HttpStatus.SC_OK && isStreamingResponse) { Method outputStreamGetter = null; for (Method m : request.getClass().getMethods()) { if (m.getName().matches("get.+OutputStream$")) { outputStreamGetter = m; } } OutputStream originalOs = (OutputStream) outputStreamGetter.invoke(request, new Object[0]); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); DigestOutputStream os = new DigestOutputStream(originalOs, messageDigest); // Streaming-response-as-unnamed-body responses from MWS // must carry the generated unique request id as a HTTP // header (x-amz-request-id) as it cannot be passed in a // wrapper to the XML response. String requestIdFromHeader = null; { requestIdFromHeader = getFirstHeader(postResponse, "x-amz-request-id").getValue(); // Avoid use of the JDK-1.6-only isEmpty() call. if (requestIdFromHeader == null || requestIdFromHeader.length() == 0) { throw new MarketplaceWebServiceException( "no request id returned in the x-amz-request-id HTTP header " + "for a streaming response call - please contact Amazon"); } } String returnedContentMD5 = null; returnedContentMD5 = getFirstHeader(postResponse, "Content-MD5").getValue(); copyResponseToOutputStream(postResponse.getEntity().getContent(), os); // Streaming-response-as-unnamed-body responses from MWS // must also carry a Content-MD5 header and it must // match the calculated MD5 for the body. String calculatedContentMD5 = new String(Base64.encodeBase64(messageDigest.digest()), "UTF-8"); if (!calculatedContentMD5.equals(returnedContentMD5)) { throw new MarketplaceWebServiceException( "Content-MD5 HTTP header transmitted by MWS (" + returnedContentMD5 + ") " + "does not match the calculated MD5 (" + calculatedContentMD5 + ") " + "in request id " + requestIdFromHeader + " - please contact Amazon"); } response = clazz.newInstance(); responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata); if (clazz == GetFeedSubmissionResultResponse.class) { GetFeedSubmissionResultResponse r = (GetFeedSubmissionResultResponse) response; r.setGetFeedSubmissionResultResult( new GetFeedSubmissionResultResult(returnedContentMD5)); r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader)); } else if (clazz == GetReportResponse.class) { GetReportResponse r = (GetReportResponse) response; r.setGetReportResult(new GetReportResult(returnedContentMD5)); r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader)); } else { throw new MarketplaceWebServiceException("unexpected streaming-response class " + clazz.getName() + " - please contact Amazon"); } shouldRetry = false; log.debug("Received streaming response."); } else { /* Unsucessful response. Attempting to unmarshall into ErrorResponse type */ if (isStreamingResponse) { // Response body contains error message. responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent()); } log.debug("Received Response. Status: " + status + "."); if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR && !(request instanceof SubmitFeedRequest) && pauseIfRetryNeeded(++retries)) { shouldRetry = true; } else { log.debug("Attempting to unmarshal into the ErrorResponse type..."); ErrorResponse errorResponse = (ErrorResponse) getUnmarshaller() .unmarshal(new StreamSource(new StringReader(responseBodyString))); log.debug("Unmarshalled response into the ErrorResponse type."); API.amazon.mws.feeds.model.Error error = errorResponse.getError().get(0); if (status == HttpStatus.SC_SERVICE_UNAVAILABLE && !(error.getCode().equals("RequestThrottled")) && !(request instanceof SubmitFeedRequest) && pauseIfRetryNeeded(++retries)) { shouldRetry = true; } else { shouldRetry = false; throw new MarketplaceWebServiceException((((request instanceof SubmitFeedRequest) && (error.getType().equals("Receiver"))) ? error.getMessage() + " [Cannot retry SubmitFeed request: must reset InputStream to retry.]" : error.getMessage()), status, error.getCode(), error.getType(), errorResponse.getRequestId(), errorResponse.toXML(), responseHeaderMetadata); } } } } catch (JAXBException je) { /* Response cannot be unmarshalled neither as <Action>Response or ErrorResponse types. Checking for other possible errors. */ log.debug("Caught JAXBException", je); log.debug("Response cannot be unmarshalled neither as " + actionName + "Response or ErrorResponse types." + "Checking for other possible errors."); MarketplaceWebServiceException awse = processErrors(responseBodyString, status, responseHeaderMetadata); throw awse; } catch (IOException ioe) { log.error("Caught IOException exception", ioe); throw new MarketplaceWebServiceException("Internal Error", ioe); } catch (Exception e) { log.error("Caught Exception", e); throw new MarketplaceWebServiceException(e); } finally { method.releaseConnection(); } } while (shouldRetry); } catch (MarketplaceWebServiceException se) { log.error("Caught MarketplaceWebServiceException", se); throw se; } catch (Throwable t) { log.error("Caught Exception", t); throw new MarketplaceWebServiceException(t); } return response; }
From source file:com.amazonaws.mws.MarketplaceWebServiceClient.java
@SuppressWarnings("serial") private <T, U> T invoke(Class<T> clazz, Map<String, String> parameters, U request) throws MarketplaceWebServiceException { String actionName = parameters.get("Action"); T response = null;/*from w ww. java2s. c o m*/ String responseBodyString = null; ResponseHeaderMetadata responseHeaderMetadata = null; Method responseHeaderMetadataSetter = null; HttpPost method = null; try { responseHeaderMetadataSetter = clazz.getMethod("setResponseHeaderMetadata", ResponseHeaderMetadata.class); if (!config.isSetServiceURL()) { throw new MarketplaceWebServiceException( "Missing serviceUrl configuration value. You may obtain a list of valid MWS URLs by consulting the MWS Developer's Guide, or reviewing the sample code published along side this library.", -1, "InvalidServiceUrl", "Sender", null, null, null) { }; } // SubmitFeed will be the only MWS API function that will stream requests to the server. if (request instanceof SubmitFeedRequest) { // For SubmitFeed, HTTP body is reserved for the Feed Content and the function parameters // are contained within the HTTP header SubmitFeedRequest sfr = (SubmitFeedRequest) request; method = new HttpPost(config.getServiceURL() + "?" + getSubmitFeedUrlParameters(parameters)); method.setEntity(new InputStreamEntity(sfr.getFeedContent(), -1)); /* Set content type and encoding - encoding and charset are ignored right now because * octet-stream is the only supported transport of MWS feeds. */ method.addHeader(new BasicHeader("Content-Type", sfr.getContentType().toString())); } else { method = new HttpPost(config.getServiceURL()); log.debug("Adding required parameters..."); addRequiredParametersToRequest(method, parameters); /* Set content type and encoding */ log.debug("Setting content-type to application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase()); method.addHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase())); log.debug("Done adding additional required parameters. Parameters now: " + parameters); } for (Header head : defaultHeaders) { method.addHeader(head); } } catch (Throwable t) { throw new MarketplaceWebServiceException(t); } int status = -1; log.debug("Invoking" + actionName + " request. Current parameters: " + parameters); try { boolean shouldRetry = true; int retries = 0; do { log.debug("Sending Request to host: " + config.getServiceURL()); try { /* Submit request */ HttpResponse postResponse; postResponse = httpClient.execute(method, httpContext); status = postResponse.getStatusLine().getStatusCode(); responseHeaderMetadata = getResponseHeaderMetadata(postResponse); // GetFeedSubmissionResult and GetReport will be the only MWS API functions that will stream // server responses. boolean isStreamingResponse = (request instanceof GetFeedSubmissionResultRequest || request instanceof GetReportRequest); if (!isStreamingResponse) { // SubmitFeed responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent()); assert (responseBodyString != null); } /* Successful response. Attempting to unmarshal into the <Action>Response type */ if (status == HttpStatus.SC_OK && responseBodyString != null) { shouldRetry = false; log.debug("Received Response. Status: " + status + ". " + "Response Body: " + responseBodyString); log.debug("Attempting to unmarshal into the " + actionName + "Response type..."); response = clazz.cast(getUnmarshaller() .unmarshal(new StreamSource(new StringReader(responseBodyString)))); responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata); log.debug("Unmarshalled response into " + actionName + "Response type."); } else if (status == HttpStatus.SC_OK && isStreamingResponse) { Method outputStreamGetter = null; for (Method m : request.getClass().getMethods()) { if (m.getName().matches("get.+OutputStream$")) { outputStreamGetter = m; } } OutputStream originalOs = (OutputStream) outputStreamGetter.invoke(request, new Object[0]); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); DigestOutputStream os = new DigestOutputStream(originalOs, messageDigest); // Streaming-response-as-unnamed-body responses from MWS // must carry the generated unique request id as a HTTP // header (x-amz-request-id) as it cannot be passed in a // wrapper to the XML response. String requestIdFromHeader = null; { requestIdFromHeader = getFirstHeader(postResponse, "x-amz-request-id").getValue(); // Avoid use of the JDK-1.6-only isEmpty() call. if (requestIdFromHeader == null || requestIdFromHeader.length() == 0) { throw new MarketplaceWebServiceException( "no request id returned in the x-amz-request-id HTTP header " + "for a streaming response call - please contact Amazon"); } } String returnedContentMD5 = null; returnedContentMD5 = getFirstHeader(postResponse, "Content-MD5").getValue(); copyResponseToOutputStream(postResponse.getEntity().getContent(), os); // Streaming-response-as-unnamed-body responses from MWS // must also carry a Content-MD5 header and it must // match the calculated MD5 for the body. String calculatedContentMD5 = new String(Base64.encodeBase64(messageDigest.digest()), "UTF-8"); if (!calculatedContentMD5.equals(returnedContentMD5)) { throw new MarketplaceWebServiceException( "Content-MD5 HTTP header transmitted by MWS (" + returnedContentMD5 + ") " + "does not match the calculated MD5 (" + calculatedContentMD5 + ") " + "in request id " + requestIdFromHeader + " - please contact Amazon"); } response = clazz.newInstance(); responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata); if (clazz == GetFeedSubmissionResultResponse.class) { GetFeedSubmissionResultResponse r = (GetFeedSubmissionResultResponse) response; r.setGetFeedSubmissionResultResult( new GetFeedSubmissionResultResult(returnedContentMD5)); r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader)); } else if (clazz == GetReportResponse.class) { GetReportResponse r = (GetReportResponse) response; r.setGetReportResult(new GetReportResult(returnedContentMD5)); r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader)); } else { throw new MarketplaceWebServiceException("unexpected streaming-response class " + clazz.getName() + " - please contact Amazon"); } shouldRetry = false; log.debug("Received streaming response."); } else { /* Unsucessful response. Attempting to unmarshall into ErrorResponse type */ if (isStreamingResponse) { // Response body contains error message. responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent()); } log.debug("Received Response. Status: " + status + "."); if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR && !(request instanceof SubmitFeedRequest) && pauseIfRetryNeeded(++retries)) { shouldRetry = true; } else { log.debug("Attempting to unmarshal into the ErrorResponse type..."); ErrorResponse errorResponse = (ErrorResponse) getUnmarshaller() .unmarshal(new StreamSource(new StringReader(responseBodyString))); log.debug("Unmarshalled response into the ErrorResponse type."); com.amazonaws.mws.model.Error error = errorResponse.getError().get(0); if (status == HttpStatus.SC_SERVICE_UNAVAILABLE && !(error.getCode().equals("RequestThrottled")) && !(request instanceof SubmitFeedRequest) && pauseIfRetryNeeded(++retries)) { shouldRetry = true; } else { shouldRetry = false; throw new MarketplaceWebServiceException((((request instanceof SubmitFeedRequest) && (error.getType().equals("Receiver"))) ? error.getMessage() + " [Cannot retry SubmitFeed request: must reset InputStream to retry.]" : error.getMessage()), status, error.getCode(), error.getType(), errorResponse.getRequestId(), errorResponse.toXML(), responseHeaderMetadata); } } } } catch (JAXBException je) { /* Response cannot be unmarshalled neither as <Action>Response or ErrorResponse types. Checking for other possible errors. */ log.debug("Caught JAXBException", je); log.debug("Response cannot be unmarshalled neither as " + actionName + "Response or ErrorResponse types." + "Checking for other possible errors."); MarketplaceWebServiceException awse = processErrors(responseBodyString, status, responseHeaderMetadata); throw awse; } catch (IOException ioe) { log.error("Caught IOException exception", ioe); if (config.isSetProxyHost() && config.isSetProxyPort() && ioe instanceof javax.net.ssl.SSLPeerUnverifiedException) { String error = "\n*****\n* Perhaps you are attempting to use https protocol to communicate with the proxy that does not support it.\n* If so either enable https on the proxy, or configure the client to use http communications with the proxy.\n* See MarketplaceWebServiceClientConfig.setProxyProtocol for details.\n*****"; log.error(error); } throw new MarketplaceWebServiceException("Internal Error", ioe); } catch (Exception e) { log.error("Caught Exception", e); throw new MarketplaceWebServiceException(e); } finally { method.releaseConnection(); } } while (shouldRetry); } catch (MarketplaceWebServiceException se) { log.error("Caught MarketplaceWebServiceException", se); throw se; } catch (Throwable t) { log.error("Caught Exception", t); throw new MarketplaceWebServiceException(t); } return response; }
From source file:no.digipost.api.representations.Dokumentpakke.java
public byte[] getSHA256() throws IOException { MessageDigest digest = getDigest(); if (asicBytes != null) { return digest.digest(asicBytes); }/*from ww w.ja v a 2 s .com*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); DigestOutputStream digestStream = null; try { digestStream = new DigestOutputStream(baos, digest); IOUtils.copy(asicStream, digestStream); } finally { IOUtils.closeQuietly(digestStream); } asicBytes = baos.toByteArray(); return digest.digest(); }