Example usage for javax.servlet.http HttpServletResponse SC_ACCEPTED

List of usage examples for javax.servlet.http HttpServletResponse SC_ACCEPTED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_ACCEPTED.

Prototype

int SC_ACCEPTED

To view the source code for javax.servlet.http HttpServletResponse SC_ACCEPTED.

Click Source Link

Document

Status code (202) indicating that a request was accepted for processing, but was not completed.

Usage

From source file:org.alfresco.rest.api.tests.TestDownloads.java

/**
 * Tests canceling a download./*from w w  w  . j  av a  2  s.c o  m*/
 *
 * <p>DELETE:</p>
 * {@literal <host>:<port>/alfresco/api/-default-/private/alfresco/versions/1/downloads/<download_id>}
 * 
 */
@Test
public void test003CancelDownload() throws Exception {
    //cancel a running download operation.
    cancelWithRetry(() -> {
        Download download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableFolderId1,
                zippableDocId3_InFolder1, zippableDocId1, zippableDocId2);
        cancel(download.getId());
        assertCancelledDownload(download, 5, 65);
    });

    //cancel a completed download - should have no effect
    Download download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1, zippableDocId2);

    assertDoneDownload(download, 2, 26);

    cancel(download.getId());

    Thread.sleep(500);

    Download downloadStatus = getDownload(download.getId());

    assertTrue("A cancel operation on a DONE download has no effect.",
            downloadStatus.getStatus().equals(DownloadStatus.Status.DONE));

    //cancel a node which is not of a download type
    cancel(HttpServletResponse.SC_BAD_REQUEST, zippableDocId1);

    //user2 canceling user1 download operation - should not be allowed
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1);

    setRequestContext(user2);

    cancel(HttpServletResponse.SC_FORBIDDEN, download.getId());
}

From source file:net.cbtltd.server.UploadFileService.java

/**
 * Handles upload file requests is in a page submitted by a HTTP POST method.
 * Form field values are extracted into a parameter list to set an associated Text instance.
 * 'File' type merely saves file and creates associated db record having code = file name.
 * Files may be rendered by reference in a browser if the browser is capable of the file type.
 * 'Image' type creates and saves thumbnail and full size jpg images and creates associated
 * text record having code = full size file name. The images may be viewed by reference in a browser.
 * 'Blob' type saves file and creates associated text instance having code = full size file name
 * and a byte array data value equal to the binary contents of the file.
 *
 * @param request the HTTP upload request.
 * @param response the HTTP response.//w  w w . j  av  a 2 s. com
 * @throws ServletException signals that an HTTP exception has occurred.
 * @throws IOException signals that an I/O exception has occurred.
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletRequestContext ctx = new ServletRequestContext(request);

    if (ServletFileUpload.isMultipartContent(ctx) == false) {
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The servlet can only handle multipart requests."));
        return;
    }

    LOG.debug("UploadFileService doPost request " + request);

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    LOG.debug("\n doPost upload " + upload);

    SqlSession sqlSession = RazorServer.openSession();
    try {
        HashMap<String, String> params = new HashMap<String, String>();
        for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
            if (item.isFormField()) { // add for field value to parameter list
                String param = item.getFieldName();
                String value = item.getString();
                params.put(param, value);
            } else if (item.getSize() > 0) { // process uploaded file
                //               String fn = RazorServer.ROOT_DIRECTORY + item.getFieldName();    // input file path
                String fn = RazorConfig.getImageURL() + item.getFieldName(); // input file path
                LOG.debug("doPost fn " + fn);
                byte[] data = item.get();
                String mimeType = item.getContentType();

                String productId = item.getFieldName();
                Pattern p = Pattern.compile("\\d+");
                Matcher m = p.matcher(productId);
                while (m.find()) {
                    productId = m.group();
                    LOG.debug("Image uploaded for Product ID: " + productId);
                    break;
                }

                // TO DO - convert content type to mime..also check if uploaded type is image

                // getMagicMatch accepts Files or byte[],
                // which is nice if you want to test streams
                MagicMatch match = null;
                try {
                    match = parser.getMagicMatch(data, false);
                    LOG.debug("Mime type of image: " + match.getMimeType());
                } catch (MagicParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicMatchNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (match != null) {
                    mimeType = match.getMimeType();
                }

                // image processor logic needs to know about the format of the image
                String contentType = RazorConfig.getMimeExtension(mimeType);

                if (StringUtils.isNotEmpty(contentType)) {
                    ImageService.uploadImages(sqlSession, productId, item.getFieldName(),
                            params.get(Text.FILE_NOTES), data, contentType);
                    LOG.debug("doPost commit params " + params);
                    sqlSession.commit();
                } else {
                    // unknown content/mime type...do not upload the file
                    sendResponse(response, new FormResponse(HttpServletResponse.SC_BAD_REQUEST,
                            "File type - " + contentType + " is not supported"));
                }
                //               File file = new File(fn);                            // output file name
                //               File tempf = File.createTempFile(Text.TEMP_FILE, "");
                //               item.write(tempf);
                //               file.delete();
                //               tempf.renameTo(file);
                //               int fullsizepixels = Integer.valueOf(params.get(Text.FULLSIZE_PIXELS));
                //               if (fullsizepixels <= 0) {fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;}
                //               int thumbnailpixels = Integer.valueOf(params.get(Text.THUMBNAIL_PIXELS));
                //               if (thumbnailpixels <= 0) {thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;}
                //
                //               setText(sqlSession, file, fn, params.get(Text.FILE_NAME), params.get(Text.FILE_TYPE), params.get(Text.FILE_NOTES), Language.EN, fullsizepixels, thumbnailpixels);
            }
        }
        sendResponse(response, new FormResponse(HttpServletResponse.SC_ACCEPTED, "OK"));
    } catch (Throwable x) {
        sqlSession.rollback();
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage()));
        LOG.error("doPost error " + x.getMessage());
    } finally {
        sqlSession.close();
    }
}

From source file:gov.nist.appvet.tool.AsynchronousService.java

private void sendHttp202(HttpServletResponse response, String message) {
    try {//from  w  w  w  . java 2 s  .  c om
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(message);
        out.flush();
        out.close();
        log.debug("Sent HTTP 202: " + message);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.dasein.cloud.azure.tests.network.AzureIpAddressSupportTest.java

@Test
public void stopForwardToServerShouldPostCorrectRequest() throws CloudException, InternalException {
    final AtomicInteger putCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 2)//w w  w  .  j  a va  2 s  . co m
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if (request.getMethod().equals("GET")) {
                DaseinObjectToXmlEntity<PersistentVMRoleModel> daseinEntity = new DaseinObjectToXmlEntity<PersistentVMRoleModel>(
                        createPersistentVMRoleModelWithEndpoint());
                assertGet(request, EXPECTED_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if (request.getMethod().equals("PUT")) {
                putCount.incrementAndGet();
                PersistentVMRoleModel persistentVMRoleModel = createPersistentVMRoleModelWithoutEndpoint();
                //set an empty list otherwise unitils will assert fail as one is null while another is empty list
                persistentVMRoleModel.getConfigurationSets().get(0)
                        .setInputEndpoints(new ArrayList<PersistentVMRoleModel.InputEndpoint>());
                assertPut(request, EXPECTED_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        persistentVMRoleModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_ACCEPTED), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    String ruleId = new AzureRuleIdParts(VM_ID, Protocol.TCP.toString(), String.valueOf(PRIVATE_PORT))
            .toProviderId();
    ipAddressSupport.stopForwardToServer(ruleId, VM_ID);
    assertEquals("PUT count doesn't match", 1, putCount.get());
}

From source file:com.imaginary.home.cloud.api.call.DeviceCall.java

@Override
public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {//  www.  j  a  v a  2 s  .co m
        String deviceId = (path.length > 1 ? path[1] : null);
        Device device = null;

        if (deviceId != null) {
            device = Device.getDevice(deviceId);
        }
        if (device == null) {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                    "The device " + deviceId + " does not exist.");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());
        String action;

        if (object.has("action") && !object.isNull("action")) {
            action = object.getString("action");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "An invalid action was specified (or not specified) in the PUT");
        }
        if (action.equals("flipOn") || action.equals("flipOff")) {
            if (userId == null) {
                throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.RELAY_NOT_ALLOWED,
                        "Invalid relay actiojn: " + action);
            }
            HashMap<String, Object> json = new HashMap<String, Object>();
            TimePeriod p = null;

            if (object.has("timeout") && !object.isNull("timeout")) {
                try {
                    p = TimePeriod.valueOf(object.getString("timeout"));
                } catch (Throwable ignore) {
                    // ignore
                }
            }
            if (p == null) {
                p = new TimePeriod<Minute>(5, TimePeriod.MINUTE);
            }
            json.put("command", action);
            json.put("arguments", new HashMap<String, Object>());
            PendingCommand[] cmds = PendingCommand.queue(userId, p,
                    new String[] { (new JSONObject(json)).toString() }, device);

            ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

            for (PendingCommand cmd : cmds) {
                list.add(CommandCall.toJSON(cmd));
            }
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            resp.getWriter().println((new JSONArray(list)).toString());
            resp.getWriter().flush();
        }
        /*
        else if( action.equalsIgnoreCase("modify") ) {
        if( object.has("device") ) {
            object = object.getJSONObject("device");
        }
        else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PUT, "No device was specified in the PUT");
        }
        String name, description;
        TimeZone timeZone;
                
        if( object.has("name") && !object.isNull("name") ) {
            name = object.getString("name");
        }
        else {
            name = location.getName();
        }
        if( object.has("description") && !object.isNull("description") ) {
            description = object.getString("description");
        }
        else {
            description = location.getName();
        }
        if( object.has("timeZone") && !object.isNull("timeZone") ) {
            String tz = object.getString("timeZone");
                
            timeZone = TimeZone.getTimeZone(tz);
        }
        else {
            timeZone = location.getTimeZone();
        }
        location.modify(name, description, timeZone);
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
        */
        else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "The action " + action + " is not a valid action.");
        }
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in request");
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

protected void delete(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource)
        throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".delete(" + authToken + "," + endpoint + ","
                + resource + ")");
    }//from  w w w. ja  va  2s .  c  o  m
    if (wire.isDebugEnabled()) {
        wire.debug("--------------------------------------------------------> " + endpoint + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpDelete delete = new HttpDelete(endpoint + resource);

        delete.addHeader("Content-Type", "application/json");
        delete.addHeader("X-Auth-Token", authToken);

        if (wire.isDebugEnabled()) {
            wire.debug(delete.getRequestLine().toString());
            for (Header header : delete.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            response = client.execute(delete);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);

        if (code != HttpServletResponse.SC_NO_CONTENT && code != HttpServletResponse.SC_ACCEPTED) {
            std.error("delete(): Expected NO CONTENT for DELETE request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items = (json == null ? null
                    : RackspaceException.parseException(code, json));

            if (items == null) {
                items = new RackspaceException.ExceptionItems();
                items.code = 404;
                items.type = CloudErrorType.COMMUNICATION;
                items.message = "itemNotFound";
                items.details = "No such object: " + resource;
            }
            std.error("delete(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            wire.debug("");
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".delete()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + endpoint + resource);
        }
    }
}

From source file:org.apache.servicemix.http.processors.ConsumerProcessor.java

public void process(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Receiving HTTP request: " + request);
    }// w  w w. j  a  va2  s  .  c  o  m
    if ("GET".equals(request.getMethod())) {
        processGetRequest(request, response);
        return;
    }
    if (!started) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Endpoint is stopped");
        return;
    }
    if (!"POST".equals(request.getMethod())) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request.getMethod() + " not supported");
        return;
    }
    // Not giving a specific mutex will synchronize on the contination itself
    Continuation cont = ContinuationSupport.getContinuation(request, null);
    MessageExchange exchange;
    // If the continuation is not a retry
    if (!cont.isPending()) {
        try {
            Context ctx = createContext(request);
            request.setAttribute(Context.class.getName(), ctx);
            exchange = soapHelper.onReceive(ctx);
            exchanges.put(exchange.getExchangeId(), exchange);
            NormalizedMessage inMessage = exchange.getMessage("in");

            Map<String, String> protocolHeaders = new HashMap();
            if (getConfiguration().isWantHeadersFromHttpIntoExchange()) {
                protocolHeaders.putAll(getHeaders(request));
            }
            protocolHeaders.put(AbstractProcessor.HEADER_X_REMOTE_HOST, getClientIp(request));
            inMessage.setProperty(JbiConstants.PROTOCOL_HEADERS, protocolHeaders);
            if (request.getHeader(HEADER_X_CORRELATION_ID) != null) {
                response.addHeader(HEADER_X_CORRELATION_ID, request.getHeader(HEADER_X_CORRELATION_ID));
            }
            String smxInstanceName = System.getProperty(SMX_INSTANCE_NAME_PROPERTY);
            if (smxInstanceName != null) {
                response.addHeader(HEADER_X_POWERED_BY, smxInstanceName);
            } else {
                log.warn(SMX_INSTANCE_NAME_PROPERTY + " property was not set in servicemix.xml file");
            }

            locks.put(exchange.getExchangeId(), cont);
            request.setAttribute(MessageExchange.class.getName(), exchange.getExchangeId());
            synchronized (cont) {
                channel.send(exchange);
                if (log.isDebugEnabled()) {
                    log.debug("Suspending continuation for exchange: " + exchange.getExchangeId());
                }
                boolean result = cont.suspend(suspentionTime);
                exchange = exchanges.remove(exchange.getExchangeId());
                request.removeAttribute(MessageExchange.class.getName());
                if (!result) {
                    locks.remove(exchange.getExchangeId());
                    throw new Exception("Exchange timed out");
                }
            }
        } catch (RetryRequest retry) {
            throw retry;
        } catch (SoapFault fault) {
            sendFault(fault, request, response);
            return;
        } catch (Exception e) {
            sendFault(new SoapFault(e), request, response);
            return;
        }
    } else {
        synchronized (cont) {
            String id = (String) request.getAttribute(MessageExchange.class.getName());
            locks.remove(id);
            exchange = exchanges.remove(id);
            request.removeAttribute(MessageExchange.class.getName());
            // Check if this is a timeout
            if (exchange == null) {
                throw new IllegalStateException("Exchange not found");
            }
            if (log.isDebugEnabled() && request.getHeader(HEADER_X_CORRELATION_ID) != null) {
                String externalCorrelationId = request.getHeader(HEADER_X_CORRELATION_ID);
                String exchangeCorrelationId = (String) exchange.getProperty(JbiConstants.CORRELATION_ID);
                log.debug("Message exchange with correlationId='" + exchangeCorrelationId
                        + "' is correlated with external message exchange with correlationId='"
                        + externalCorrelationId + "'");
            }
            if (!cont.isResumed()) {
                Exception e = new Exception("Exchange timed out: " + exchange.getExchangeId());
                sendFault(new SoapFault(e), request, response);
                return;
            }
        }
    }
    if (exchange.getStatus() == ExchangeStatus.ERROR) {
        if (exchange.getError() != null) {
            throw new Exception(exchange.getError());
        } else {
            throw new Exception("Unknown Error");
        }
    } else if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
        try {
            if (exchange.getFault() != null) {
                processFault(exchange, request, response);
            } else {
                processResponse(exchange, request, response);
            }
        } finally {
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);
        }
    } else if (exchange.getStatus() == ExchangeStatus.DONE) {
        // This happens when there is no response to send back
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
    }
}

From source file:org.alfresco.rest.api.tests.TestDownloads.java

/**
 * Tests downloading the content of a download node(a zip) using the /nodes API:
 *
 * <p>GET:</p>//from   ww w  . j  a v a2  s. c  o  m
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>/content}
 * 
 */
@Test
public void test004GetDownloadContent() throws Exception {

    //test downloading the content of a 1 file zip
    Download download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1);

    assertDoneDownload(download, 1, 13);

    HttpResponse response = downloadContent(download);

    ZipInputStream zipStream = getZipStreamFromResponse(response);

    ZipEntry zipEntry = zipStream.getNextEntry();

    assertEquals("Zip entry name is not correct", ZIPPABLE_DOC1_NAME, zipEntry.getName());

    assertTrue("Zip entry size is not correct", zipEntry.getCompressedSize() <= 13);

    assertTrue("No more entries should be in this zip", zipStream.getNextEntry() == null);
    zipStream.close();

    Map<String, String> responseHeaders = response.getHeaders();

    assertNotNull(responseHeaders);

    assertEquals(format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
            ZIPPABLE_DOC1_NAME + DEFAULT_ARCHIVE_EXTENSION, ZIPPABLE_DOC1_NAME + DEFAULT_ARCHIVE_EXTENSION),
            responseHeaders.get("Content-Disposition"));

    //test downloading the content of a multiple file zip
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableFolderId1, zippableDocId3_InFolder1);

    assertDoneDownload(download, 3, 39);

    response = downloadContent(download);

    zipStream = getZipStreamFromResponse(response);

    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/", zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/" + DOC3_NAME,
            zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/" + SUB_FOLDER1_NAME + "/",
            zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/" + SUB_FOLDER1_NAME + "/" + DOC4_NAME,
            zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", DOC3_NAME, zipStream.getNextEntry().getName());

    assertTrue("No more entries should be in this zip", zipStream.getNextEntry() == null);
    zipStream.close();

    responseHeaders = response.getHeaders();

    assertNotNull(responseHeaders);

    assertEquals(format("attachment; filename=\"%s\"; filename*=UTF-8''%s", DEFAULT_ARCHIVE_NAME,
            DEFAULT_ARCHIVE_NAME), responseHeaders.get("Content-Disposition"));

    //test download the content of a zip which has a secondary child
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1, zippableFolderId3);
    assertDoneDownload(download, 2, 26);

    response = downloadContent(download);

    zipStream = getZipStreamFromResponse(response);

    assertEquals("Zip entry name is not correct", ZIPPABLE_DOC1_NAME, zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER3_NAME + "/", zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER3_NAME + "/" + ZIPPABLE_DOC1_NAME,
            zipStream.getNextEntry().getName());
    assertTrue("No more entries should be in this zip", zipStream.getNextEntry() == null);
}

From source file:org.opencastproject.workspace.impl.WorkspaceImpl.java

/**
 * {@inheritDoc}/*from  w  ww.j  a v  a  2s  . c om*/
 * 
 * @see org.opencastproject.workspace.api.Workspace#get(java.net.URI)
 */
public File get(final URI uri) throws NotFoundException, IOException {
    final String urlString = uri.toString();
    final File f = getWorkspaceFile(uri, false);

    // Does the file exist and is it up to date?
    Long workspaceFileLastModified = new Long(0); // make sure this is not null, otherwise the requested file can not be
                                                  // copied
    if (f.isFile()) {
        workspaceFileLastModified = new Long(f.lastModified());
    }

    if (wfrRoot != null && wfrUrl != null) {
        if (uri.toString().startsWith(wfrUrl)) {
            String localPath = uri.toString().substring(wfrUrl.length());
            File wfrCopy = new File(PathSupport.concat(wfrRoot, localPath));
            if (wfrCopy.isFile()) {
                // if the file exists in the workspace, but is older than the wfr copy, replace it
                if (workspaceFileLastModified < wfrCopy.lastModified()) {
                    logger.debug("Replacing {} with an updated version from the file repository",
                            f.getAbsolutePath());
                    if (linkingEnabled) {
                        FileUtils.deleteQuietly(f);
                        FileSupport.link(wfrCopy, f);
                    } else {
                        FileSupport.copy(wfrCopy, f);
                    }
                } else {
                    logger.debug("{} is up to date", f);
                }
                logger.debug("Getting {} directly from working file repository root at {}", uri, f);
                return new File(f.getAbsolutePath());
            }
        }
    }

    String ifNoneMatch = null;
    if (f.isFile()) {
        ifNoneMatch = md5(f);
    }

    final HttpGet get = new HttpGet(urlString);
    if (ifNoneMatch != null)
        get.setHeader("If-None-Match", ifNoneMatch);

    return locked(f, new Function<File, File>() {
        @Override
        public File apply(File file) {
            InputStream in = null;
            OutputStream out = null;
            HttpResponse response = null;
            try {
                response = trustedHttpClient.execute(get);
                if (HttpServletResponse.SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
                    throw new NotFoundException(uri + " does not exist");
                } else if (HttpServletResponse.SC_NOT_MODIFIED == response.getStatusLine().getStatusCode()) {
                    logger.debug("{} has not been modified.", urlString);
                    return file;
                } else if (HttpServletResponse.SC_ACCEPTED == response.getStatusLine().getStatusCode()) {
                    logger.debug("{} is not ready, try again in one minute.", urlString);
                    String token = response.getHeaders("token")[0].getValue();
                    get.setParams(new BasicHttpParams().setParameter("token", token));
                    Thread.sleep(60000);
                    while (true) {
                        response = trustedHttpClient.execute(get);
                        if (HttpServletResponse.SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
                            throw new NotFoundException(uri + " does not exist");
                        } else if (HttpServletResponse.SC_NOT_MODIFIED == response.getStatusLine()
                                .getStatusCode()) {
                            logger.debug("{} has not been modified.", urlString);
                            return file;
                        } else if (HttpServletResponse.SC_ACCEPTED == response.getStatusLine()
                                .getStatusCode()) {
                            logger.debug("{} is not ready, try again in one minute.", urlString);
                            Thread.sleep(60000);
                        } else if (HttpServletResponse.SC_OK == response.getStatusLine().getStatusCode()) {
                            logger.info("Downloading {} to {}", urlString, file.getAbsolutePath());
                            file.createNewFile();
                            in = response.getEntity().getContent();
                            out = new FileOutputStream(file);
                            IOUtils.copyLarge(in, out);
                            return file;
                        } else {
                            logger.warn(
                                    "Received unexpected response status {} while trying to download from {}",
                                    response.getStatusLine().getStatusCode(), urlString);
                            FileUtils.deleteQuietly(file);
                            return chuck(new NotFoundException(
                                    "Unexpected response status " + response.getStatusLine().getStatusCode()));
                        }
                    }
                } else if (HttpServletResponse.SC_OK == response.getStatusLine().getStatusCode()) {
                    logger.info("Downloading {} to {}", urlString, file.getAbsolutePath());
                    file.createNewFile();
                    in = response.getEntity().getContent();
                    out = new FileOutputStream(file);
                    IOUtils.copyLarge(in, out);
                    return file;
                } else {
                    logger.warn("Received unexpected response status {} while trying to download from {}",
                            response.getStatusLine().getStatusCode(), urlString);
                    FileUtils.deleteQuietly(file);
                    return chuck(new NotFoundException(
                            "Unexpected response status " + response.getStatusLine().getStatusCode()));
                }
            } catch (Exception e) {
                logger.warn("Could not copy {} to {}: {}",
                        new String[] { urlString, file.getAbsolutePath(), e.getMessage() });
                FileUtils.deleteQuietly(file);
                return chuck(new NotFoundException(e));
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
                trustedHttpClient.close(response);
            }
        }
    });
}

From source file:org.wso2.carbon.dssapi.valve.DSSAPIValve.java

public void invoke(Request request, Response response, CompositeValve compositeValve) {
    String context1 = request.getCoyoteRequest().toString().replace("R( ", "");
    context1 = context1.substring(0, context1.lastIndexOf(")"));
    String context = null;/*from   w w w .j  a v  a 2 s  . com*/
    String tenantDomain = MultitenantUtils.getTenantDomain(request);
    AxisConfiguration configurationContext;
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
        configurationContext = TenantAxisUtils.getTenantAxisConfiguration(tenantDomain,
                DataHolder.getServerConfigContext());
    } else {
        configurationContext = DataHolder.getServerConfigContext().getAxisConfiguration();
    }
    if (context1.contains("api")) {
        context = context1.split("/[0-9][.][0-9][.][0-9]")[0];
    }

    if (context.isEmpty()) {
        //Invoke next valve in pipe.
        getNext().invoke(request, response, compositeValve);
        return;
    }
    boolean contextExist;
    Boolean contextValueInCache = null;
    if (APIUtil.getAPIContextCache().get(context) != null) {
        contextValueInCache = Boolean.parseBoolean(APIUtil.getAPIContextCache().get(context).toString());
    }
    if (contextValueInCache != null) {
        contextExist = contextValueInCache;
    } else {
        contextExist = ApiMgtDAO.isContextExist(context);
        APIUtil.getAPIContextCache().put(context, contextExist);
    }
    if (!contextExist) {
        getNext().invoke(request, response, compositeValve);
        return;
    }

    handleWSDLGetRequest(request, response, compositeValve, context);

    long requestTime = System.currentTimeMillis();
    APIManagerInterceptorOps interceptorOps = new APIManagerInterceptorOps();
    UsageStatConfiguration statConfiguration = new UsageStatConfiguration();

    //Use embedded API Management
    if (log.isDebugEnabled()) {
        log.debug("API Manager Interceptor Valve Got invoked!!");
    }

    String bearerToken = request.getHeader(APIConstants.OperationParameter.AUTH_PARAM_NAME);
    String accessToken = null;

    /* Authenticate*/
    try {
        if (bearerToken != null) {
            accessToken = APIManagetInterceptorUtils.getBearerToken(bearerToken);
        }

        String apiVersion = null;
        Matcher matcher = Pattern.compile("[0-9][.][0-9][.][0-9]").matcher(context1);
        while (matcher.find()) {
            apiVersion = matcher.group();
        }
        String domain = request.getHeader(APITokenValidator.getAPIManagerClientDomainHeader());
        String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion,
                request.getRequestURI(), request.getMethod());
        if (authLevel.equals(APIConstants.NO_MATCHING_AUTH_SCHEME)) {
            APIManagetInterceptorUtils.handleNoMatchAuthSchemeCallForRestService(response, request.getMethod(),
                    request.getRequestURI(), apiVersion, context);
            return;
        } else {
            interceptorOps.doAuthenticate(context, apiVersion, accessToken, authLevel, domain);
        }
    } catch (APIManagementException e) {
        String payLoad = "<ams:fault xmlns:ams=\"http://wso2.org/apimanager/security\">\n"
                + "  <ams:code>900902</ams:code>\n" + "  <ams:message> Invocation Failure </ams:message>\n"
                + "  <ams:description>" + e.getMessage() + " \"Authorization: Bearer "
                + "ACCESS_TOKEN\"</ams:description>\n" + "</ams:fault>";
        APIManagetInterceptorUtils.handleRestFailure(response, payLoad);
    } catch (APIFaultException e) {/* If !isAuthorized APIFaultException is thrown*/
        APIManagetInterceptorUtils.handleAPIFaultForRestService(e, APIManagerErrorConstants.API_SECURITY_NS,
                APIManagerErrorConstants.API_SECURITY_NS_PREFIX, response);
        return;
    }
    /* Throttle*/
    try {
        interceptorOps.doThrottle(request, accessToken);
    } catch (APIFaultException e) {
        APIManagetInterceptorUtils.handleAPIFaultForRestService(e, APIManagerErrorConstants.API_THROTTLE_NS,
                APIManagerErrorConstants.API_THROTTLE_NS_PREFIX, response);
        return;
    }
    /* Publish Statistic if enabled*/
    if (statConfiguration.isStatsPublishingEnabled()) {
        try {
            interceptorOps.publishStatistics(request, requestTime, false);
        } catch (APIManagementException e) {
            log.error("Error occurred when publishing stats", e);
        }
    }

    String serviceName = context.split("/api/")[1];
    String temp = context1.split("[0-9][.][0-9][.][0-9][/]")[1];
    String resourceName;
    String pathParam = null;
    if (temp.split("/").length > 1) {
        resourceName = temp.substring(0, temp.indexOf("/", 1));
        pathParam = temp.substring(temp.indexOf("/") + 1);
    } else {
        resourceName = temp;
    }
    BufferedReader bufferedReader = null;

    try {
        AxisService axisService = configurationContext.getService(serviceName);
        DataService dataService = (DataService) axisService.getParameter(DBConstants.DATA_SERVICE_OBJECT)
                .getValue();
        Map<String, ParamValue> paramValueMap = new HashMap<String, ParamValue>();
        Enumeration<String> requestParameters = request.getParameterNames();
        boolean isOperation = true;
        boolean pathParamExist = false;
        if (!"PUT".equalsIgnoreCase(request.getMethod())) {
            while (requestParameters.hasMoreElements()) {
                String requestKey = requestParameters.nextElement();
                paramValueMap.put(requestKey, new ParamValue(request.getParameter(requestKey)));
            }
        } else {
            bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String data = bufferedReader.readLine();
            if (data != null) {
                String[] formParameters = data.split("&");
                for (String nameValue : formParameters) {
                    String[] nameValuePair = nameValue.split("=");
                    paramValueMap.put(nameValuePair[0], new ParamValue(nameValuePair[1]));
                }
            }
        }

        Resource resource = null;
        if (pathParam != null) {
            pathParamExist = true;
            for (Resource.ResourceID resourceID : dataService.getResourceIds()) {
                if (Pattern.matches(resourceName + "/[{]\\w+[}]", resourceID.getPath())) {
                    resource = dataService.getResource(resourceID);
                }
            }
            if (resource != null) {
                Matcher paramNamePattern = Pattern.compile("[{]\\w+[}]")
                        .matcher(resource.getResourceId().getPath());
                paramNamePattern.find();
                String pathParamName = paramNamePattern.group().replace("{", "").replace("}", "");
                paramValueMap.put(pathParamName, new ParamValue(pathParam));
            }
        } else {
            resource = dataService.getResource(new Resource.ResourceID(resourceName, request.getMethod()));

        }
        if (resource != null) {
            isOperation = false;
        }
        try {
            OMElement output;
            if (!isOperation) {
                if (pathParamExist) {

                    output = DSTools.accessResource(dataService, resource.getResourceId().getPath(),
                            paramValueMap, request.getMethod());
                } else {
                    output = DSTools.accessResource(dataService, resourceName, paramValueMap,
                            request.getMethod());
                }

            } else {
                output = DSTools.invokeOperation(dataService, resourceName, paramValueMap);
            }
            if (output != null) {
                output.serialize(response.getWriter());
            } else {
                response.setStatus(HttpServletResponse.SC_ACCEPTED);
                response.getWriter().write("");
            }
        } catch (IOException e) {
            log.error("couldn't create Writer object from response", e);
        }
    } catch (AxisFault axisFault) {
        log.error("couldn't create Configuration Context", axisFault);
    } catch (DataServiceFault dataServiceFault) {
        log.error("error occurred when accessing DataService", dataServiceFault);
    } catch (XMLStreamException e) {
        log.error("Couldn't Serialize Output", e);
    } catch (IOException e) {
        log.error("Couldn't read the input stream", e);
    } finally {
        IOUtils.closeQuietly(bufferedReader);
    }

    //Handle Responses
    if (contextExist && statConfiguration.isStatsPublishingEnabled()) {
        try {
            interceptorOps.publishStatistics(request, requestTime, true);
        } catch (APIManagementException e) {
            log.error("Error occurred when publishing stats", e);
        }
    }

}