List of usage examples for org.apache.commons.httpclient HttpStatus SC_SERVICE_UNAVAILABLE
int SC_SERVICE_UNAVAILABLE
To view the source code for org.apache.commons.httpclient HttpStatus SC_SERVICE_UNAVAILABLE.
Click Source Link
From source file:JiraWebClient.java
protected void handleErrorMessage(HttpMethodBase method) throws JiraException { try {/*from www .ja va 2s.com*/ String response = method.getResponseBodyAsString(); // TODO consider logging the error if (method.getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) { throw new JiraRemoteException("JIRA system error", null); //$NON-NLS-1$ } if (response == null) { throw new JiraRemoteMessageException("Error making JIRA request: " + method.getStatusCode(), ""); //$NON-NLS-1$ //$NON-NLS-2$ } StringReader reader = new StringReader(response); try { StringBuilder msg = new StringBuilder(); HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer .nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); String classValue = tag.getAttribute("class"); //$NON-NLS-1$ if (classValue != null) { if (tag.getTagType() == Tag.DIV) { if (classValue.startsWith("infoBox") || classValue.startsWith("errorArea") //$NON-NLS-1$ //$NON-NLS-2$ || classValue.contains("error")) { //$NON-NLS-1$ throw new JiraRemoteMessageException(getContent(tokenizer, Tag.DIV)); } } else if (tag.getTagType() == Tag.SPAN) { if (classValue.startsWith("errMsg")) { //$NON-NLS-1$ msg.append(getContent(tokenizer, Tag.SPAN)); } } } } } if (msg.length() == 0) { throw new JiraRemoteMessageException(response); } else { throw new JiraRemoteMessageException(msg.toString()); } } catch (ParseException e) { throw new JiraRemoteMessageException("Error parsing JIRA response: " + method.getStatusCode(), ""); //$NON-NLS-1$ //$NON-NLS-2$ } finally { reader.close(); } } catch (IOException e) { throw new JiraException(e); } }
From source file:edu.unc.lib.dl.fedora.ManagementClient.java
public String upload(File file, boolean retry) { String result = null;/* w w w .j a v a2s .c o m*/ String uploadURL = this.getFedoraContextUrl() + "/upload"; PostMethod post = new PostMethod(uploadURL); post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); log.debug("Uploading file with forwarded groups: " + GroupsThreadStore.getGroupString()); post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString()); try { log.debug("Uploading to " + uploadURL); Part[] parts = { new FilePart("file", file) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); int status = httpClient.executeMethod(post); StringWriter sw = new StringWriter(); try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) { int b; while ((b = in.read()) != -1) { pw.write(b); } } switch (status) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: result = sw.toString().trim(); log.info("Upload complete, response=" + result); break; case HttpStatus.SC_FORBIDDEN: log.warn("Authorization to Fedora failed, attempting to reestablish connection."); try { this.initializeConnections(); return upload(file, false); } catch (Exception e) { log.error("Failed to reestablish connection to Fedora", e); } break; case HttpStatus.SC_SERVICE_UNAVAILABLE: throw new FedoraTimeoutException("Fedora service unavailable, upload failed"); default: log.warn("Upload failed, response=" + HttpStatus.getStatusText(status)); log.debug(sw.toString().trim()); break; } } catch (ServiceException ex) { throw ex; } catch (Exception ex) { throw new ServiceException(ex); } finally { post.releaseConnection(); } return result; }
From source file:davmail.caldav.CaldavConnection.java
/** * Send Http error response for exception * * @param e exception/*from ww w .j a va2 s. c o m*/ * @throws IOException on error */ public void sendErr(Exception e) throws IOException { String message = e.getMessage(); if (message == null) { message = e.toString(); } if (e instanceof HttpNotFoundException) { sendErr(HttpStatus.SC_NOT_FOUND, message); } else if (e instanceof HttpPreconditionFailedException) { sendErr(HttpStatus.SC_PRECONDITION_FAILED, message); } else { sendErr(HttpStatus.SC_SERVICE_UNAVAILABLE, message); } }
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;//w w w . j a v a 2s . com 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.UploadContent.java
@SuppressWarnings("unchecked") @Override//from w ww . j av a 2s .c om protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { getGoogleDocsServiceSubsystem(); Map<String, Object> model = new HashMap<String, Object>(); if (googledocsService.isEnabled()) { String param_nodeRef = req.getParameter(PARAM_NODEREF); NodeRef nodeRef = new NodeRef(param_nodeRef); Map<String, Serializable> jsonParams = parseContent(req); DriveFile driveFile; try { if (nodeService.hasAspect(nodeRef, GoogleDocsModel.ASPECT_EDITING_IN_GOOGLE)) { // Check the doc exists in Google - it may have been removed accidentally try { driveFile = googledocsService.getDriveFile(nodeRef); } catch (GoogleDocsServiceException gdse) { driveFile = googledocsService.uploadFile(nodeRef); if (log.isDebugEnabled()) { log.debug(nodeRef + " Uploaded to Google."); } // Re-apply the previous permissions, if they exist if (nodeService.getProperty(nodeRef, GoogleDocsModel.PROP_CURRENT_PERMISSIONS) != null) { googledocsService.addRemotePermissions(driveFile, googledocsService .getGooglePermissions(nodeRef, GoogleDocsModel.PROP_CURRENT_PERMISSIONS), true); } } } else { driveFile = googledocsService.uploadFile(nodeRef); if (log.isDebugEnabled()) { log.debug(nodeRef + " Uploaded to Google."); } } if (jsonParams.containsKey(PARAM_PERMISSIONS)) { if (log.isDebugEnabled()) { log.debug("Adding permissions to remote object"); } googledocsService.addRemotePermissions(driveFile, (List<GooglePermission>) jsonParams.get(PARAM_PERMISSIONS), ((Boolean) jsonParams.get(PARAM_SEND_EMAIL)).booleanValue()); } // If this is a non-cloud instance of Alfresco, we need to make the // node versionable before we start working on it. We want the the // version component to be triggered on save. The versionable aspect // is only added if this is existing content, not if it was just // created where the document is the initial version when saved if (!nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPORARY) && !nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) { Map<String, Serializable> versionProperties = new HashMap<String, Serializable>(); versionProperties.put(Version2Model.PROP_VERSION_TYPE, VersionType.MAJOR); nodeService.setProperty(nodeRef, ContentModel.PROP_AUTO_VERSION, true); // autoVersionOnUpdateProps now set to false to follow Share upload scripts (fixes GOOGLEDOCS-111) nodeService.setProperty(nodeRef, ContentModel.PROP_AUTO_VERSION_PROPS, false); log.debug("Version Node:" + nodeRef + "; Version Properties: " + versionProperties); versionService.createVersion(nodeRef, versionProperties); } if (googledocsService.isLockedByGoogleDocs(nodeRef)) { googledocsService.unlockNode(nodeRef); } googledocsService.decorateNode(nodeRef, driveFile, googledocsService.getLatestRevision(driveFile), (List<GooglePermission>) jsonParams.get(PARAM_PERMISSIONS), false); googledocsService.lockNode(nodeRef); } 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(), ioe); } catch (Exception e) { throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e); } model.put(MODEL_NODEREF, nodeRef.toString()); } else { throw new WebScriptException(HttpStatus.SC_SERVICE_UNAVAILABLE, "Google Docs Disabled"); } return model; }
From source file:org.alfresco.repo.jive.rest.GetCommunitiesWebScript.java
/** * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.Status, org.springframework.extensions.webscripts.Cache) *//*from w w w . ja v a 2 s.co m*/ @Override protected Map<String, Object> executeImpl(final WebScriptRequest req, final Status status, final Cache cache) { if (log.isTraceEnabled()) log.trace("GetCommunitiesWebScript.executeImpl called"); final Map<String, Object> result = new HashMap<String, Object>(); final String communityIdAsStr = parseCommunityId(req.getExtensionPath()); List<JiveCommunity> subCommunities = null; cache.setNeverCache(true); if (communityIdAsStr != null && communityIdAsStr.trim().length() > 0) { // We got a community Id in the request, so retrieve its subcommunities long communityId = -1; try { communityId = Long.parseLong(communityIdAsStr); } catch (final NumberFormatException nfe) { throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Could not parse community Id from value '" + communityIdAsStr + "'.", nfe); } try { if (log.isDebugEnabled()) log.debug("Retrieving sub-communities of Jive community " + communityId); result.put("root", false); subCommunities = jiveService.getSubCommunities(communityId); } catch (final InvalidCommunityException ice) { throw new WebScriptException(HttpStatus.SC_NOT_FOUND, ice.getMessage(), ice); } catch (final ServiceUnavailableException sue) { throw new WebScriptException(HttpStatus.SC_SERVICE_UNAVAILABLE, sue.getMessage(), sue); } } else { try { // No community id provided, so retrieve the root-level communities if (log.isDebugEnabled()) log.debug("Retrieving root-level communities from Jive."); result.put("root", true); subCommunities = jiveService.getCommunities(); } catch (final ServiceUnavailableException sue) { throw new WebScriptException(HttpStatus.SC_SERVICE_UNAVAILABLE, sue.getMessage(), sue); } } result.put("subCommunities", subCommunities); return (result); }
From source file:org.alfresco.repo.jive.rest.SocializeDocumentsWebScript.java
/** * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.Status, org.springframework.extensions.webscripts.Cache) *//* w ww. j ava2 s . co m*/ @Override protected Map<String, Object> executeImpl(final WebScriptRequest req, final Status status, final Cache cache) { if (log.isTraceEnabled()) log.trace("SocializeDocumentsWebScript.executeImpl called"); Map<String, Object> result = null; List<NodeRef> nodeRefs = parseNodeRefs(req); long communityId = parseCommunityId(req); cache.setNeverCache(true); try { if (log.isDebugEnabled()) log.debug("Socializing documents " + Arrays.toString(nodeRefs.toArray()) + " to Jive community " + communityId); jiveService.socializeDocuments(nodeRefs, communityId); } catch (final FileNotFoundException fnfe) { throw new WebScriptException(HttpStatus.SC_NOT_FOUND, fnfe.getMessage(), fnfe); } catch (final NotAFileException nafe) { throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, nafe.getMessage(), nafe); } catch (final JiveServiceException jse) { throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, jse.getMessage(), jse); } catch (final ServiceUnavailableException sue) { throw new WebScriptException(HttpStatus.SC_SERVICE_UNAVAILABLE, sue.getMessage(), sue); } catch (final DocumentSizeException dse) { throw new WebScriptException(HttpStatus.SC_CONFLICT, dse.getMessage(), dse); } return (result); }
From source file:org.carrot2.source.boss.BossSearchService.java
/** * Sends a search query to Yahoo! and parses the result. *///from w ww.j a v a 2 s.co m protected final SearchEngineResponse query(String query, int start, int results) throws IOException { results = Math.min(results, metadata.resultsPerPage); final ArrayList<NameValuePair> params = createRequestParams(query, start, results); params.add(new NameValuePair("appid", appid)); params.add(new NameValuePair("start", Integer.toString(start))); params.add(new NameValuePair("count", Integer.toString(results))); params.add(new NameValuePair("format", "xml")); params.add(new NameValuePair("sites", sites)); if (languageAndRegion != null) { try { params.add(new NameValuePair("lang", languageAndRegion.langCode)); params.add(new NameValuePair("region", languageAndRegion.regionCode)); } catch (IllegalArgumentException e) { throw new IOException("Language value: " + languageAndRegion); } } final String serviceURI = substituteAttributes(getServiceURI(), new NameValuePair("query", query)); final HttpUtils.Response response = HttpUtils.doGET(serviceURI, params, Arrays.asList(new Header[] { HttpHeaders.USER_AGENT_HEADER_MOZILLA })); final int statusCode = response.status; if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE || statusCode == HttpStatus.SC_BAD_REQUEST) { // Parse the data stream. final SearchEngineResponse ser = parseResponseXML(response.getPayloadAsStream()); ser.metadata.put(SearchEngineResponse.COMPRESSION_KEY, response.compression); if (logger.isDebugEnabled()) { logger.debug("Received, results: " + ser.results.size() + ", total: " + ser.getResultsTotal()); } return ser; } else { // Read the output and throw an exception. final String m = "BOSS returned HTTP Error: " + statusCode + ", HTTP payload: " + new String(response.payload, "iso8859-1"); logger.warn(m); throw new IOException(m); } }
From source file:org.carrot2.source.yahoo.YahooSearchService.java
/** * Sends a search query to Yahoo! and parses the result. *///from www .java 2 s . c om protected final SearchEngineResponse query(String query, int start, int results) throws IOException { // Yahoo's results start from 1. start++; results = Math.min(results, metadata.resultsPerPage); final ArrayList<NameValuePair> params = createRequestParams(query, start, results); params.add(new NameValuePair("output", "xml")); final HttpUtils.Response response = HttpUtils.doGET(getServiceURI(), params, Arrays.asList(new Header[] { HttpHeaders.USER_AGENT_HEADER_MOZILLA })); final int statusCode = response.status; if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE || statusCode == HttpStatus.SC_BAD_REQUEST) { // Parse the data stream. final SearchEngineResponse ser = parseResponseXML(response.getPayloadAsStream()); ser.metadata.put(SearchEngineResponse.COMPRESSION_KEY, response.compression); if (logger.isDebugEnabled()) { logger.debug("Received, results: " + ser.results.size() + ", total: " + ser.getResultsTotal() + ", first: " + ser.metadata.get(FIRST_INDEX_KEY)); } return ser; } else { // Read the output and throw an exception. final String m = "Yahoo returned HTTP Error: " + statusCode + ", HTTP payload: " + new String(response.payload, "iso8859-1"); logger.warn(m); throw new IOException(m); } }
From source file:org.codehaus.mojo.delicious.DeliciousServiceTest.java
/** * Inserts an http connector that only reports service-unavailable. * @throws InterruptedException //w w w .ja v a 2s . c om * @throws IOException * */ public void testServiceUnavailable() throws IOException, InterruptedException { DeliciousService service = new DeliciousService(new DeliciousConnection() { public int executeMethod(HttpClient client, GetMethod httpMethod) throws IOException, HttpException { return HttpStatus.SC_SERVICE_UNAVAILABLE; } }); try { service.setUser("", ""); service.addBookmark(new Bookmark(), Boolean.TRUE); } catch (RuntimeException e) { assertEquals(service.getCode(), HttpStatus.SC_SERVICE_UNAVAILABLE); } }