Example usage for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR

List of usage examples for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR.

Prototype

int SC_INTERNAL_SERVER_ERROR

To view the source code for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR.

Click Source Link

Document

<tt>500 Server Error</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:com.thoughtworks.go.server.service.ValueStreamMapServiceTest.java

@Test
public void shouldPopulateErrorCorrectly_VSMForMaterial() throws Exception {
    /*//from   ww w  .  ja va  2s . c o m
    git --> p1
     */

    String groupName = "g1";
    String pipelineName = "p1";
    String userName = "looser";
    GitMaterial gitMaterial = new GitMaterial("git");
    MaterialConfig gitConfig = gitMaterial.config();
    GitMaterialInstance gitMaterialInstance = new GitMaterialInstance("url", "branch", "submodule",
            "flyweight");
    PipelineConfigs groups = new BasicPipelineConfigs(groupName, new Authorization(),
            PipelineConfigMother.pipelineConfig(pipelineName, new MaterialConfigs(gitConfig)));
    CruiseConfig cruiseConfig = new BasicCruiseConfig(groups);
    when(goConfigService.currentCruiseConfig()).thenReturn(cruiseConfig);
    when(goConfigService.groups()).thenReturn(new PipelineGroups(groups));

    when(securityService.hasViewPermissionForGroup(userName, groupName)).thenReturn(false);

    // unknown material
    valueStreamMapService.getValueStreamMap("unknown-material", "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_NOT_FOUND, "MATERIAL_CONFIG_WITH_FINGERPRINT_NOT_FOUND");

    // unauthorized
    valueStreamMapService.getValueStreamMap(gitMaterial.getFingerprint(), "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_UNAUTHORIZED, "MATERIAL_CANNOT_VIEW");

    // material config exists but no material instance
    when(securityService.hasViewPermissionForGroup(userName, groupName)).thenReturn(true);
    when(materialRepository.findMaterialInstance(gitConfig)).thenReturn(null);

    valueStreamMapService.getValueStreamMap(gitMaterial.getFingerprint(), "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_NOT_FOUND, "MATERIAL_INSTANCE_WITH_FINGERPRINT_NOT_FOUND");

    // modification (revision) doesn't exist
    when(materialRepository.findMaterialInstance(gitConfig)).thenReturn(gitMaterialInstance);
    when(materialRepository.findModificationWithRevision(gitMaterial, "r1")).thenReturn(null);

    valueStreamMapService.getValueStreamMap(gitMaterial.getFingerprint(), "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_NOT_FOUND, "MATERIAL_MODIFICATION_NOT_FOUND");

    // internal error
    when(goConfigService.groups()).thenThrow(new RuntimeException("just for fun"));

    valueStreamMapService.getValueStreamMap(gitMaterial.getFingerprint(), "r1",
            new Username(new CaseInsensitiveString(userName)), result);

    assertResult(HttpStatus.SC_INTERNAL_SERVER_ERROR, "VSM_INTERNAL_SERVER_ERROR_FOR_MATERIAL");
}

From source file:org.alfresco.dropbox.webscripts.Node.java

protected List<NodeRef> parseNodeRefs(final WebScriptRequest req) {
    final List<NodeRef> result = new ArrayList<NodeRef>();
    Content content = req.getContent();/* w  ww .ja  v  a 2 s  . co m*/
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        jsonStr = content.getContent();

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        json = new JSONObject(jsonStr);

        if (!json.has(JSON_KEY_NODE_REFS)) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Key " + JSON_KEY_NODE_REFS + " is missing from JSON: " + jsonStr);
        }

        JSONArray nodeRefs = json.getJSONArray(JSON_KEY_NODE_REFS);

        for (int i = 0; i < nodeRefs.length(); i++) {
            NodeRef nodeRef = new NodeRef(nodeRefs.getString(i));
            result.add(nodeRef);
        }
    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                "Unable to retrieve nodeRefs from JSON '" + jsonStr + "'.", e);
    }

    return (result);
}

From source file:org.alfresco.integrations.google.docs.webscripts.AuthURL.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();//from   ww w .ja  v  a2 s  . c o m

    String nodeRef = req.getParameter(PARAM_NODEREF);

    Map<String, Object> model = new HashMap<String, Object>();

    boolean authenticated = false;

    try {
        if (!Boolean.valueOf(req.getParameter(PARAM_OVERRIDE))) {
            if (googledocsService.isAuthenticated()) {
                authenticated = true;
            } else {
                model.put(MODEL_AUTHURL, googledocsService.getAuthenticateUrl(req.getParameter(PARAM_STATE)));
            }

            log.debug("Authenticated: " + authenticated + "; AuthUrl: "
                    + ((model.containsKey(MODEL_AUTHURL)) ? model.get(MODEL_AUTHURL) : ""));
        } else {
            model.put(MODEL_AUTHURL, googledocsService.getAuthenticateUrl(req.getParameter(PARAM_STATE)));
            authenticated = googledocsService.isAuthenticated();
            log.debug("Forced AuthURL. AuthUrl: " + model.get(MODEL_AUTHURL) + "; Authenticated: "
                    + authenticated);
        }

        if (nodeRef != null && nodeRef.length() > 0) {
            List<GoogleDocsService.GooglePermission> permissions = googledocsService
                    .getGooglePermissions(new NodeRef(nodeRef), GoogleDocsModel.PROP_PERMISSIONS);
            model.put(MODEL_PERMISSIONS, permissions); // permissions may be null
        }
    } catch (IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage());
    }

    model.put(MODEL_AUTHENTICATED, authenticated);

    return model;
}

From source file:org.alfresco.integrations.google.docs.webscripts.CompleteAuth.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();/*  w  w  w .j  av a  2  s .  c  o  m*/

    Map<String, Object> model = new HashMap<String, Object>();

    boolean authenticated = false;

    if (req.getParameter(PARAM_ACCESS_TOKEN) != null) {
        try {
            authenticated = googledocsService.completeAuthentication(req.getParameter(PARAM_ACCESS_TOKEN));
        } catch (GoogleDocsServiceException gdse) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, gdse.getMessage());
        } catch (IOException ioe) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage());
        }
    }

    model.put(MODEL_AUTHENTICATED, authenticated);

    return model;
}

From source file:org.alfresco.integrations.google.docs.webscripts.CreateContent.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    // Set Service Beans
    this.getGoogleDocsServiceSubsystem();

    Map<String, Object> model = new HashMap<String, Object>();

    if (googledocsService.isEnabled()) {

        String contentType = req.getParameter(PARAM_TYPE);
        NodeRef parentNodeRef = new NodeRef(req.getParameter(PARAM_PARENT));

        log.debug("ContentType: " + contentType + "; Parent: " + parentNodeRef);

        NodeRef newNode = null;/*from  ww  w .  ja v  a  2s. co m*/
        File file = null;
        try {
            Credential credential = googledocsService.getCredential();
            if (contentType.equals(GoogleDocsConstants.DOCUMENT_TYPE)) {
                newNode = createFile(parentNodeRef, contentType, GoogleDocsConstants.MIMETYPE_DOCUMENT);
                file = googledocsService.createDocument(credential, newNode);
            } else if (contentType.equals(GoogleDocsConstants.SPREADSHEET_TYPE)) {
                newNode = createFile(parentNodeRef, contentType, GoogleDocsConstants.MIMETYPE_SPREADSHEET);
                file = googledocsService.createSpreadSheet(credential, newNode);
            } else if (contentType.equals(GoogleDocsConstants.PRESENTATION_TYPE)) {
                newNode = createFile(parentNodeRef, contentType, GoogleDocsConstants.MIMETYPE_PRESENTATION);
                file = googledocsService.createPresentation(credential, newNode);
            } else {
                throw new WebScriptException(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE, "Content Type Not Found.");
            }

            googledocsService.decorateNode(newNode, file, googledocsService.getLatestRevision(credential, file),
                    true);

        } catch (GoogleDocsServiceException gdse) {
            if (gdse.getPassedStatusCode() > -1) {
                throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
            } else {
                throw new WebScriptException(gdse.getMessage());
            }
        } catch (GoogleDocsTypeException gdte) {
            throw new WebScriptException(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE, gdte.getMessage());
        } catch (GoogleDocsAuthenticationException gdae) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
        } catch (GoogleDocsRefreshTokenException gdrte) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
        } catch (IOException ioe) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
        } catch (Exception e) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
        }

        googledocsService.lockNode(newNode);

        model.put(MODEL_NODEREF, newNode.toString());
        model.put(MODEL_EDITOR_URL, file.getAlternateLink());

    } else {
        throw new WebScriptException(HttpStatus.SC_SERVICE_UNAVAILABLE, "Google Docs Disabled");
    }

    return model;
}

From source file:org.alfresco.integrations.google.docs.webscripts.CreateContent.java

/**
 * Create a new content item for a document, spreadsheet or presentation which is to be edited in Google Docs
 *
 * <p>The name of the file is generated automatically, based on the type of content. In the event of a clash with
 * an existing file, the file name will have a numeric suffix placed on the end of it before the file extension,
 * which will be incremented until a valid name is found.</p>
 *
 * @param parentNodeRef NodeRef identifying the folder where the content will be created
 * @param contentType   The type of content to be created, one of 'document', 'spreadsheet' or 'presentation'
 * @param mimetype  The mimetype of the new content item, used to determine the file extension to add
 * @return  A FileInfo object representing the new content item. Call fileInfo.getNodeRef() to get the nodeRef
 *//*  ww  w . j  ava  2s .co m*/
private NodeRef createFile(final NodeRef parentNodeRef, final String contentType, final String mimetype) {
    String baseName = getNewFileName(contentType), fileExt = fileNameUtil.getExtension(mimetype);
    final StringBuffer sb = new StringBuffer(baseName);
    if (fileExt != null && !fileExt.equals("")) {
        sb.append(".").append(fileExt);
    }
    int i = 0, maxCount = 1000; // Limit the damage should something go horribly wrong and a FileExistsException is always thrown

    while (i <= maxCount) {
        List<String> parts = new ArrayList<String>(1);
        parts.add(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, sb.toString()).toPrefixString());
        try {
            if (fileFolderService.resolveNamePath(parentNodeRef, parts, false) == null) {
                return fileFolderService.create(parentNodeRef, sb.toString(), ContentModel.TYPE_CONTENT)
                        .getNodeRef();
            } else {
                log.debug("Filename " + sb.toString() + " already exists");
                String name = fileNameUtil.incrementFileName(sb.toString());
                sb.replace(0, sb.length(), name);
                if (log.isDebugEnabled())
                    log.debug("new file name " + sb.toString());
            }
        } catch (FileNotFoundException e) // We should never catch this because we set mustExist=false
        {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    "Unexpected FileNotFoundException", e);
        }
        i++;
    }
    throw new WebScriptException(HttpStatus.SC_CONFLICT,
            "Too many untitled files. Try renaming some existing documents.");
}

From source file:org.alfresco.integrations.google.docs.webscripts.DiscardContent.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();/*from w  w  w  .  j  a  va2  s .  c o m*/

    Map<String, Object> model = new HashMap<String, Object>();

    Map<String, Serializable> map = parseContent(req);
    final NodeRef nodeRef = (NodeRef) map.get(JSON_KEY_NODEREF);

    if (nodeService.hasAspect(nodeRef, GoogleDocsModel.ASPECT_EDITING_IN_GOOGLE)) {
        try {
            boolean deleted = false;

            if (!Boolean.valueOf(map.get(JSON_KEY_OVERRIDE).toString())) {
                SiteInfo siteInfo = siteService.getSite(nodeRef);
                if (siteInfo == null
                        || siteService.isMember(siteInfo.getShortName(), AuthenticationUtil.getRunAsUser())) {

                    if (googledocsService.hasConcurrentEditors(nodeRef)) {
                        throw new WebScriptException(HttpStatus.SC_CONFLICT,
                                "Node: " + nodeRef.toString() + " has concurrent editors.");
                    }
                } else {
                    throw new AccessDeniedException(
                            "Access Denied.  You do not have the appropriate permissions to perform this operation.");
                }
            }

            deleted = delete(nodeRef);

            model.put(MODEL_SUCCESS, deleted);

        } catch (InvalidNodeRefException ine) {
            throw new WebScriptException(HttpStatus.SC_NOT_FOUND, ine.getMessage());
        } catch (IOException ioe) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage());
        } catch (GoogleDocsAuthenticationException gdae) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
        } catch (GoogleDocsRefreshTokenException gdrte) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
        } catch (GoogleDocsServiceException gdse) {
            if (gdse.getPassedStatusCode() > -1) {
                throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
            } else {
                throw new WebScriptException(gdse.getMessage());
            }
        } catch (AccessDeniedException ade) {
            // This code will make changes after the rollback has occurred to clean up the node: remove the lock and the Google
            // Docs aspect. If it has the temporary aspect it will also remove the node from Alfresco
            AlfrescoTransactionSupport.bindListener(new TransactionListenerAdapter() {
                public void afterRollback() {
                    transactionService.getRetryingTransactionHelper()
                            .doInTransaction(new RetryingTransactionCallback<Object>() {
                                public Object execute() throws Throwable {
                                    DriveFile driveFile = googledocsService.getDriveFile(nodeRef);
                                    googledocsService.unlockNode(nodeRef);
                                    boolean deleted = googledocsService.deleteContent(nodeRef, driveFile);

                                    if (deleted) {
                                        AuthenticationUtil
                                                .runAsSystem(new AuthenticationUtil.RunAsWork<Object>() {
                                                    public Object doWork() throws Exception {
                                                        if (nodeService.hasAspect(nodeRef,
                                                                ContentModel.ASPECT_TEMPORARY)) {
                                                            nodeService.deleteNode(nodeRef);
                                                        }

                                                        return null;
                                                    }
                                                });
                                    }

                                    return null;
                                }
                            }, false, true);
                }
            });

            throw new WebScriptException(HttpStatus.SC_FORBIDDEN, ade.getMessage(), ade);
        } catch (Exception e) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
        }
    } else {
        throw new WebScriptException(HttpStatus.SC_NOT_ACCEPTABLE,
                "Missing Google Docs Aspect on " + nodeRef.toString());
    }

    return model;
}

From source file:org.alfresco.integrations.google.docs.webscripts.DiscardContent.java

private Map<String, Serializable> parseContent(final WebScriptRequest req) {
    final Map<String, Serializable> result = new HashMap<String, Serializable>();
    Content content = req.getContent();//  w w  w  .j a  v  a 2 s  .  c o  m
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        jsonStr = content.getContent();
        log.debug("Parsed JSON: " + jsonStr);

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        json = new JSONObject(jsonStr);

        if (!json.has(JSON_KEY_NODEREF)) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Key " + JSON_KEY_NODEREF + " is missing from JSON: " + jsonStr);
        } else {
            NodeRef nodeRef = new NodeRef(json.getString(JSON_KEY_NODEREF));
            result.put(JSON_KEY_NODEREF, nodeRef);

            if (json.has(JSON_KEY_OVERRIDE)) {
                result.put(JSON_KEY_OVERRIDE, json.getBoolean(JSON_KEY_OVERRIDE));
            } else {
                result.put(JSON_KEY_OVERRIDE, false);
            }
        }
    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON '" + jsonStr + "'.", e);
    }

    return result;
}

From source file:org.alfresco.integrations.google.docs.webscripts.HasConcurrentEditors.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();/*www . jav  a2 s  . c om*/

    Map<String, Object> model = new HashMap<String, Object>();

    String param_nodeRef = req.getParameter(PARAM_NODEREF);
    NodeRef nodeRef = new NodeRef(param_nodeRef);

    try {
        Credential credential = googledocsService.getCredential();

        model.put(MODEL_CONCURRENT_EDITORS, googledocsService.hasConcurrentEditors(credential, nodeRef));
    } catch (GoogleDocsAuthenticationException gdae) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
    } catch (GoogleDocsRefreshTokenException gdrte) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
    } catch (GoogleDocsServiceException gdse) {
        if (gdse.getPassedStatusCode() > -1) {
            throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
        } else {
            throw new WebScriptException(gdse.getMessage());
        }
    } catch (Exception e) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
    }

    return model;
}

From source file:org.alfresco.integrations.google.docs.webscripts.IsLatestRevision.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();//from w w w  .j  a  v a 2s  . co  m

    Map<String, Object> model = new HashMap<String, Object>();

    /* Get the nodeRef to test */
    String param_nodeRef = req.getParameter(PARAM_NODEREF);
    NodeRef nodeRef = new NodeRef(param_nodeRef);
    log.debug("Comparing Node Revision Id from Alfresco and Google: " + nodeRef);

    /* The revision Id persisted on the node */
    String currentRevision = null;
    /* The latest revision Id from Google for the file */
    String latestRevision = null;

    try {
        /* The node needs the editingInGoogle aspect if not then tell return 412 */
        if (nodeService.hasAspect(nodeRef, GoogleDocsModel.ASPECT_EDITING_IN_GOOGLE)) {
            Credential credential = googledocsService.getCredential();

            /* get the nodes revision Id null if not found */
            Serializable property = nodeService.getProperty(nodeRef, GoogleDocsModel.PROP_REVISION_ID);
            currentRevision = property != null ? property.toString() : null;
            log.debug("currentRevision: " + currentRevision);

            /* get the latest revision Id null if not found */
            Revision revision = googledocsService.getLatestRevision(credential, nodeRef);
            latestRevision = revision != null ? revision.getId() : null;
            log.debug("latestRevision: " + latestRevision);

            /* compare the revision Ids */
            if (currentRevision != null && latestRevision != null) {

                isLatestRevision = currentRevision.equals(latestRevision);
            }

            model.put(MODEL_IS_LATEST_REVISION, isLatestRevision);
        } else {
            throw new WebScriptException(HttpStatus.SC_PRECONDITION_FAILED,
                    "Node: " + nodeRef.toString() + " has no revision Ids.");
        }
    } catch (GoogleDocsAuthenticationException gdae) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
    } catch (GoogleDocsServiceException gdse) {
        if (gdse.getPassedStatusCode() > -1) {
            throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
        } else {
            throw new WebScriptException(gdse.getMessage());
        }
    } catch (GoogleDocsRefreshTokenException gdrte) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
    } catch (IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage());
    }

    return model;
}