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:org.ednovo.gooru.controllers.v2.api.SessionRestV2Controller.java

@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_V2_SESSION_ADD })
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@RequestMapping(method = RequestMethod.POST, value = "/{id}/item")
public ModelAndView createSessionItem(@RequestBody String data, @PathVariable(ID) String sessionId,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setAttribute(PREDICATE, TAG_ADD_RESOURCE);
    User user = (User) request.getAttribute(Constants.USER);
    JSONObject json = requestData(data);
    final ActionResponseDTO<SessionItem> sessionItem = getSessionService().createSessionItem(
            this.buildSessionItemFromInputParameters(getValue(SESSION_ITEM, json)), sessionId);
    if (sessionItem.getErrors().getErrorCount() > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {//from   w  ww  .j  a  v a2s  .  c  o m
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    SessionContextSupport.putLogParameter(EVENT_NAME, "create-session-item");
    SessionContextSupport.putLogParameter(USER_ID, user.getUserId());
    SessionContextSupport.putLogParameter(GOORU_UID, user.getPartyUid());
    String[] includeFields = getValue(FIELDS, json) != null ? getFields(getValue(FIELDS, json)) : null;
    String includes[] = (String[]) ArrayUtils
            .addAll(includeFields == null ? SESSION_ITEM_INCLUDES : includeFields, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(sessionItem.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes);
}

From source file:org.apache.qpid.systest.rest.RestTestHelper.java

public void createNewGroupMember(String groupProviderName, String groupName, String memberName)
        throws IOException {
    createNewGroupMember(groupProviderName, groupName, memberName, HttpServletResponse.SC_CREATED);
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTResource.java

/**
 * The PUT service is used to create a new resource in the repository...
 *
 * @param req/*  w  ww .  ja v a  2 s.co m*/
 * @param resp
 * @throws ServiceException
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {

    HttpServletRequest mreq = restUtils.extractAttachments(runReportService, req);

    String resourceDescriptorXml = null;

    // get the resource descriptor...
    if (mreq instanceof MultipartHttpServletRequest) {
        resourceDescriptorXml = mreq.getParameter(restUtils.REQUEST_PARAMENTER_RD);
    } else {
        try {
            resourceDescriptorXml = IOUtils.toString(req.getInputStream());
        } catch (IOException ex) {
            throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
        }
    }

    if (resourceDescriptorXml == null) {
        restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Missing parameter "
                + restUtils.REQUEST_PARAMENTER_RD + " " + runReportService.getInputAttachments());
        return;
    }

    // Parse the resource descriptor...
    InputSource is = new InputSource(new StringReader(resourceDescriptorXml));
    Document doc = null;
    ResourceDescriptor rd = null;
    try {
        doc = XMLUtil.getNewDocumentBuilder().parse(is);
        rd = Unmarshaller.readResourceDescriptor(doc.getDocumentElement());
        if (log.isDebugEnabled()) {
            log.debug("resource descriptor was created successfully for: " + rd.getUriString());
        }

        // we force the rd to be new...
        rd.setIsNew(true);

        ResourceDescriptor createdRd = resourcesManagementRemoteService.putResource(rd);

        Marshaller m = new Marshaller();
        String xml = m.writeResourceDescriptor(createdRd);
        // send the xml...
        restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, "");

    } catch (SAXException ex) {
        log.error("Unexpected error during resource descriptor marshaling: " + ex.getMessage(), ex);
        restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Invalid resource descriptor");
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        log.error("Unexpected error during resource save: " + ex.getMessage(), ex);
        throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
    }

}

From source file:com.imaginary.home.controller.CloudService.java

private void authenticate() throws ControllerException, CommunicationException {
    HttpClient client = getClient(endpoint, proxyHost, proxyPort);
    HttpPut method = new HttpPut(endpoint + "/token");
    long timestamp = System.currentTimeMillis();

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

    String stringToSign = "PUT:/token:" + serviceId + ":" + timestamp + ":" + VERSION;

    try {//  w w w .  j ava2s .c o m
        method.addHeader("x-imaginary-signature", sign(apiKeySecret.getBytes("utf-8"), stringToSign));
    } catch (Exception e) {
        throw new ControllerException(e);
    }
    HttpResponse response;

    try {
        response = client.execute(method);
    } catch (IOException e) {
        throw new CommunicationException(e);
    }
    if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_CREATED) {
        HttpEntity entity = response.getEntity();

        if (entity == null) {
            throw new CommunicationException(response.getStatusLine().getStatusCode(),
                    "An error was returned without explanation");
        }
        String json;

        try {
            json = EntityUtils.toString(entity);
        } catch (IOException e) {
            throw new ControllerException(e);
        }
        try {
            JSONObject ob = new JSONObject(json);

            if (ob.has("token") && !ob.isNull("token")) {
                token = ob.getString("token");
            } else {
                throw new CommunicationException("No token was provided in a successful authentication");
            }
        } catch (JSONException e) {
            throw new CommunicationException(e);
        }
    } else {
        parseError(response);
    }
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Returns the created header for the sent data*/
public Properties upload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender,
        Partner receiver) throws Exception {
    NumberFormat formatter = new DecimalFormat("0.00");
    AS2Info as2Info = message.getAS2Info();
    MessageAccessDB messageAccess = null;
    MDNAccessDB mdnAccess = null;/*from www .ja  va 2  s . c  o m*/
    if (this.runtimeConnection != null && messageAccess == null && !as2Info.isMDN()) {
        messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
        messageAccess.initializeOrUpdateMessage((AS2MessageInfo) as2Info);
    } else if (this.runtimeConnection != null && as2Info.isMDN()) {
        mdnAccess = new MDNAccessDB(this.configConnection, this.runtimeConnection);
        mdnAccess.initializeOrUpdateMDN((AS2MDNInfo) as2Info);
    }
    if (this.clientserver != null) {
        this.clientserver.broadcastToClients(new RefreshClientMessageOverviewList());
    }
    long startTime = System.currentTimeMillis();
    //sets the global requestHeader
    int returnCode = this.performUpload(connectionParameter, message, sender, receiver);
    long size = message.getRawDataSize();
    long transferTime = System.currentTimeMillis() - startTime;
    float bytePerSec = (float) ((float) size * 1000f / (float) transferTime);
    float kbPerSec = (float) (bytePerSec / 1024f);
    if (returnCode == HttpServletResponse.SC_OK) {
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("returncode.ok",
                            new Object[] { as2Info.getMessageId(), String.valueOf(returnCode),
                                    AS2Tools.getDataSizeDisplay(size), AS2Tools.getTimeDisplay(transferTime),
                                    formatter.format(kbPerSec), }),
                    as2Info);
        }
    } else if (returnCode == HttpServletResponse.SC_ACCEPTED || returnCode == HttpServletResponse.SC_CREATED
            || returnCode == HttpServletResponse.SC_NO_CONTENT
            || returnCode == HttpServletResponse.SC_RESET_CONTENT
            || returnCode == HttpServletResponse.SC_PARTIAL_CONTENT) {
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("returncode.accepted",
                            new Object[] { as2Info.getMessageId(), String.valueOf(returnCode),
                                    AS2Tools.getDataSizeDisplay(size), AS2Tools.getTimeDisplay(transferTime),
                                    formatter.format(kbPerSec), }),
                    as2Info);
        }
    } else {
        //the system was unable to connect the partner
        if (returnCode < 0) {
            throw new NoConnectionException(
                    this.rb.getResourceString("error.noconnection", as2Info.getMessageId()));
        }
        if (this.runtimeConnection != null) {
            if (messageAccess == null) {
                messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            }
            messageAccess.setMessageState(as2Info.getMessageId(), AS2Message.STATE_STOPPED);
        }
        throw new Exception(as2Info.getMessageId() + ": HTTP " + returnCode);
    }
    if (this.configConnection != null) {
        //inc the sent data size, this is for new connections (as2 messages, async mdn)
        AS2Server.incRawSentData(size);
        if (message.getAS2Info().isMDN()) {
            AS2MDNInfo mdnInfo = (AS2MDNInfo) message.getAS2Info();
            //ASYNC MDN sent: insert an entry into the statistic table
            QuotaAccessDB.incReceivedMessages(this.configConnection, this.runtimeConnection,
                    mdnInfo.getSenderId(), mdnInfo.getReceiverId(), mdnInfo.getState(),
                    mdnInfo.getRelatedMessageId());
        }
    }
    if (this.configConnection != null) {
        MessageStoreHandler messageStoreHandler = new MessageStoreHandler(this.configConnection,
                this.runtimeConnection);
        messageStoreHandler.storeSentMessage(message, sender, receiver, this.requestHeader);
    }
    //inform the server of the result if a sync MDN has been requested
    if (!message.isMDN()) {
        AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
        if (messageInfo.requestsSyncMDN()) {
            //perform a check if the answer really contains a MDN or is just an empty HTTP 200 with some header data
            //this check looks for the existance of some key header values
            boolean as2FromExists = false;
            boolean as2ToExists = false;
            for (int i = 0; i < this.getResponseHeader().length; i++) {
                String key = this.getResponseHeader()[i].getName();
                if (key.toLowerCase().equals("as2-to")) {
                    as2ToExists = true;
                } else if (key.toLowerCase().equals("as2-from")) {
                    as2FromExists = true;
                }
            }
            if (!as2ToExists) {
                throw new Exception(this.rb.getResourceString("answer.no.sync.mdn",
                        new Object[] { as2Info.getMessageId(), "as2-to" }));
            }
            //send the data to the as2 server. It does not care if the MDN has been sync or async anymore
            GenericClient client = new GenericClient();
            CommandObjectIncomingMessage commandObject = new CommandObjectIncomingMessage();
            //create temporary file to store the data
            File tempFile = AS2Tools.createTempFile("SYNCMDN_received", ".bin");
            FileOutputStream outStream = new FileOutputStream(tempFile);
            ByteArrayInputStream memIn = new ByteArrayInputStream(this.responseData);
            this.copyStreams(memIn, outStream);
            memIn.close();
            outStream.flush();
            outStream.close();
            commandObject.setMessageDataFilename(tempFile.getAbsolutePath());
            for (int i = 0; i < this.getResponseHeader().length; i++) {
                String key = this.getResponseHeader()[i].getName();
                String value = this.getResponseHeader()[i].getValue();
                commandObject.addHeader(key.toLowerCase(), value);
                if (key.toLowerCase().equals("content-type")) {
                    commandObject.setContentType(value);
                }
            }
            //compatibility issue: some AS2 systems do not send a as2-from in the sync case, even if
            //this if _NOT_ RFC conform
            //see RFC 4130, section 6.2: The AS2-To and AS2-From header fields MUST be
            //present in all AS2 messages and AS2 MDNs whether asynchronous or synchronous in nature,
            //except for asynchronous MDNs, which are sent using SMTP.
            if (!as2FromExists) {
                commandObject.addHeader("as2-from",
                        AS2Message.escapeFromToHeader(receiver.getAS2Identification()));
            }
            ErrorObject errorObject = client.send(commandObject);
            if (errorObject.getErrors() > 0) {
                messageAccess.setMessageState(as2Info.getMessageId(), AS2Message.STATE_STOPPED);
            }
            tempFile.delete();
        }
    }
    return (this.requestHeader);
}

From source file:com.sun.syndication.propono.atom.server.AtomServlet.java

/**
 * Handles an Atom POST by calling handler to identify URI, reading/parsing
 * data, calling handler and writing results to response.
 *//*from   w ww .ja v  a 2s  .  c  om*/
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.debug("Entering");
    AtomHandler handler = createAtomRequestHandler(req, res);
    String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isCollectionURI(areq)) {

                if (req.getContentType().startsWith("application/atom+xml")) {

                    // parse incoming entry
                    Entry entry = Atom10Parser.parseEntry(
                            new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null);

                    // call handler to post it
                    Entry newEntry = handler.postEntry(areq, entry);

                    // set Location and Content-Location headers                        
                    for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("edit".equals(link.getRel())) {
                            res.addHeader("Location", link.getHrefResolved());
                            break;
                        }
                    }
                    for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("alternate".equals(link.getRel())) {
                            res.addHeader("Content-Location", link.getHrefResolved());
                            break;
                        }
                    }

                    // write entry back out to response
                    res.setStatus(HttpServletResponse.SC_CREATED);
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(newEntry, writer);
                    writer.close();

                } else if (req.getContentType() != null) {

                    // get incoming title and slug from HTTP header
                    String title = areq.getHeader("Title");

                    // create new entry for resource, set title and type
                    Entry resource = new Entry();
                    resource.setTitle(title);
                    Content content = new Content();
                    content.setType(areq.getContentType());
                    resource.setContents(Collections.singletonList(content));

                    // hand input stream off to hander to post file
                    Entry newEntry = handler.postMedia(areq, resource);

                    // set Location and Content-Location headers
                    for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("edit".equals(link.getRel())) {
                            res.addHeader("Location", link.getHrefResolved());
                            break;
                        }
                    }
                    for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("alternate".equals(link.getRel())) {
                            res.addHeader("Content-Location", link.getHrefResolved());
                            break;
                        }
                    }

                    res.setStatus(HttpServletResponse.SC_CREATED);
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(newEntry, writer);
                    writer.close();

                } else {
                    res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                            "No content-type specified in request");
                }

            } else {
                res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid collection specified in request");
            }
        } catch (AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            log.debug("ERROR processing POST", ae);
        } catch (Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            log.debug("ERROR processing POST", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    log.debug("Exiting");
}

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

@RequestMapping(value = "/egf/billpaymentdetails", method = GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getBillAndPaymentDetails(final HttpServletResponse response, String billNo, String cityCode) {
    RestErrors restErrors;/*from w w  w  .  j  a  va  2s  .  c  o  m*/
    try {
        if (StringUtils.isEmpty(billNo)) {
            restErrors = new RestErrors();
            restErrors.setErrorCode(RestApiConstants.THIRD_PARTY_ERR_CODE_NO_BILLNO);
            restErrors.setErrorMessage(RestApiConstants.THIRD_PARTY_ERR_MSG_NO_BILLNO);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return JsonConvertor.convert(restErrors);
        }

        EgBillregister egBillregister = expenseBillService.getByBillnumber(billNo);
        if (egBillregister == null) {
            restErrors = new RestErrors();
            restErrors.setErrorCode(RestApiConstants.THIRD_PARTY_ERR_CODE_NOT_VALID_BILLNUMBER);
            restErrors.setErrorMessage(RestApiConstants.THIRD_PARTY_ERR_MSG_NOT_VALID_BILLNUMBER);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return JsonConvertor.convert(restErrors);
        }

        if (!egBillregister.getStatus().getCode().contentEquals("Approved")) {
            restErrors = new RestErrors();
            restErrors.setErrorCode(RestApiConstants.THIRD_PARTY_ERR_CODE_NO_BILL_STATUS);
            restErrors.setErrorMessage(RestApiConstants.THIRD_PARTY_ERR_MSG_NO_BILL_STATUS);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return JsonConvertor.convert(restErrors);
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
        List<BillPaymentDetails> billPaymetDetails = billService.getBillAndPaymentDetails(billNo);
        if (billPaymetDetails.isEmpty()) {
            restErrors = new RestErrors();
            restErrors.setErrorCode(RestApiConstants.THIRD_PARTY_ERR_CODE_NO_DATA_FOUND);
            restErrors.setErrorMessage(RestApiConstants.THIRD_PARTY_ERR_MESSAGE_NO_DATA_FOUND);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return JsonConvertor.convert(restErrors);
        } else {
            return JsonConvertor.convert(billPaymetDetails);
        }

    } catch (final Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return JsonConvertor.convert(StringUtils.EMPTY);
    }
}

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

private void setupLocation() throws Exception {
    if (apiKeyId == null) {
        setupUser();/*from ww w .  j  a  v a2  s . c  o  m*/
    }
    HashMap<String, Object> lstate = new HashMap<String, Object>();
    long key = (System.currentTimeMillis() % 100000);

    lstate.put("name", "My Home " + key);
    lstate.put("description", "Integration test location");
    lstate.put("timeZone", TimeZone.getDefault().getID());

    HttpClient client = getClient();

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

    method.addHeader("Content-Type", "application/json");
    method.addHeader("x-imaginary-version", VERSION);
    method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
    method.addHeader("x-imaginary-api-key", apiKeyId);
    method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"),
            "post:/location:" + apiKeyId + ":" + timestamp + ":" + VERSION));

    //noinspection deprecation
    method.setEntity(new StringEntity((new JSONObject(lstate)).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);

        locationId = (u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId") : null;
    } else {
        Assert.fail("Failed to create location (" + status.getStatusCode() + ": "
                + EntityUtils.toString(response.getEntity()));
    }
}

From source file:org.jahia.bin.DefaultPostAction.java

public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource,
        final JCRSessionWrapper session, final Map<String, List<String>> parameters, URLResolver urlResolver)
        throws Exception {
    JCRNodeWrapper newNode = null;/*from   w w  w  . j  a  v  a2 s.  c o  m*/
    String[] subPaths = Patterns.SLASH.split(urlResolver.getPath());
    String lastPath = subPaths[subPaths.length - 1];
    JCRNodeWrapper node = null;
    StringBuilder realPath = new StringBuilder();
    String startPath = "";
    int index = 0;
    for (String subPath : subPaths) {
        index++;
        if (StringUtils.isNotBlank(subPath) && !"*".equals(subPath) && index != subPaths.length) {
            realPath.append("/").append(subPath);
            try {
                session.getNode(JCRContentUtils.escapeNodePath(realPath.toString()));
                startPath = "";

            } catch (PathNotFoundException e) {
                if ("".equals(startPath)) {
                    startPath = realPath.substring(0, realPath.lastIndexOf("/"));
                }
            }
        }
    }
    startPath = "".equals(startPath) ? realPath.toString() : startPath;
    realPath = realPath.delete(0, realPath.length());
    index = 0;
    for (String subPath : subPaths) {
        index++;
        if (StringUtils.isNotBlank(subPath) && !"*".equals(subPath) && index != subPaths.length) {
            realPath.append("/").append(subPath);
            if (realPath.toString().contains(startPath)) {
                try {
                    node = session.getNode(JCRContentUtils.escapeNodePath(realPath.toString()));
                } catch (PathNotFoundException e) {
                    if (node != null) {
                        if (!node.isCheckedOut()) {
                            session.checkout(node);
                        }
                        String parentType = "jnt:contentList";
                        if (parameters.containsKey(Render.PARENT_TYPE)) {
                            parentType = parameters.get(Render.PARENT_TYPE).get(0);
                        }
                        node = node.addNode(subPath, parentType);
                    }
                }
            }
        }
    }
    if (node != null) {
        String nodeType = null;
        if (parameters.containsKey(Render.NODE_TYPE)) {
            nodeType = parameters.get(Render.NODE_TYPE).get(0);
        }
        if (StringUtils.isBlank(nodeType)) {
            //                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing nodeType Property");
            return ActionResult.BAD_REQUEST;
        }
        String nodeName = null;
        if (parameters.containsKey(Render.NODE_NAME)) {
            nodeName = parameters.get(Render.NODE_NAME).get(0);
        }
        boolean forceCreation = false;
        if (!"*".equals(lastPath)) {
            nodeName = lastPath;
        } else {
            forceCreation = true;
        }
        try {
            newNode = createNode(req, parameters, node, nodeType, nodeName, forceCreation);
            final FileUpload fileUpload = (FileUpload) req.getAttribute(FileUpload.FILEUPLOAD_ATTRIBUTE);
            if (fileUpload != null && fileUpload.getFileItems() != null
                    && fileUpload.getFileItems().size() > 0) {
                final Map<String, DiskFileItem> stringDiskFileItemMap = fileUpload.getFileItems();
                for (Map.Entry<String, DiskFileItem> itemEntry : stringDiskFileItemMap.entrySet()) {
                    newNode.uploadFile(itemEntry.getValue().getName(), itemEntry.getValue().getInputStream(),
                            JCRContentUtils.getMimeType(itemEntry.getValue().getName(),
                                    itemEntry.getValue().getContentType()));
                }
            }

            session.save();
        } catch (CompositeConstraintViolationException e) {
            List<JSONObject> jsonErrors = new ArrayList<JSONObject>();
            for (ConstraintViolationException exception : e.getErrors()) {
                jsonErrors.add(getJSONConstraintError(exception));
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("validationError", jsonErrors);
            return new ActionResult(HttpServletResponse.SC_BAD_REQUEST, null, jsonObject);
        } catch (ConstraintViolationException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("validationError", Arrays.asList(getJSONConstraintError(e)));
            return new ActionResult(HttpServletResponse.SC_BAD_REQUEST, null, jsonObject);
        }

        final String nodeId = newNode.getIdentifier();
        if (parameters.containsKey(Render.AUTO_ASSIGN_ROLE)
                && !JahiaUserManagerService.isGuest(session.getUser())) {
            JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(session.getUser(),
                    session.getWorkspace().getName(), null, new JCRCallback<Object>() {
                        public Object doInJCR(JCRSessionWrapper rootSession) throws RepositoryException {
                            JCRNodeWrapper createdNode = rootSession.getNodeByUUID(nodeId);
                            List<String> roles = parameters.get(Render.AUTO_ASSIGN_ROLE);
                            createdNode.grantRoles("u:" + session.getUser().getName(),
                                    new HashSet<String>(roles));
                            rootSession.save();
                            return null;
                        }
                    });
        }

        if (parameters.containsKey(Render.AUTO_CHECKIN)
                && (parameters.get(Render.AUTO_CHECKIN)).get(0).length() > 0) {
            newNode.checkpoint();
        }
    }

    String sessionID = "";
    HttpSession httpSession = req.getSession(false);
    if (httpSession != null) {
        sessionID = httpSession.getId();
    }
    String nodeIdentifier = null;
    if (newNode != null) {
        nodeIdentifier = newNode.getIdentifier();
    }
    if (loggingService.isEnabled()) {
        loggingService.logContentEvent(renderContext.getUser().getName(), req.getRemoteAddr(), sessionID,
                nodeIdentifier, urlResolver.getPath(), parameters.get(Render.NODE_TYPE).get(0), "nodeCreated",
                new JSONObject(parameters).toString());
    }

    if (newNode != null) {
        return new ActionResult(HttpServletResponse.SC_CREATED, newNode.getPath(),
                Render.serializeNodeToJSON(newNode));
    } else {
        return null;
    }
}

From source file:org.openo.auth.common.CommonMockUp.java

public void mockUserClient() {

    new MockUp<UserServiceClient>() {

        @Mock/* w w w  .j a v  a  2 s.co m*/
        public ClientResponse createUser(String json, String authToken) {
            ClientResponse resp = new ClientResponse();
            resp.setStatus(HttpServletResponse.SC_CREATED);
            resp.setBody("body");
            resp.setHeader("header");
            return resp;
        }

        @Mock
        public int assignRolesToUser(String authToken, String projectId, String userId, String roleId) {
            return HttpServletResponse.SC_OK;
        }

        @Mock
        public ClientResponse modifyUser(String userId, String json, String authToken) {
            ClientResponse resp = new ClientResponse();
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setBody("body");
            resp.setHeader("header");
            return resp;
        }

        @Mock
        public int deleteUser(String userId, String authToken) {
            return HttpServletResponse.SC_OK;
        }

        @Mock
        public ClientResponse getUserDetails(String authToken) {
            ClientResponse resp = new ClientResponse();
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setBody("body");
            resp.setHeader("header");
            return resp;
        }

        @Mock
        public ClientResponse getUserDetails(String userId, String authToken) {
            ClientResponse resp = new ClientResponse();
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setBody("body");
            resp.setHeader("header");
            return resp;
        }

        @Mock
        public int modifyPassword(String userId, String json, String authToken) {
            return HttpServletResponse.SC_OK;
        }
    };

}