List of usage examples for javax.servlet.http HttpServletResponse SC_SEE_OTHER
int SC_SEE_OTHER
To view the source code for javax.servlet.http HttpServletResponse SC_SEE_OTHER.
Click Source Link
From source file:com.cognitivemedicine.nifi.http.PostAdvancedHTTP.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean(); final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger(); final String userAgent = context.getProperty(USER_AGENT).getValue(); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setConnectionRequestTimeout( context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setConnectTimeout( context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setRedirectsEnabled(false); requestConfigBuilder//from w w w .jav a 2 s .co m .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); final RequestConfig requestConfig = requestConfigBuilder.build(); final StreamThrottler throttler = throttlerRef.get(); final ProcessorLog logger = getLogger(); final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B); String lastUrl = null; long bytesToSend = 0L; final List<FlowFile> toSend = new ArrayList<>(); DestinationAccepts destinationAccepts = null; CloseableHttpClient client = null; final String transactionId = UUID.randomUUID().toString(); final ObjectHolder<String> dnHolder = new ObjectHolder<>("none"); while (true) { FlowFile flowFile = session.get(); if (flowFile == null) { break; } final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue(); try { new java.net.URL(url); } catch (final MalformedURLException e) { logger.error( "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure", new Object[] { flowFile, url }); flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); continue; } // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles if (lastUrl != null && !lastUrl.equals(url)) { session.transfer(flowFile); break; } lastUrl = url; toSend.add(flowFile); if (client == null || destinationAccepts == null) { final Config config = getConfig(url, context); final HttpClientConnectionManager conMan = config.getConnectionManager(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setConnectionManager(conMan); clientBuilder.setUserAgent(userAgent); clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException { HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext); ManagedHttpClientConnection conn = coreContext .getConnection(ManagedHttpClientConnection.class); if (!conn.isOpen()) { return; } SSLSession sslSession = conn.getSSLSession(); if (sslSession != null) { final X509Certificate[] certChain = sslSession.getPeerCertificateChain(); if (certChain == null || certChain.length == 0) { throw new SSLPeerUnverifiedException("No certificates found"); } final X509Certificate cert = certChain[0]; dnHolder.set(cert.getSubjectDN().getName().trim()); } } }); clientBuilder.disableAutomaticRetries(); clientBuilder.disableContentCompression(); final String username = context.getProperty(USERNAME).getValue(); final String password = context.getProperty(PASSWORD).getValue(); // set the credentials if appropriate if (username != null) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (password == null) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username)); } else { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); } ; clientBuilder.setDefaultCredentialsProvider(credentialsProvider); } client = clientBuilder.build(); // determine whether or not destination accepts flowfile/gzip destinationAccepts = config.getDestinationAccepts(); if (destinationAccepts == null) { try { if (sendAsFlowFile) { destinationAccepts = getDestinationAcceptance(client, url, getLogger(), transactionId); } else { destinationAccepts = new DestinationAccepts(false, false, false, false, null); } config.setDestinationAccepts(destinationAccepts); } catch (IOException e) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); logger.error( "Unable to communicate with destination {} to determine whether or not it can accept flowfiles/gzip; routing {} to failure due to {}", new Object[] { url, flowFile, e }); context.yield(); return; } } } // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format, // then only use a single FlowFile if (!sendAsFlowFile || (!destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted())) { break; } bytesToSend += flowFile.getSize(); if (bytesToSend > maxBatchBytes.longValue()) { break; } } if (toSend.isEmpty()) { return; } final String url = lastUrl; final HttpPost post = new HttpPost(url); final List<FlowFile> flowFileList = toSend; final DestinationAccepts accepts = destinationAccepts; final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null; final EntityTemplate entity = new EntityTemplate(new ContentProducer() { @Override public void writeTo(final OutputStream rawOut) throws IOException { final OutputStream throttled = (throttler == null) ? rawOut : throttler.newThrottledOutputStream(rawOut); OutputStream wrappedOut = new BufferedOutputStream(throttled); if (compressionLevel > 0 && accepts.isGzipAccepted()) { wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel); } try (final OutputStream out = wrappedOut) { for (final FlowFile flowFile : flowFileList) { session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream rawIn) throws IOException { try (final InputStream in = new BufferedInputStream(rawIn)) { FlowFilePackager packager = null; if (!sendAsFlowFile) { packager = null; } else if (accepts.isFlowFileV3Accepted()) { packager = new FlowFilePackagerV3(); } else if (accepts.isFlowFileV2Accepted()) { packager = new FlowFilePackagerV2(); } else if (accepts.isFlowFileV1Accepted()) { packager = new FlowFilePackagerV1(); } // if none of the above conditions is met, we should never get here, because // we will have already verified that at least 1 of the FlowFile packaging // formats is acceptable if sending as FlowFile. if (packager == null) { StreamUtils.copy(in, out); } else { final Map<String, String> flowFileAttributes; if (isDestinationLegacyNiFi) { // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path; // in order to maintain backward compatibility, we copy the filename & path to those attribute keys. flowFileAttributes = new HashMap<>(flowFile.getAttributes()); flowFileAttributes.put("nf.file.name", flowFile.getAttribute(CoreAttributes.FILENAME.key())); flowFileAttributes.put("nf.file.path", flowFile.getAttribute(CoreAttributes.PATH.key())); } else { flowFileAttributes = flowFile.getAttributes(); } packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize()); } } } }); } out.flush(); } } }); entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean()); post.setEntity(entity); post.setConfig(requestConfig); final String contentType; if (sendAsFlowFile) { if (accepts.isFlowFileV3Accepted()) { contentType = APPLICATION_FLOW_FILE_V3; } else if (accepts.isFlowFileV2Accepted()) { contentType = APPLICATION_FLOW_FILE_V2; } else if (accepts.isFlowFileV1Accepted()) { contentType = APPLICATION_FLOW_FILE_V1; } else { logger.error( "Cannot send data to {} because the destination does not accept FlowFiles and this processor is configured to deliver FlowFiles; rolling back session", new Object[] { url }); session.rollback(); context.yield(); return; } } else { final String attributeValue = toSend.get(0).getAttribute(CoreAttributes.MIME_TYPE.key()); contentType = (attributeValue == null) ? DEFAULT_CONTENT_TYPE : attributeValue; } final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue(); if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) { final Pattern pattern = Pattern.compile(attributeHeaderRegex); final Map<String, String> attributes = flowFileList.get(0).getAttributes(); for (final Map.Entry<String, String> entry : attributes.entrySet()) { final String key = entry.getKey(); if (pattern.matcher(key).matches()) { post.setHeader(entry.getKey(), entry.getValue()); } } } post.setHeader(CONTENT_TYPE, contentType); post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true"); post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION); post.setHeader(TRANSACTION_ID_HEADER, transactionId); if (compressionLevel > 0 && accepts.isGzipAccepted()) { post.setHeader(GZIPPED_HEADER, "true"); } // Do the actual POST final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles"; final String uploadDataRate; final long uploadMillis; String responseContent; CloseableHttpResponse response = null; try { final StopWatch stopWatch = new StopWatch(true); response = client.execute(post); responseContent = EntityUtils.toString(response.getEntity()); stopWatch.stop(); uploadDataRate = stopWatch.calculateDataRate(bytesToSend); uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS); } catch (final IOException e) { logger.error("Failed to Post {} due to {}; transferring to failure", new Object[] { flowFileDescription, e }); context.yield(); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } finally { if (response != null) { try { response.close(); } catch (IOException e) { getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e }); } } } // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us // from posting to some other webservice and then attempting to delete some resource to which // we are redirected final int responseCode = response.getStatusLine().getStatusCode(); final String responseReason = response.getStatusLine().getReasonPhrase(); String holdUri = null; if (responseCode == HttpServletResponse.SC_SEE_OTHER) { final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME); if (locationUriHeader != null) { if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) { final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME); if (holdUriHeader != null) { holdUri = holdUriHeader.getValue(); } } } if (holdUri == null) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } } if (holdUri == null) { if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: response code was {}:{}; will yield processing, since the destination is temporarily unavailable", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } context.yield(); return; } if (responseCode >= 300) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error("Failed to Post {} to {}: response code was {}:{}", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription, url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate }); for (FlowFile flowFile : toSend) { flowFile = this.setHttpPostResponse(context, session, responseContent, flowFile); session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis, true); session.transfer(flowFile, REL_SUCCESS); } return; } // // the response indicated a Hold URI; delete the Hold. // // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have // changed over the past, so we have to take into account a few different possibilities. String fullHoldUri = holdUri; if (holdUri.startsWith("/contentListener")) { // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener, // as this really indicates that it should be whatever we posted to -- if posting directly to the // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may // be posting to some other URL. fullHoldUri = url + holdUri.substring(16); } else if (holdUri.startsWith("/")) { // URL indicates the full path but not hostname or port; use the same hostname & port that we posted // to but use the full path indicated by the response. int firstSlash = url.indexOf("/", 8); if (firstSlash < 0) { firstSlash = url.length(); } final String beforeSlash = url.substring(0, firstSlash); fullHoldUri = beforeSlash + holdUri; } else if (!holdUri.startsWith("http")) { // Absolute URL fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri; } final HttpDelete delete = new HttpDelete(fullHoldUri); delete.setHeader(TRANSACTION_ID_HEADER, transactionId); while (true) { try { final HttpResponse holdResponse = client.execute(delete); responseContent = EntityUtils.toString(holdResponse.getEntity()); final int holdStatusCode = holdResponse.getStatusLine().getStatusCode(); final String holdReason = holdResponse.getStatusLine().getReasonPhrase(); if (holdStatusCode >= 300) { logger.error( "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure", new Object[] { flowFileDescription, holdStatusCode, holdReason }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}", new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate }); for (FlowFile flowFile : toSend) { flowFile = this.setHttpPostResponse(context, session, responseContent, flowFile); session.getProvenanceReporter().send(flowFile, url); session.transfer(flowFile, REL_SUCCESS); } return; } catch (final IOException e) { logger.warn("Failed to delete Hold that destination placed on {} due to {}", new Object[] { flowFileDescription, e }); } if (!isScheduled()) { context.yield(); logger.warn( "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure", new Object[] { flowFileDescription }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } } }
From source file:de.escidoc.core.test.EscidocAbstractTest.java
/** * Test logging in an user.//from ww w .j a v a2s . c om * * @param loginName * The login name of the user. * @param password * The password of the user. * @param encodeTargetUrlSlashes * Flag indicating that the slashes contained in the targetUrl shall be encoded (<code>true</code>) or * shall not be encoded ( <code>false</code>). * @return The eSciDoc user handle. * @throws Exception * If anything fails. */ protected String login(final String loginName, final String password, final boolean encodeTargetUrlSlashes) throws Exception { UserManagementWrapperClient userManagementWrapperClient = new UserManagementWrapperClient(); HttpResponse result = userManagementWrapperClient.login(loginName, password, false, false, "http://www.fiz-karlsruhe.de", encodeTargetUrlSlashes); assertHttpStatus("", HttpServletResponse.SC_SEE_OTHER, result); assertNotNull(result.getFirstHeader("Location")); assertNotNull(result.getFirstHeader("Set-Cookie")); String userHandleFromRedirectUrl = null; String userHandleFromCookie = null; Header[] headers = result.getAllHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String locationHeaderValue = result.getFirstHeader("Location").getValue(); int index = locationHeaderValue.indexOf('='); userHandleFromRedirectUrl = new String(Base64 .decodeBase64(locationHeaderValue.substring(index + 1, locationHeaderValue.length()))); } else if ("Set-Cookie".equals(headers[i].getName())) { String setCookieHeaderValue = result.getFirstHeader("Set-Cookie").getValue(); int index = setCookieHeaderValue.indexOf("escidocCookie="); String value = setCookieHeaderValue.substring(index + "escidocCookie=".length()); index = value.indexOf(';'); userHandleFromCookie = value.substring(0, index); } } assertNotNull("No handle from redirect URL", userHandleFromRedirectUrl); assertNotNull("No handle from cookie", userHandleFromCookie); assertEquals("Handle mismatch in cookie and URL", userHandleFromCookie, userHandleFromRedirectUrl); return userHandleFromCookie; }
From source file:de.escidoc.core.test.EscidocRestSoapTestBase.java
/** * Test logging in an user.// w w w. j a v a 2s. c o m * * @param loginName The login name of the user. * @param password The password of the user. * @param encodeTargetUrlSlashes Flag indicating that the slashes contained in the targetUrl shall be encoded * (<code>true</code>) or shall not be encoded ( <code>false</code>). * @return The eSciDoc user handle. * @throws Exception If anything fails. */ protected String login(final String loginName, final String password, final boolean encodeTargetUrlSlashes) throws Exception { UserManagementWrapperClient userManagementWrapperClient = new UserManagementWrapperClient(getTransport()); HttpResponse result = userManagementWrapperClient.login(loginName, password, false, false, "http://www.fiz-karlsruhe.de", encodeTargetUrlSlashes); assertHttpStatus("", HttpServletResponse.SC_SEE_OTHER, result); assertNotNull(result.getFirstHeader("Location")); assertNotNull(result.getFirstHeader("Set-Cookie")); String userHandleFromRedirectUrl = null; String userHandleFromCookie = null; Header[] headers = result.getAllHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String locationHeaderValue = result.getFirstHeader("Location").getValue(); int index = locationHeaderValue.indexOf('='); userHandleFromRedirectUrl = new String( Base64.decode(locationHeaderValue.substring(index + 1, locationHeaderValue.length()))); } else if ("Set-Cookie".equals(headers[i].getName())) { String setCookieHeaderValue = result.getFirstHeader("Set-Cookie").getValue(); int index = setCookieHeaderValue.indexOf("escidocCookie="); String value = setCookieHeaderValue.substring(index + "escidocCookie=".length()); index = value.indexOf(';'); userHandleFromCookie = value.substring(0, index); } } assertNotNull("No handle from redirect URL", userHandleFromRedirectUrl); assertNotNull("No handle from cookie", userHandleFromCookie); assertEquals("Handle mismatch in cookie and URL", userHandleFromCookie, userHandleFromRedirectUrl); return userHandleFromCookie; }
From source file:de.escidoc.core.test.aa.AaTestBase.java
/** * Test logging out an user./*from www . ja va 2 s .com*/ * * @param redirectUrl * The target to that the user shall be redirected after being logged out. This may be <code>null</code> * (no redirect). * @param userHandle * The eSciDOc user handle that shall be sent in the cookie of the logout request. * @param encodeRedirectUrlSlashes * Flag indicating that the slashes contained in the redirectUrl shall be encoded (<code>true</code>) or * shall not be encoded (<code>false</code>). * @return The response of the logout. * @throws Exception * If anything fails. */ protected String logout(final String redirectUrl, final String userHandle, final boolean encodeRedirectUrlSlashes) throws Exception { final Object result = getUserManagementWrapperClient().logout(redirectUrl, userHandle, encodeRedirectUrlSlashes); String xmlResult = null; if (result instanceof HttpResponse) { final HttpResponse httpRes = (HttpResponse) result; xmlResult = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8); assertHttpStatus("", HttpServletResponse.SC_SEE_OTHER, httpRes); assertRedirect(httpRes, redirectUrl); assertLogoutCookies(httpRes); } else { fail("Unexpected result, expected result of type HttpResponse."); } return xmlResult; }
From source file:org.apache.nifi.processors.standard.PostHTTP.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean(); final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger(); final String userAgent = context.getProperty(USER_AGENT).getValue(); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setConnectionRequestTimeout( context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setConnectTimeout( context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); requestConfigBuilder.setRedirectsEnabled(false); requestConfigBuilder// w w w . j a va 2s. com .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); final RequestConfig requestConfig = requestConfigBuilder.build(); final StreamThrottler throttler = throttlerRef.get(); final ComponentLog logger = getLogger(); final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B); String lastUrl = null; long bytesToSend = 0L; final List<FlowFile> toSend = new ArrayList<>(); DestinationAccepts destinationAccepts = null; CloseableHttpClient client = null; final String transactionId = UUID.randomUUID().toString(); final AtomicReference<String> dnHolder = new AtomicReference<>("none"); while (true) { FlowFile flowFile = session.get(); if (flowFile == null) { break; } final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue(); try { new java.net.URL(url); } catch (final MalformedURLException e) { logger.error( "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure", new Object[] { flowFile, url }); flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); continue; } // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles if (lastUrl != null && !lastUrl.equals(url)) { session.transfer(flowFile); break; } lastUrl = url; toSend.add(flowFile); if (client == null || destinationAccepts == null) { final Config config = getConfig(url, context); final HttpClientConnectionManager conMan = config.getConnectionManager(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setConnectionManager(conMan); clientBuilder.setUserAgent(userAgent); clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException { final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext); final ManagedHttpClientConnection conn = coreContext .getConnection(ManagedHttpClientConnection.class); if (!conn.isOpen()) { return; } final SSLSession sslSession = conn.getSSLSession(); if (sslSession != null) { final Certificate[] certChain = sslSession.getPeerCertificates(); if (certChain == null || certChain.length == 0) { throw new SSLPeerUnverifiedException("No certificates found"); } try { final X509Certificate cert = CertificateUtils .convertAbstractX509Certificate(certChain[0]); dnHolder.set(cert.getSubjectDN().getName().trim()); } catch (CertificateException e) { final String msg = "Could not extract subject DN from SSL session peer certificate"; logger.warn(msg); throw new SSLPeerUnverifiedException(msg); } } } }); clientBuilder.disableAutomaticRetries(); clientBuilder.disableContentCompression(); final String username = context.getProperty(USERNAME).getValue(); final String password = context.getProperty(PASSWORD).getValue(); // set the credentials if appropriate if (username != null) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (password == null) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username)); } else { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); } clientBuilder.setDefaultCredentialsProvider(credentialsProvider); } // Set the proxy if specified if (context.getProperty(PROXY_HOST).isSet() && context.getProperty(PROXY_PORT).isSet()) { final String host = context.getProperty(PROXY_HOST).getValue(); final int port = context.getProperty(PROXY_PORT).asInteger(); clientBuilder.setProxy(new HttpHost(host, port)); } client = clientBuilder.build(); // determine whether or not destination accepts flowfile/gzip destinationAccepts = config.getDestinationAccepts(); if (destinationAccepts == null) { try { destinationAccepts = getDestinationAcceptance(sendAsFlowFile, client, url, getLogger(), transactionId); config.setDestinationAccepts(destinationAccepts); } catch (final IOException e) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); logger.error( "Unable to communicate with destination {} to determine whether or not it can accept " + "flowfiles/gzip; routing {} to failure due to {}", new Object[] { url, flowFile, e }); context.yield(); return; } } } bytesToSend += flowFile.getSize(); if (bytesToSend > maxBatchBytes.longValue()) { break; } // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format, // then only use a single FlowFile if (!sendAsFlowFile || !destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted()) { break; } } if (toSend.isEmpty()) { return; } final String url = lastUrl; final HttpPost post = new HttpPost(url); final List<FlowFile> flowFileList = toSend; final DestinationAccepts accepts = destinationAccepts; final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null; final EntityTemplate entity = new EntityTemplate(new ContentProducer() { @Override public void writeTo(final OutputStream rawOut) throws IOException { final OutputStream throttled = throttler == null ? rawOut : throttler.newThrottledOutputStream(rawOut); OutputStream wrappedOut = new BufferedOutputStream(throttled); if (compressionLevel > 0 && accepts.isGzipAccepted()) { wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel); } try (final OutputStream out = wrappedOut) { for (final FlowFile flowFile : flowFileList) { session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream rawIn) throws IOException { try (final InputStream in = new BufferedInputStream(rawIn)) { FlowFilePackager packager = null; if (!sendAsFlowFile) { packager = null; } else if (accepts.isFlowFileV3Accepted()) { packager = new FlowFilePackagerV3(); } else if (accepts.isFlowFileV2Accepted()) { packager = new FlowFilePackagerV2(); } else if (accepts.isFlowFileV1Accepted()) { packager = new FlowFilePackagerV1(); } // if none of the above conditions is met, we should never get here, because // we will have already verified that at least 1 of the FlowFile packaging // formats is acceptable if sending as FlowFile. if (packager == null) { StreamUtils.copy(in, out); } else { final Map<String, String> flowFileAttributes; if (isDestinationLegacyNiFi) { // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path; // in order to maintain backward compatibility, we copy the filename & path to those attribute keys. flowFileAttributes = new HashMap<>(flowFile.getAttributes()); flowFileAttributes.put("nf.file.name", flowFile.getAttribute(CoreAttributes.FILENAME.key())); flowFileAttributes.put("nf.file.path", flowFile.getAttribute(CoreAttributes.PATH.key())); } else { flowFileAttributes = flowFile.getAttributes(); } packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize()); } } } }); } out.flush(); } } }) { @Override public long getContentLength() { if (compressionLevel == 0 && !sendAsFlowFile && !context.getProperty(CHUNKED_ENCODING).asBoolean()) { return toSend.get(0).getSize(); } else { return -1; } } }; if (context.getProperty(CHUNKED_ENCODING).isSet()) { entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean()); } post.setEntity(entity); post.setConfig(requestConfig); final String contentType; if (sendAsFlowFile) { if (accepts.isFlowFileV3Accepted()) { contentType = APPLICATION_FLOW_FILE_V3; } else if (accepts.isFlowFileV2Accepted()) { contentType = APPLICATION_FLOW_FILE_V2; } else if (accepts.isFlowFileV1Accepted()) { contentType = APPLICATION_FLOW_FILE_V1; } else { logger.error( "Cannot send data to {} because the destination does not accept FlowFiles and this processor is " + "configured to deliver FlowFiles; rolling back session", new Object[] { url }); session.rollback(); context.yield(); IOUtils.closeQuietly(client); return; } } else { final String contentTypeValue = context.getProperty(CONTENT_TYPE) .evaluateAttributeExpressions(toSend.get(0)).getValue(); contentType = StringUtils.isBlank(contentTypeValue) ? DEFAULT_CONTENT_TYPE : contentTypeValue; } final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue(); if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) { final Pattern pattern = Pattern.compile(attributeHeaderRegex); final Map<String, String> attributes = flowFileList.get(0).getAttributes(); for (final Map.Entry<String, String> entry : attributes.entrySet()) { final String key = entry.getKey(); if (pattern.matcher(key).matches()) { post.setHeader(entry.getKey(), entry.getValue()); } } } post.setHeader(CONTENT_TYPE_HEADER, contentType); post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true"); post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION); post.setHeader(TRANSACTION_ID_HEADER, transactionId); if (compressionLevel > 0 && accepts.isGzipAccepted()) { if (sendAsFlowFile) { post.setHeader(GZIPPED_HEADER, "true"); } else { post.setHeader(CONTENT_ENCODING_HEADER, CONTENT_ENCODING_GZIP_VALUE); } } // Do the actual POST final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles"; final String uploadDataRate; final long uploadMillis; CloseableHttpResponse response = null; try { final StopWatch stopWatch = new StopWatch(true); response = client.execute(post); // consume input stream entirely, ignoring its contents. If we // don't do this, the Connection will not be returned to the pool EntityUtils.consume(response.getEntity()); stopWatch.stop(); uploadDataRate = stopWatch.calculateDataRate(bytesToSend); uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS); } catch (final IOException e) { logger.error("Failed to Post {} due to {}; transferring to failure", new Object[] { flowFileDescription, e }); context.yield(); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } finally { if (response != null) { try { response.close(); } catch (final IOException e) { getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e }); } } } // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us // from posting to some other webservice and then attempting to delete some resource to which // we are redirected final int responseCode = response.getStatusLine().getStatusCode(); final String responseReason = response.getStatusLine().getReasonPhrase(); String holdUri = null; if (responseCode == HttpServletResponse.SC_SEE_OTHER) { final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME); if (locationUriHeader != null) { if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) { final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME); if (holdUriHeader != null) { holdUri = holdUriHeader.getValue(); } } } if (holdUri == null) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } } if (holdUri == null) { if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error( "Failed to Post {} to {}: response code was {}:{}; will yield processing, " + "since the destination is temporarily unavailable", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } context.yield(); return; } if (responseCode >= 300) { for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); logger.error("Failed to Post {} to {}: response code was {}:{}", new Object[] { flowFile, url, responseCode, responseReason }); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription, url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate }); for (final FlowFile flowFile : toSend) { session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis, true); session.transfer(flowFile, REL_SUCCESS); } return; } // // the response indicated a Hold URI; delete the Hold. // // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have // changed over the past, so we have to take into account a few different possibilities. String fullHoldUri = holdUri; if (holdUri.startsWith("/contentListener")) { // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener, // as this really indicates that it should be whatever we posted to -- if posting directly to the // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may // be posting to some other URL. fullHoldUri = url + holdUri.substring(16); } else if (holdUri.startsWith("/")) { // URL indicates the full path but not hostname or port; use the same hostname & port that we posted // to but use the full path indicated by the response. int firstSlash = url.indexOf("/", 8); if (firstSlash < 0) { firstSlash = url.length(); } final String beforeSlash = url.substring(0, firstSlash); fullHoldUri = beforeSlash + holdUri; } else if (!holdUri.startsWith("http")) { // Absolute URL fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri; } final HttpDelete delete = new HttpDelete(fullHoldUri); delete.setHeader(TRANSACTION_ID_HEADER, transactionId); while (true) { try { final HttpResponse holdResponse = client.execute(delete); EntityUtils.consume(holdResponse.getEntity()); final int holdStatusCode = holdResponse.getStatusLine().getStatusCode(); final String holdReason = holdResponse.getStatusLine().getReasonPhrase(); if (holdStatusCode >= 300) { logger.error( "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure", new Object[] { flowFileDescription, holdStatusCode, holdReason }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}", new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate }); for (final FlowFile flowFile : toSend) { session.getProvenanceReporter().send(flowFile, url); session.transfer(flowFile, REL_SUCCESS); } return; } catch (final IOException e) { logger.warn("Failed to delete Hold that destination placed on {} due to {}", new Object[] { flowFileDescription, e }); } if (!isScheduled()) { context.yield(); logger.warn( "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure", new Object[] { flowFileDescription }); for (FlowFile flowFile : toSend) { flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_FAILURE); } return; } } }
From source file:org.apache.nifi.processors.standard.servlets.ListenHTTPServlet.java
@Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final ProcessContext context = processContext; ProcessSessionFactory sessionFactory; do {//from w w w .j a v a 2s.c o m sessionFactory = sessionFactoryHolder.get(); if (sessionFactory == null) { try { Thread.sleep(10); } catch (final InterruptedException e) { } } } while (sessionFactory == null); final ProcessSession session = sessionFactory.createSession(); FlowFile flowFile = null; String holdUuid = null; String foundSubject = null; try { final long n = filesReceived.getAndIncrement() % FILES_BEFORE_CHECKING_DESTINATION_SPACE; if (n == 0 || !spaceAvailable.get()) { if (context.getAvailableRelationships().isEmpty()) { spaceAvailable.set(false); if (logger.isDebugEnabled()) { logger.debug("Received request from " + request.getRemoteHost() + " but no space available; Indicating Service Unavailable"); } response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } else { spaceAvailable.set(true); } } response.setHeader("Content-Type", MediaType.TEXT_PLAIN); final boolean contentGzipped = Boolean.parseBoolean(request.getHeader(GZIPPED_HEADER)); final X509Certificate[] certs = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); foundSubject = DEFAULT_FOUND_SUBJECT; if (certs != null && certs.length > 0) { for (final X509Certificate cert : certs) { foundSubject = cert.getSubjectDN().getName(); if (authorizedPattern.matcher(foundSubject).matches()) { break; } else { logger.warn("Rejecting transfer attempt from " + foundSubject + " because the DN is not authorized, host=" + request.getRemoteHost()); response.sendError(HttpServletResponse.SC_FORBIDDEN, "not allowed based on dn"); return; } } } final String destinationVersion = request.getHeader(PROTOCOL_VERSION_HEADER); Integer protocolVersion = null; if (destinationVersion != null) { try { protocolVersion = Integer.valueOf(destinationVersion); } catch (final NumberFormatException e) { // Value was invalid. Treat as if the header were missing. } } final boolean destinationIsLegacyNiFi = (protocolVersion == null); final boolean createHold = Boolean.parseBoolean(request.getHeader(FLOWFILE_CONFIRMATION_HEADER)); final String contentType = request.getContentType(); final InputStream unthrottled = contentGzipped ? new GZIPInputStream(request.getInputStream()) : request.getInputStream(); final InputStream in = (streamThrottler == null) ? unthrottled : streamThrottler.newThrottledInputStream(unthrottled); if (logger.isDebugEnabled()) { logger.debug("Received request from " + request.getRemoteHost() + ", createHold=" + createHold + ", content-type=" + contentType + ", gzip=" + contentGzipped); } final AtomicBoolean hasMoreData = new AtomicBoolean(false); final FlowFileUnpackager unpackager; if (APPLICATION_FLOW_FILE_V3.equals(contentType)) { unpackager = new FlowFileUnpackagerV3(); } else if (APPLICATION_FLOW_FILE_V2.equals(contentType)) { unpackager = new FlowFileUnpackagerV2(); } else if (APPLICATION_FLOW_FILE_V1.equals(contentType)) { unpackager = new FlowFileUnpackagerV1(); } else { unpackager = null; } final Set<FlowFile> flowFileSet = new HashSet<>(); do { final long startNanos = System.nanoTime(); final Map<String, String> attributes = new HashMap<>(); flowFile = session.create(); flowFile = session.write(flowFile, new OutputStreamCallback() { @Override public void process(final OutputStream rawOut) throws IOException { try (final BufferedOutputStream bos = new BufferedOutputStream(rawOut, 65536)) { if (unpackager == null) { IOUtils.copy(in, bos); hasMoreData.set(false); } else { attributes.putAll(unpackager.unpackageFlowFile(in, bos)); if (destinationIsLegacyNiFi) { if (attributes.containsKey("nf.file.name")) { // for backward compatibility with old nifi... attributes.put(CoreAttributes.FILENAME.key(), attributes.remove("nf.file.name")); } if (attributes.containsKey("nf.file.path")) { attributes.put(CoreAttributes.PATH.key(), attributes.remove("nf.file.path")); } } hasMoreData.set(unpackager.hasMoreData()); } } } }); final long transferNanos = System.nanoTime() - startNanos; final long transferMillis = TimeUnit.MILLISECONDS.convert(transferNanos, TimeUnit.NANOSECONDS); // put metadata on flowfile final String nameVal = request.getHeader(CoreAttributes.FILENAME.key()); if (StringUtils.isNotBlank(nameVal)) { attributes.put(CoreAttributes.FILENAME.key(), nameVal); } // put arbitrary headers on flow file for (Enumeration<String> headerEnum = request.getHeaderNames(); headerEnum.hasMoreElements();) { String headerName = headerEnum.nextElement(); if (headerPattern != null && headerPattern.matcher(headerName).matches()) { String headerValue = request.getHeader(headerName); attributes.put(headerName, headerValue); } } String sourceSystemFlowFileIdentifier = attributes.get(CoreAttributes.UUID.key()); if (sourceSystemFlowFileIdentifier != null) { sourceSystemFlowFileIdentifier = "urn:nifi:" + sourceSystemFlowFileIdentifier; // If we receveied a UUID, we want to give the FlowFile a new UUID and register the sending system's // identifier as the SourceSystemFlowFileIdentifier field in the Provenance RECEIVE event attributes.put(CoreAttributes.UUID.key(), UUID.randomUUID().toString()); } flowFile = session.putAllAttributes(flowFile, attributes); session.getProvenanceReporter().receive(flowFile, request.getRequestURL().toString(), sourceSystemFlowFileIdentifier, "Remote DN=" + foundSubject, transferMillis); flowFile = session.putAttribute(flowFile, "restlistener.remote.source.host", request.getRemoteHost()); flowFile = session.putAttribute(flowFile, "restlistener.remote.user.dn", foundSubject); flowFileSet.add(flowFile); if (holdUuid == null) { holdUuid = flowFile.getAttribute(CoreAttributes.UUID.key()); } } while (hasMoreData.get()); if (createHold) { String uuid = (holdUuid == null) ? UUID.randomUUID().toString() : holdUuid; if (flowFileMap.containsKey(uuid)) { uuid = UUID.randomUUID().toString(); } final FlowFileEntryTimeWrapper wrapper = new FlowFileEntryTimeWrapper(session, flowFileSet, System.currentTimeMillis()); FlowFileEntryTimeWrapper previousWrapper; do { previousWrapper = flowFileMap.putIfAbsent(uuid, wrapper); if (previousWrapper != null) { uuid = UUID.randomUUID().toString(); } } while (previousWrapper != null); response.setStatus(HttpServletResponse.SC_SEE_OTHER); final String ackUri = "/" + basePath + "/holds/" + uuid; response.addHeader(LOCATION_HEADER_NAME, ackUri); response.addHeader(LOCATION_URI_INTENT_NAME, LOCATION_URI_INTENT_VALUE); response.getOutputStream().write(ackUri.getBytes("UTF-8")); if (logger.isDebugEnabled()) { logger.debug( "Ingested {} from Remote Host: [{}] Port [{}] SubjectDN [{}]; placed hold on these {} files with ID {}", new Object[] { flowFileSet, request.getRemoteHost(), request.getRemotePort(), foundSubject, flowFileSet.size(), uuid }); } } else { response.setStatus(HttpServletResponse.SC_OK); logger.info( "Received from Remote Host: [{}] Port [{}] SubjectDN [{}]; transferring to 'success' {}", new Object[] { request.getRemoteHost(), request.getRemotePort(), foundSubject, flowFile }); session.transfer(flowFileSet, ListenHTTP.RELATIONSHIP_SUCCESS); session.commit(); } } catch (final Throwable t) { session.rollback(); if (flowFile == null) { logger.error("Unable to receive file from Remote Host: [{}] SubjectDN [{}] due to {}", new Object[] { request.getRemoteHost(), foundSubject, t }); } else { logger.error("Unable to receive file {} from Remote Host: [{}] SubjectDN [{}] due to {}", new Object[] { flowFile, request.getRemoteHost(), foundSubject, t }); } response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.toString()); } }
From source file:org.apache.syncope.ext.saml2lsp.agent.AbstractSAML2SPServlet.java
protected void prepare(final HttpServletResponse response, final SAML2RequestTO requestTO) throws IOException { response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store"); response.setHeader("Pragma", "no-cache"); switch (requestTO.getBindingType()) { case REDIRECT: UriBuilder ub = UriBuilder.fromUri(requestTO.getIdpServiceAddress()); ub.queryParam(SSOConstants.SAML_REQUEST, requestTO.getContent()); ub.queryParam(SSOConstants.RELAY_STATE, requestTO.getRelayState()); ub.queryParam(SSOConstants.SIG_ALG, requestTO.getSignAlg()); ub.queryParam(SSOConstants.SIGNATURE, requestTO.getSignature()); response.setStatus(HttpServletResponse.SC_SEE_OTHER); response.setHeader("Location", ub.build().toASCIIString()); break;/*from w ww. j ava 2 s . c om*/ case POST: default: response.setContentType(MediaType.TEXT_HTML); response.getWriter().write("" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + " <body onLoad=\"document.forms[0].submit();\">" + " <form action=\"" + requestTO.getIdpServiceAddress() + "\" method=\"POST\">" + " <input type=\"hidden\" name=\"" + SSOConstants.SAML_REQUEST + "\"" + " value=\"" + requestTO.getContent() + "\"/>" + " <input type=\"hidden\" name=\"" + SSOConstants.RELAY_STATE + "\"" + " value=\"" + requestTO.getRelayState() + "\"/>" + " <input type=\"submit\" style=\"visibility: hidden;\"/>" + " </form>" + " </body>" + "</html>"); } }
From source file:org.bibsonomy.webapp.filters.ContentNegotiationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final String requestURI = httpRequest.getRequestURI(); /*/*from w w w . j a v a 2 s.co m*/ * proceed to next filter, if method is not GET or HEAD * * Note: we use strings since the filter is called often and we don't * want the overhead of org.bibsonomy.rest.enums.HttpMethod. Furthermore, * we would need to catch the UnsupportedHttpMethodException. * */ final String httpMethod = httpRequest.getMethod().toUpperCase(); if (!("GET".equals(httpMethod) || "HEAD".equals(httpMethod))) { log.debug("skipping " + ContentNegotiationFilter.class.getName() + " for " + requestURI + " (cause: unsupported HTTP method " + httpMethod + ")"); chain.doFilter(request, response); return; } /* * proceed to next filter in chain for certain patterns */ if (excludePattern.matcher(requestURI).matches()) { log.debug("skipping " + ContentNegotiationFilter.class.getName() + " for " + requestURI + " (cause: match in exclude pattern)"); chain.doFilter(request, response); return; } final String firstPathElement = UrlUtils.getFirstPathElement(requestURI); /* * We skip working on the request when a specific format is already * selected using the URL path or the URL's "format" parameter. * * This is also crucial to avoid redirect loops! * * Note: we must ignore "bibtex" here (which is accepted by * Views.getViewByFormat), since as path part it is not a format. * */ if (!Views.FORMAT_STRING_BIBTEX.equals(firstPathElement)) { try { Views.getViewByFormat(firstPathElement); chain.doFilter(request, response); log.debug("skipping " + ContentNegotiationFilter.class.getName() + " for " + requestURI + " (cause: format selected by URL path)"); return; } catch (final BadRequestOrResponseException e) { // no known format selected - continue } } try { Views.getViewByFormat(httpRequest.getParameter("format")); chain.doFilter(request, response); log.debug("skipping " + ContentNegotiationFilter.class.getName() + " for " + requestURI + " (cause: format selected by URL parameter)"); return; } catch (final BadRequestOrResponseException e) { // no known format selected - continue } final String accept = httpRequest.getHeader("Accept"); log.debug("working on accept header '" + accept + "'"); log.debug("request URI: " + requestURI); final String responseFormat = getResponseFormat(accept); log.debug("format would be: " + responseFormat); if (present(responseFormat)) { /* * send redirect */ final HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setStatus(HttpServletResponse.SC_SEE_OTHER); httpServletResponse.sendRedirect("/" + responseFormat + HeaderUtils.getPathAndQuery(httpRequest)); /* * stop processing */ return; } chain.doFilter(httpRequest, response); }
From source file:org.dspace.rdf.negotiation.Negotiator.java
public static boolean sendRedirect(HttpServletResponse response, String handle, String extraPathInfo, int serialization, boolean redirectHTML) throws IOException { if (extraPathInfo == null) extraPathInfo = ""; StringBuilder urlBuilder = new StringBuilder(); String lang = null;//from w w w. j a va2s . c om switch (serialization) { case (Negotiator.UNSPECIFIED): case (Negotiator.WILDCARD): { lang = DEFAULT_LANG; break; } case (Negotiator.HTML): { lang = "html"; break; } case (Negotiator.RDFXML): { lang = "rdf"; break; } case (Negotiator.TURTLE): { lang = "turtle"; break; } case (Negotiator.N3): { lang = "n3"; break; } default: { lang = DEFAULT_LANG; break; } } assert (lang != null); if (StringUtils.isEmpty(handle)) { log.warn("Handle is empty, set it to Site Handle."); handle = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("handle.prefix") + "/0"; } // don't redirect if HTML is requested and content negotiation is done // in a ServletFilter, as the ServletFilter should just let the request // pass. if ("html".equals(lang) && !redirectHTML) { return false; } // as we do content negotiation and we'll redirect the request, we // should send a vary caching so browsers can adopt their caching strategy response.setHeader("Vary", "Accept"); // if html is requested we have to forward to the repositories webui. if ("html".equals(lang)) { urlBuilder.append( DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("dspace.url")); if (!handle.equals( DSpaceServicesFactory.getInstance().getConfigurationService().getProperty("handle.prefix") + "/0")) { urlBuilder.append("/handle/"); urlBuilder.append(handle).append("/").append(extraPathInfo); } String url = urlBuilder.toString(); log.debug("Will forward to '" + url + "'."); response.setStatus(HttpServletResponse.SC_SEE_OTHER); response.setHeader("Location", url); response.flushBuffer(); return true; } // currently we cannot serve statistics as rdf if ("statistics".equals(extraPathInfo)) { log.info("Cannot send statistics as RDF yet. => 406 Not Acceptable."); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); response.flushBuffer(); return true; } // load the URI of the dspace-rdf module. urlBuilder.append(DSpaceServicesFactory.getInstance().getConfigurationService() .getProperty(RDFUtil.CONTEXT_PATH_KEY)); if (urlBuilder.length() == 0) { log.error("Cannot load URL of dspace-rdf module. " + "=> 500 Internal Server Error"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.flushBuffer(); return true; } // and build the uri to the DataProviderServlet urlBuilder.append("/handle/").append(handle); urlBuilder.append("/").append(lang); String url = urlBuilder.toString(); log.debug("Will forward to '" + url + "'."); response.setStatus(HttpServletResponse.SC_SEE_OTHER); response.setHeader("Location", url); response.flushBuffer(); return true; }