Example usage for javax.servlet.http HttpServletResponse SC_CREATED

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

Introduction

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

Prototype

int SC_CREATED

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

Click Source Link

Document

Status code (201) indicating the request succeeded and created a new resource on the server.

Usage

From source file:com.rmn.qa.servlet.BmpServlet.java

/**
 * Starts a new BrowserMobProxy. Note that either recordHar must be set to true or some credentials are provided or
 * a proxy will not be created./*w  w w .  j a  va2s  .co  m*/
 *
 * Content should be a json object in the following form.
 * 
 * <pre>
{
  "uuid": "my-uuid",//required
  "recordHar" : "true",
  "credentials": [{
    "domain" : "",
    "username" : "",
    "password" : "",
  }]
}
 * </pre>
 * 
 * @return Responds with a 201 Created and the url ins the Location header if proxy is created.
 * 
 * @return Responds with a 400 Bad Request if the uuid is not specified or there is no reason to create the proxy
 *         (see above).
 * 
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // if (request.getContentType().equals("application/json"))
    try {
        JsonNode input = getNodeFromRequest(request);
        String uuid = getJsonString(input, "uuid");
        if (StringUtils.isBlank(uuid)) {
            log.error("uuid not  present");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "uuid must be specified in json");
            return;
        }

        JsonNode harRecording = input.get("recordHar");
        boolean recorrdingHar = harRecording != null && harRecording.asBoolean(false);
        BrowserMobProxy proxy = null;
        if (recorrdingHar) {
            proxy = new BrowserMobProxyServer();
            Set<CaptureType> set = new HashSet<CaptureType>(CaptureType.getRequestCaptureTypes());
            set.addAll(CaptureType.getResponseCaptureTypes());
            set.removeAll(CaptureType.getBinaryContentCaptureTypes());
            proxy.setHarCaptureTypes(set);
        }
        JsonNode creds = input.get("credentials");
        if (creds != null) {
            if (proxy == null) {
                proxy = new BrowserMobProxyServer();
            }
            if (creds.isArray()) {
                ArrayNode array = (ArrayNode) creds;
                Iterator<JsonNode> elements = array.elements();
                while (elements.hasNext()) {
                    JsonNode cred = elements.next();
                    addCredentials(proxy, cred);
                }
            } else {
                addCredentials(proxy, creds);
            }
        }
        if (proxy == null) {
            log.error("Nothing for proxy to do");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Har recording or credentials not specified. There is no reason to start a proxy.");
            return;
        } else {
            String localhostname;
            // Try and get the IP address from the system property
            String runTimeHostName = System.getProperty(AutomationConstants.IP_ADDRESS);
            try {
                if (runTimeHostName == null) {
                    log.warn("Host name could not be determined from system property.");
                }
                localhostname = (runTimeHostName != null) ? runTimeHostName
                        : InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                log.error("Error parsing out host name", e);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Host name could not be determined: " + e);
                return;
            }

            // build the response
            BmpProxyRegistry.getInstance().addProxy(uuid, proxy);
            proxy.start();
            response.setStatus(HttpServletResponse.SC_CREATED);
            response.setHeader("Location", localhostname + ":" + proxy.getPort());
        }
    } catch (Exception e) {
        log.error("Error starting proxy: " + e, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error starting proxy: " + e);
    }
}

From source file:biz.taoconsulting.dominodav.methods.PUT.java

/**
 * (non-Javadoc)/*from   w  ww.j  av a2  s. co m*/
 * 
 * @see biz.taoconsulting.dominodav.methods.AbstractDAVMethod#action()
 */
public void action() throws Exception {
    IDAVRepository rep = this.getRepository();

    // uri is the unique identifier on the host includes servlet and
    // repository but not server
    String curURI = (String) this.getHeaderValues().get("uri");
    IDAVResource resource = null;
    InputStream instream = null;
    OutputStream out = null;
    boolean success = true;
    String relockToken = this.getRelockToken(this.getReq());
    LockManager lm = this.getLockManager();
    Long TimeOutValue = this.getTimeOutValue(this.getReq());
    // String lockrequestorName =
    // this.getOwnerFromXMLLockRequest(this.getReq());
    int status = HttpServletResponse.SC_OK; // We presume success
    LockInfo li = null;
    try {
        curURI = java.net.URLDecoder.decode(curURI, "UTF-8");
    } catch (Exception e) {
    }

    try {
        // LOGGER.info("getResource");
        resource = rep.getResource(curURI, true);

    } catch (DAVNotFoundException e) {
        // This exception isn't a problem since we just can create the new
        // URL
        // LOGGER.info("Exception not found resource");

    }
    if (resource == null) {
        // LOGGER.info("Resource Null start create new resource");
        resource = rep.createNewResource(curURI);
        // isNew=true;
    }
    if (resource == null) {
        // LOGGER.info("Error, resource is null");
        // Set the return error
        // Unprocessable Entity (see
        // http://www.webdav.org/specs/rfc2518.html#status.code.extensions.to.http11)
        this.setHTTPStatus(422);
    } else {
        if (relockToken != null) {
            li = lm.relock(resource, relockToken, TimeOutValue);
            if (li == null) {
                String eString = "Relock failed for " + relockToken;
                LOGGER.debug(eString);
                this.setErrorMessage(eString, 412); // Precondition failed
                status = 412;
            } else {
                LOGGER.debug("successful relock for " + relockToken + ", new Token:" + li.getToken());
                status = HttpServletResponse.SC_OK;
            }
        }
        if (status >= 400) {
            this.setHTTPStatus(status);
            HttpServletResponse resp = this.getResp();
            resp.setStatus(status);
            return;
        }
        try {
            instream = this.getReq().getInputStream();
            out = resource.getOutputStream();
        } catch (Exception e) {
            LOGGER.error("Input/Output stream creation failed", e);
            success = false;
            this.setErrorMessage("Input/Output stream creation failed in PUT for " + curURI, 501);
        }
        if (success) {
            try {
                int read = 0;
                byte[] bytes = new byte[2 * 2048]; // TODO: are 2 KB blocks
                // the right size?
                while ((read = instream.read(bytes)) != -1) {
                    // LOGGER.info("Read total"+ new
                    // Integer(read).toString() +" bytes");
                    out.write(bytes, 0, read);
                    // LOGGER.info("Write  total"+ new
                    // Integer(read).toString() +" bytes");
                }

            } catch (Exception ex) {
                LOGGER.error(ex);
            } finally {
                try {
                    if (instream != null) {
                        instream.close();
                        // LOGGER.info("istream successfully closed");
                    }
                } catch (Exception finalE) {
                    // Not a fatal error
                    LOGGER.error("Put stream closing failed", finalE);
                }

                try {
                    if (out != null) {
                        // LOGGER.info("out closed");
                        out.flush();
                        // LOGGER.info("Output stream flushed");
                        out.close();
                        // LOGGER.info("Output stream closed");
                    }
                } catch (Exception outE) {
                    // Success is false!
                    LOGGER.error("closing of output stream (and saving) failed", outE);
                    this.setErrorMessage("closing of output stream (and saving) failed for" + curURI, 501);
                    success = false;
                }
            }
        }
    }
    if (this.getReq().getContentLength() == 0) {
        this.setHTTPStatus(HttpServletResponse.SC_CREATED);
        HttpServletResponse resp = this.getResp();
        resp.setStatus(HttpServletResponse.SC_CREATED);
        return;
    }
    this.setHTTPStatus(HttpServletResponse.SC_OK);
    HttpServletResponse resp = this.getResp();
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:org.egov.restapi.web.rest.CreateBillController.java

/**
 * API to create works contractor bill.//  www.j a  va 2  s  .  c  om
 *
 * @param egBillregister
 * @param request
 * @return successMessage and billnumber - server response in JSON format
 */

@RequestMapping(value = "/egf/bill", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public String createContractorBill(@RequestBody final String requestJson, final HttpServletResponse response) {
    if (LOG.isDebugEnabled())
        LOG.debug("Rest API creating bill with the data: " + requestJson);
    String responseJson;
    EgBillregister egBillregister;
    EgBillregister savedBillregister;
    ApplicationThreadLocals.setUserId(2L);
    BillRegister billRegister = null;
    final JsonObject jsonObject = new JsonObject();
    try {
        billRegister = (BillRegister) getObjectFromJSONRequest(requestJson, BillRegister.class);
    } catch (final IOException e) {
        LOG.error(e.getStackTrace());
        final List<RestErrors> errorList = new ArrayList<>(0);
        final RestErrors re = new RestErrors();
        re.setErrorCode(e.getMessage());
        re.setErrorMessage(e.getMessage());
        errorList.add(re);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return JsonConvertor.convert(errorList);
    }
    try {
        final List<RestErrors> errors = billService.validateBillRegister(billRegister);
        if (!errors.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return JsonConvertor.convert(errors);
        } else {
            egBillregister = new EgBillregister();
            billService.createProjectCode(billRegister);
            billService.populateBillRegister(egBillregister, billRegister);
            savedBillregister = billService.createBill(egBillregister);
            responseJson = savedBillregister.getBillnumber();
        }
    } catch (final ValidationException e) {
        LOG.error(e.getStackTrace());
        final List<RestErrors> errorList = new ArrayList<>(0);

        final List<ValidationError> errors = e.getErrors();
        for (final ValidationError ve : errors) {
            final RestErrors re = new RestErrors();
            re.setErrorCode(ve.getKey());
            re.setErrorMessage(ve.getMessage());
            errorList.add(re);
        }
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return JsonConvertor.convert(errorList);
    } catch (final Exception e) {
        LOG.error(e.getStackTrace());
        final List<RestErrors> errorList = new ArrayList<>(0);
        final RestErrors re = new RestErrors();
        re.setErrorCode(e.getMessage());
        re.setErrorMessage(e.getMessage());
        errorList.add(re);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return JsonConvertor.convert(errorList);
    }
    jsonObject.addProperty("successMessage", "Works Bill created Successfully");
    jsonObject.addProperty("billNumber", responseJson);
    response.setStatus(HttpServletResponse.SC_CREATED);
    return jsonObject.toString();
}

From source file:uk.ac.edukapp.servlets.WidgetServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ///*  w w  w  .j a  va2s  . c om*/
    // POST always requires a valid user login
    //
    Useraccount userAccount = (Useraccount) SecurityUtils.getSubject().getPrincipal();
    if (userAccount == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    String body = IOUtils.toString(req.getInputStream());
    if (body == null || body.trim().length() == 0) {
        resp.sendError(400, "no tag specified");
        return;
    }

    Message message = new Message();

    String part = req.getParameter("part");

    //
    // Get widget resource
    //
    Widgetprofile widgetProfile = getWidgetProfile(req);
    if (widgetProfile == null)
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);

    OutputStream out = resp.getOutputStream();

    WidgetProfileService widgetProfileService = new WidgetProfileService(getServletContext());

    if (part.equals("tag")) {
        message = widgetProfileService.addTag(widgetProfile, body);
        //
        // log this tagging to UserActivity table
        //
        addUserActivity("tagged", widgetProfile.getId());
    } else if (part.equals("comment")) {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readTree(body);
        String userId = json.findValue("userId").asText();
        String text = json.findValue("comment").asText();

        //
        // Check that the current logged in user is the same principal as
        // the comment owner
        //
        if (userAccount.getId() == Integer.parseInt(userId)) {

            // TODO Map the JSON onto an actual Comment bean or DTO

            UserReviewService userReviewService = new UserReviewService(getServletContext());

            if (userReviewService.publishUserReview(text, userAccount, widgetProfile)) {
                message.setMessage("OK");
                resp.setStatus(HttpServletResponse.SC_CREATED);
                //
                // log this review to UserActivity table
                //
                addUserActivity("commented", widgetProfile.getId());
            } else {
                message.setMessage("Problem saving review");
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            message.setMessage("You are not authorized to create a review");
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }

    } else if (part.equals("activity")) {

        WidgetProfileService widgetService = new WidgetProfileService(getServletContext());

        if (widgetService.addActivity(widgetProfile, body)) {
            message.setMessage("OK");
            resp.setStatus(HttpServletResponse.SC_CREATED);
            //
            // log this activity-binding UserActivity table
            //
            addUserActivity("bindactivity", widgetProfile.getId());
        } else {
            message.setMessage("Problem saving activity");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        }
    } else if (part.equals("rating")) {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readTree(body);
        String userId = json.findValue("userId").asText();
        String rating = json.findValue("rating").asText();

        System.out.println("userid = " + userId);
        System.out.println("rating = " + rating);

        if (userId == null || rating == null) {
            message.setMessage("parameters missing");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

        UserRateService userRateService = new UserRateService(getServletContext());

        message = userRateService.publishUserRate(rating, userAccount, widgetProfile);
        if (message.getMessage().equals("OK")) {
            //
            // log this rating to UserActivity table
            //
            addUserActivity("rated", widgetProfile.getId());
            resp.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

    }

    MetadataRenderer.render(out, message);
    out.flush();
    out.close();
}

From source file:com.imaginary.home.cloud.CloudTest.java

private void setupUser() throws Exception {
    HashMap<String, Object> user = new HashMap<String, Object>();
    long key = (System.currentTimeMillis() % 100000);

    user.put("firstName", "Test " + key);
    user.put("lastName", "User");
    user.put("email", "test" + key + "@example.com");
    user.put("password", "ABC" + random.nextInt(1000000));

    HttpClient client = getClient();//from  ww w  .j a v a 2s . com

    HttpPost method = new HttpPost(cloudAPI + "/user");
    long timestamp = System.currentTimeMillis();

    method.addHeader("Content-Type", "application/json");
    method.addHeader("x-imaginary-version", VERSION);
    method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));

    //noinspection deprecation
    method.setEntity(new StringEntity((new JSONObject(user)).toString(), "application/json", "UTF-8"));

    HttpResponse response;
    StatusLine status;

    try {
        response = client.execute(method);
        status = response.getStatusLine();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CommunicationException(e);
    }
    if (status.getStatusCode() == HttpServletResponse.SC_CREATED) {
        String json = EntityUtils.toString(response.getEntity());
        JSONObject u = new JSONObject(json);

        JSONObject keys = (u.has("apiKeys") && !u.isNull("apiKeys")) ? u.getJSONObject("apiKeys") : null;

        if (keys != null) {
            CloudTest.apiKeyId = (keys.has("apiKeyId") && !keys.isNull("apiKeyId")) ? keys.getString("apiKeyId")
                    : null;
            CloudTest.apiKeySecret = (keys.has("apiKeySecret") && !keys.isNull("apiKeySecret"))
                    ? keys.getString("apiKeySecret")
                    : null;
        }
    } else {
        Assert.fail("Failed to create user (" + status.getStatusCode() + ": "
                + EntityUtils.toString(response.getEntity()));
    }
}

From source file:org.iavante.sling.gad.administration.impl.UploadOperations.java

/**
 * Creates a new source./*from   w w w  .j  a v  a2s  .  co m*/
 * 
 * @param request
 * @return Location header attribute
 * @throws IOException
 */
public String createSourceInCore(HttpServletRequest request, String resourceType) throws IOException {

    init();

    String location = null;

    if (log.isInfoEnabled())
        log.info("createSource, ini");

    Enumeration en2 = request.getParameterNames();
    while (en2.hasMoreElements()) {
        String cad = (String) en2.nextElement();
        if ("data".compareTo(cad) != 0) {
            if (log.isInfoEnabled())
                log.info("createSource, Param: " + cad + ", value: " + request.getParameter(cad));
        } else {
            if (log.isInfoEnabled())
                log.info("createSource, Param: " + cad);
        }
    }

    // Getting parameters
    String sourcename = request.getParameter("sourcename");
    if (sourcename == null) {
        throw new IOException("No <filename> param found in request");
    }
    String content = request.getParameter("content");
    if (content == null) {
        throw new IOException("No <content> param found in request");
    }

    // If 'content' ends with '/*' then check if exists, else create
    if (!content.endsWith("/*")) {
        // Setting GET
        Credentials creds = new UsernamePasswordCredentials(adminUser, adminPasswd);
        String getUrl = HTTP_BASE_URL + content;
        if (log.isInfoEnabled())
            log.info("createSource, getUrl: " + getUrl);
        assertAuthenticatedHttpStatus(creds, getUrl, 200, null);
        location = content;
        if (log.isInfoEnabled())
            log.info("createSource, source already exists");

    } else { // 'create'

        // Setting POST
        Credentials creds = new UsernamePasswordCredentials(adminUser, adminPasswd);
        String postUrl = HTTP_BASE_URL + content;
        if (log.isInfoEnabled())
            log.info("createSource, postUrl: " + postUrl);
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new NameValuePair("title", sourcename));
        postParams.add(new NameValuePair("sling:resourceType", resourceType));
        postParams.add(new NameValuePair("file", ""));
        postParams.add(new NameValuePair("mimetype", ""));
        postParams.add(new NameValuePair("jcr:lastModifiedBy", ""));
        postParams.add(new NameValuePair("jcr:lastModified", ""));

        List<String> oksCodes = new ArrayList<String>();
        oksCodes.add("" + HttpServletResponse.SC_CREATED);
        oksCodes.add("" + HttpServletResponse.SC_OK);

        Header[] headers = assertAuthenticatedPostStatus(creds, postUrl, oksCodes, postParams, null);

        if (headers != null) {
            boolean seguir = true;
            int i = 0;
            while (seguir && i < headers.length) {
                Header header = headers[i];
                if ("Location".compareTo(header.getName()) == 0) {
                    location = header.getValue();
                    if (!location.startsWith(baseRepoDir)) {
                        location = "/" + baseRepoDir + location;
                    }
                    seguir = false;
                    if (log.isInfoEnabled())
                        log.info("createSource, header Location:" + location);
                } else {
                    i++;
                }
            }
            if (seguir) {
                if (log.isInfoEnabled())
                    log.info("createSource, header Location: NOT FOUND (null)");
            }
        }
    }

    if (log.isInfoEnabled())
        log.info("createSource, end");
    return location;

}

From source file:org.ednovo.gooru.controllers.v2.api.UserRestV2Controller.java

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_USER_ADD })
@RequestMapping(method = { RequestMethod.POST }, value = "")
public ModelAndView createUser(final HttpServletRequest request, @RequestBody final String data,
        @RequestParam(value = SESSIONTOKEN, required = false) final String sessionToken,
        @RequestParam(value = SHARED_SECRETKEY, required = false) final String sharedSecretKey,
        @RequestParam(value = ORG_ADMIN, required = false, defaultValue = "false") final Boolean orgAdmin,
        @RequestParam(value = ADMIN_ORGANIZATION_UID, required = false) final String adminOrganizationUid,
        final HttpServletResponse response) throws Exception {
    final JSONObject json = requestData(data);
    final User creator = this.buildUserFromInputParameters((getValue(USER, json)));
    final String sessionId = request.getSession().getId();

    String dateOfBirth = getValue(DATEOFBIRTH, json);
    final User apiCaller = (User) request.getAttribute(Constants.USER);
    if (getValue(CHILDFLAG, json) != null ? Boolean.parseBoolean(getValue(CHILDFLAG, json)) : false) {
        dateOfBirth = dateOfBirth != null ? dateOfBirth.replace("d", "/") : dateOfBirth;
    }//from www  .jav a2 s .com

    // Check user organization permission
    if (creator.getOrganization() != null && creator.getOrganization().getOrganizationCode() != null
            && apiCaller != null && !creator.getOrganization().getOrganizationCode().equalsIgnoreCase(GOORU)) {
        this.getUserManagementService()
                .validateUserOrganization(creator.getOrganization().getOrganizationCode(), sharedSecretKey);
    }

    final User user = this.getUserManagementService().createUserWithValidation(creator,
            getValue(PASSWORD, json), null,
            getValue(CONFIRM_STATUS, json) != null ? Integer.parseInt(getValue(CONFIRM_STATUS, json)) : null,
            getValue(USEGENERATEDPASSWORD, json) != null
                    ? Boolean.parseBoolean(getValue(USEGENERATEDPASSWORD, json))
                    : false,
            getValue(SENDCONFIRMATIONMAIL, json) != null
                    ? Boolean.parseBoolean(getValue(SENDCONFIRMATIONMAIL, json))
                    : true,
            apiCaller, getValue(ACCOUNTTYPE, json), dateOfBirth, getValue(USERPARENTID, json), sessionId,
            getValue(GENDER, json), getValue(CHILDDOB, json), getValue(GOORU_BASE_URL, json),
            getValue(TOKEN, json) != null ? Boolean.parseBoolean(getValue(TOKEN, json)) : false, request,
            getValue(ROLE, json),
            getValue(MAIL_CONFIRMATION_URL, json) != null ? getValue(MAIL_CONFIRMATION_URL, json) : null);
    if (user != null) {
        if (orgAdmin && adminOrganizationUid != null) {
            this.getUserManagementService().updateOrgAdminCustomField(adminOrganizationUid, user);
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
        indexHandler.setReIndexRequest(user.getPartyUid(), IndexProcessor.INDEX, USER, null, false, false);
    }

    return toModelAndViewWithIoFilter(user, RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, USER_INCLUDES);
}

From source file:org.gss_project.gss.server.rest.GroupsHandler.java

/**
 * Handle POST requests in the groups namespace.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are processing
  * @throws IOException if an input/output error occurs
 *//* w w  w.jav a2s . c om*/
void postGroup(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Identify the requested resource path
    String path = getInnerPath(req, PATH_GROUPS);
    if (path.equals(""))
        path = "/";

    try {
        User user = getUser(req);
        final User owner = getOwner(req);
        if (!owner.equals(user))
            throw new InsufficientPermissionsException("User " + user.getUsername()
                    + " does not have permission to modify the groups owned by " + owner.getUsername());
        if (path.equals("/")) {
            // Request to add group
            final String group = req.getParameter(GROUP_PARAMETER);
            if (!isValidResourceName(group)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            if (logger.isDebugEnabled())
                logger.debug("Adding group " + group);
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().createGroup(owner.getId(), group);
                    return null;
                }
            });
            resp.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            // Request to add group member
            String username = req.getParameter(USERNAME_PARAMETER);
            if (!isValidResourceName(username)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            // Chop any trailing slash
            path = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
            // Chop any leading slash
            path = path.startsWith("/") ? path.substring(1) : path;
            if (logger.isDebugEnabled())
                logger.debug("Adding member " + username + " to group " + path);
            final Group group = getService().getGroup(owner.getId(), URLDecoder.decode(path, "UTF-8"));
            final User member = getService().findUser(username);
            if (member == null) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "User " + username + " not found");
                return;
            }
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().addUserToGroup(owner.getId(), group.getId(), member.getId());
                    return null;
                }
            });
            resp.setStatus(HttpServletResponse.SC_CREATED);
        }
        // Workaround for IE's broken caching behavior.
        resp.setHeader("Expires", "-1");
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
    } catch (Exception e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:org.dasein.cloud.aws.platform.CloudFrontMethod.java

CloudFrontResponse invoke(String... args) throws CloudFrontException, CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException("Context not specified for this request");
    }/*from w ww  .j a v  a  2  s .  com*/
    StringBuilder url = new StringBuilder();
    String dateString = getDate();
    HttpRequestBase method;
    HttpClient client;

    url.append(CLOUD_FRONT_URL + "/" + CF_VERSION + "/distribution");
    if (args != null && args.length > 0) {
        for (String arg : args) {
            url.append("/");
            url.append(arg);
        }
    }
    method = action.getMethod(url.toString());
    method.addHeader(AWSCloud.P_AWS_DATE, dateString);
    try {
        String signature = provider.signCloudFront(new String(ctx.getAccessPublic(), "utf-8"),
                ctx.getAccessPrivate(), dateString);

        method.addHeader(AWSCloud.P_CFAUTH, signature);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            method.addHeader(entry.getKey(), entry.getValue());
        }
    }
    if (body != null) {
        try {
            ((HttpEntityEnclosingRequestBase) method)
                    .setEntity(new StringEntity(body, "application/xml", "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
    }
    attempts++;
    client = getClient(url.toString());
    CloudFrontResponse response = new CloudFrontResponse();

    HttpResponse httpResponse;
    int status;

    try {
        APITrace.trace(provider, action.toString());
        httpResponse = client.execute(method);
        status = httpResponse.getStatusLine().getStatusCode();

    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    Header header = httpResponse.getFirstHeader("ETag");

    if (header != null) {
        response.etag = header.getValue();
    } else {
        response.etag = null;
    }
    if (status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_CREATED
            || status == HttpServletResponse.SC_ACCEPTED) {
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            try {
                response.document = parseResponse(input);
                return response;
            } finally {
                input.close();
            }
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    } else if (status == HttpServletResponse.SC_NO_CONTENT) {
        return null;
    } else {
        if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE
                || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            if (attempts >= 5) {
                String msg;

                if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
                    msg = "Cloud service is currently unavailable.";
                } else {
                    msg = "The cloud service encountered a server error while processing your request.";
                }
                logger.error(msg);
                throw new CloudException(msg);
            } else {
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException ignore) {
                }
                return invoke(args);
            }
        }
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            Document doc;

            try {
                doc = parseResponse(input);
            } finally {
                input.close();
            }
            if (doc != null) {
                String code = null, message = null, requestId = null, type = null;
                NodeList blocks = doc.getElementsByTagName("Error");

                if (blocks.getLength() > 0) {
                    Node error = blocks.item(0);
                    NodeList attrs;

                    attrs = error.getChildNodes();
                    for (int i = 0; i < attrs.getLength(); i++) {
                        Node attr = attrs.item(i);

                        if (attr.getNodeName().equals("Code")) {
                            code = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Type")) {
                            type = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Message")) {
                            message = attr.getFirstChild().getNodeValue().trim();
                        }
                    }

                }
                blocks = doc.getElementsByTagName("RequestId");
                if (blocks.getLength() > 0) {
                    Node id = blocks.item(0);

                    requestId = id.getFirstChild().getNodeValue().trim();
                }
                if (message == null) {
                    throw new CloudException(
                            "Unable to identify error condition: " + status + "/" + requestId + "/" + code);
                }
                throw new CloudFrontException(status, requestId, type, code, message);
            }
            throw new CloudException("Unable to parse error.");
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    }
}

From source file:org.geosdi.geoplatform.gui.server.UploadServlet.java

@SuppressWarnings("unchecked")
@Override//www.  j  a v  a 2  s .c o m
public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException, GeoPlatformException {
    //        logger.info("Query String: " + req.getQueryString());
    //        while (req.getParameterMap().keySet().iterator().hasNext()) {
    //            logger.info("Parameter next: " + req.getParameterMap().keySet().iterator().next());
    //        }
    //        while (req.getParameterNames().hasMoreElements()) {
    //            logger.info("Parameter name: " + req.getParameterNames().nextElement());
    //        }
    //        while (req.getAttributeNames().hasMoreElements()) {
    //            logger.info("Attribute name: " + req.getAttributeNames().nextElement());
    //        }
    String workspace = null;
    HttpSession session = req.getSession();
    Object accountObj = session.getAttribute(SessionProperty.LOGGED_ACCOUNT.toString());
    GPAccount account;
    if (accountObj != null && accountObj instanceof GPAccount) {
        account = (GPAccount) accountObj;
    } else {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Session Timeout");
        return;
    }
    receivedAssertion = (AssertionImpl) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        /*
          * Set the size threshold, above which content will be stored on
          * disk.
          */
        factory.setSizeThreshold(1 * 1024 * 1024); //1 MB

        ServletFileUpload upload = new ServletFileUpload(factory);
        File uploadedFile = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    logger.debug("Analyzing item field name: " + item.getFieldName());
                    logger.debug("Analyzing item string: " + item.getString());
                    //Ricevo parametro
                    if (item.getFieldName().equals("workspace")) {
                        workspace = item.getString();
                        logger.debug("Found workspace in request param: " + workspace);
                    }
                } else {
                    String fileName = item.getName();
                    // get only the file name not whole path
                    if (fileName != null) {
                        fileName = FilenameUtils.getName(fileName);
                    }

                    try {
                        uploadedFile = this.publisherFileUtils.createFileWithUniqueName(fileName);
                        item.write(uploadedFile);
                    } catch (Exception ex) {
                        logger.info("ERRORE : " + ex);
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "An error occurred writing the file: " + ex.getMessage());
                        throw new GeoPlatformException("Error on uploading shape.");
                    }
                    resp.setStatus(HttpServletResponse.SC_CREATED);
                    resp.flushBuffer();
                }
            }
            List<InfoPreview> infoPreviews = this.manageUploadedFilePreview(uploadedFile, session.getId(),
                    account.getNaturalID(), workspace);
            resp.setContentType("text/x-json;charset=UTF-8");
            resp.setHeader("Cache-Control", "no-cache");
            String result = PublisherFileUtils.generateJSONObjects(infoPreviews);
            resp.getWriter().write(result);
            //geoPlatformPublishClient.publish("previews", "dataTest", infoPreview.getDataStoreName());
        } catch (FileUploadException ex) {
            logger.info("ERRORE : " + ex);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred creating the file: " + ex.getMessage());
            throw new GeoPlatformException("Error on uploading shape.");
        } finally {
            uploadedFile.delete();
            resp.getWriter().close();
        }
    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}