Java Code Examples for javax.ws.rs.core.Response.Status#INTERNAL_SERVER_ERROR

The following examples show how to use javax.ws.rs.core.Response.Status#INTERNAL_SERVER_ERROR . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WorkerImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public WorkerInfo getClusterLeader(String clientRole) {
    if (!isWorkerServiceAvailable()) {
        throwUnavailableException();
    }

    if (worker().getWorkerConfig().isAuthorizationEnabled() && !isSuperUser(clientRole)) {
        log.error("Client [{}] is not authorized to get cluster leader", clientRole);
        throw new RestException(Status.UNAUTHORIZED, "client is not authorize to perform operation");
    }

    MembershipManager membershipManager = worker().getMembershipManager();
    WorkerInfo leader = membershipManager.getLeader();

    if (leader == null) {
        throw new RestException(Status.INTERNAL_SERVER_ERROR, "Leader cannot be determined");
    }

    return leader;
}
 
Example 2
Source File: FilesUtils.java    From at.info-knowledge-base with MIT License 6 votes vote down vote up
public static Status unZipItems(final String filePath, final String outputFolder) {
    Status response;

    if (getExtension(filePath).equals("zip")) {
        try {
            new ZipFile(filePath).extractAll(outputFolder);
            IO_LOGGER.info("All files have been successfully extracted!");
            response = Status.OK;
        } catch (ZipException e) {
            IO_LOGGER.severe("Unable extract files from " + filePath + ": " + e.getMessage());
            response = Status.INTERNAL_SERVER_ERROR;
        }
    } else {
        response = Status.NOT_FOUND;
    }

    return response;
}
 
Example 3
Source File: AlbResource.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/target-groups/{targetGroup}/targets/{instanceId}")
public AgentCheckInResponse removeFromTargetGroup(@PathParam("targetGroup") String targetGroup,
                                                  @PathParam("instanceId") String instanceId) {
  if (instanceId == null) {
    throw new BaragonWebException("Must provide instance ID to remove target from group");
  } else if (config.isPresent()) {
    AgentCheckInResponse result = applicationLoadBalancer.removeInstance(instanceId, targetGroup);
    if (result.getExceptionMessage().isPresent()) {
      throw new WebApplicationException(result.getExceptionMessage().get(), Status.INTERNAL_SERVER_ERROR);
    }
    return result;
  } else {
    throw new BaragonWebException("ElbSync and related actions not currently enabled");
  }
}
 
Example 4
Source File: EntityParent.java    From agrest with Apache License 2.0 5 votes vote down vote up
public EntityParent(Class<P> parentType, String relationshipFromParent) {

		if (parentType == null) {
			throw new AgException(Status.INTERNAL_SERVER_ERROR, "Related parent type is missing");
		}

		if (relationshipFromParent == null) {
			throw new AgException(Status.INTERNAL_SERVER_ERROR, "Related parent relationship is missing");
		}

		this.type = parentType;
		this.relationship = relationshipFromParent;
	}
 
Example 5
Source File: FieldInjectionResource.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
@GET
public String sessionUser() {
    try {
        return subject.getPrincipal().toString();
    } catch (NullPointerException e) {
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example 6
Source File: TestResource.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Path("service-discovery")
@GET
public String serviceDiscovery(@Context @ServiceName("test-service") Record classRecord,
		@Context @ServiceName("hello-service") Record methodRecord,
		@Context @ServiceName("missing-service") Record missingRecord) {
	if(classRecord == null || !classRecord.getLocation().getString("endpoint").equals("http://localhost:9000/test"))
		throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
	if(methodRecord == null || !methodRecord.getLocation().getString("endpoint").equals("http://localhost:9000/test/hello"))
		throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
	if(missingRecord != null)
		throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
	return "ok";
}
 
Example 7
Source File: InjectionResource.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
@Path("usersubject")
@GET
public String sessionUser(@Auth Subject subject, @Auth User user) {
    if (subject != user.unwrap(Subject.class)) {
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
    return "User and Subject method param injection works.\n";
}
 
Example 8
Source File: MCRWCMSNavigationResource.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public String get() {
    try {
        JsonObject json = MCRWCMSNavigationUtils.getNavigationAsJSON();
        return json.toString();
    } catch (Exception exc) {
        throw new WebApplicationException(exc, Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example 9
Source File: StatisticsResource.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@POST
   @Path("set_db_settings")
   @Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
   public Response setDBSettings(XmlStatisticsDBSettings dbSettings) throws IOException {
       
       XmlResponse xmlResponse = new XmlResponse();
       Status status = Status.OK;
       
       StatisticsServiceSettings settings = new StatisticsServiceSettings(getStatisticsService().getSettings());
       settings.setServiceEnabled(dbSettings.getStatisticsServiceEnabled());
       settings.getStorageSettings().setDbms(dbSettings.getDbms());
       settings.getStorageSettings().setHost(dbSettings.getHost());
       settings.getStorageSettings().setPort(dbSettings.getPort());
       settings.getStorageSettings().setDbName(dbSettings.getDbName());
       settings.getStorageSettings().setConnectionOptionsQuery(dbSettings.getConnectionOptionsQuery());
       settings.getStorageSettings().setUsername(dbSettings.getUsername());
       settings.getStorageSettings().setPassword(dbSettings.getPassword());
       
       try {
           TestToolsAPI.getInstance().setStatisticsDBSettings(settings);
       } catch (Exception e) {
           logger.error(e.getMessage(), e);
           status = Status.INTERNAL_SERVER_ERROR;
           xmlResponse.setMessage("Unexpected error");
           xmlResponse.setRootCause(e.getMessage());
       }
       xmlResponse.setMessage("OK");
         
       return Response.
               status(status).
               entity(xmlResponse).
               build();        
   }
 
Example 10
Source File: TestResourceRxJava1.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@NoAuthRedirect
@RequiresUser
@Path("inject-user")
@GET
public String injectUser(@Context User user,
		@Context AuthProvider authProvider) {
	if(user == null
			|| authProvider == null)
		throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
	return "ok";
}
 
Example 11
Source File: GET_ExceptionIT.java    From agrest with Apache License 2.0 5 votes vote down vote up
@GET
@Path("th")
public Response getTh() {
    try {
        throw new Throwable("Dummy");
    } catch (Throwable th) {
        throw new AgException(Status.INTERNAL_SERVER_ERROR, "request failed with th", th);
    }
}
 
Example 12
Source File: MultiSelectBuilder.java    From agrest with Apache License 2.0 5 votes vote down vote up
public DataResponse<T> select(long timeout, TimeUnit timeoutUnit) {

        // TODO: can we properly cancel the tasks on timeout?
        try {
            return selectAsync().get(timeout, timeoutUnit);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            LOGGER.info("Async fetcher error", e);
            throw new AgException(Status.INTERNAL_SERVER_ERROR, "Error fetching games", e);
        }
    }
 
Example 13
Source File: GatewayRequestHandler.java    From jrestless with Apache License 2.0 4 votes vote down vote up
@Override
protected GatewayResponse onRequestFailure(Exception e, GatewayRequestAndLambdaContext request,
		JRestlessContainerRequest containerRequest) {
	LOG.error("request failed", e);
	return new GatewayResponse(null, Collections.emptyMap(), Status.INTERNAL_SERVER_ERROR, false);
}
 
Example 14
Source File: DefaultExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
Status getResponseStatus() {
    return Status.INTERNAL_SERVER_ERROR;
}
 
Example 15
Source File: ServiceSimple.java    From jqm with Apache License 2.0 4 votes vote down vote up
@GET
@Path("localnode/health")
@Produces(MediaType.TEXT_PLAIN)
public String getLocalNodeHealth() throws MalformedObjectNameException
{
    // Local service only - not enabled when running on top of Tomcat & co.
    if (n == null)
    {
        throw new ErrorDto("can only retrieve local node health when the web app runs on top of JQM", "", 7, Status.BAD_REQUEST);
    }
    if (n.getJmxServerPort() == null || n.getJmxServerPort() == 0)
    {
        throw new ErrorDto("JMX is not enabled on this server", "", 8, Status.BAD_REQUEST);
    }

    // Connect to JMX server
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    ObjectName nodeBean = new ObjectName("com.enioka.jqm:type=Node,name=" + n.getName());
    Set<ObjectName> names = server.queryNames(nodeBean, null);
    if (names.isEmpty())
    {
        throw new ErrorDto("could not find the JMX Mbean of the local JQM node", "", 8, Status.INTERNAL_SERVER_ERROR);
    }
    ObjectName localNodeBean = names.iterator().next();

    // Query bean
    Object result;
    try
    {
        result = server.getAttribute(localNodeBean, "AllPollersPolling");
    }
    catch (Exception e)
    {
        throw new ErrorDto("Issue when querying JMX server", 12, e, Status.INTERNAL_SERVER_ERROR);
    }
    if (!(result instanceof Boolean))
    {
        throw new ErrorDto("JMX bean answered with wrong datatype - answer was " + result.toString(), "", 9,
                Status.INTERNAL_SERVER_ERROR);
    }

    // Analyze output
    boolean res = (Boolean) result;
    if (!res)
    {
        throw new ErrorDto("JQM node has is not working as expected", "", 11, Status.SERVICE_UNAVAILABLE);
    }

    return "Pollers are polling";
}
 
Example 16
Source File: IssueTypeToHttpStatusMapper.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private static Status issueTypeToResponseCode(IssueType.ValueSet value) {
    switch (value) {
    case INFORMATIONAL:
        return Status.OK;
    case FORBIDDEN:
    case SUPPRESSED:
    case SECURITY:
    case THROTTLED:     // Consider HTTP 429?
        return Status.FORBIDDEN;
    case PROCESSING:
    case BUSINESS_RULE: // Consider HTTP 422?
    case CODE_INVALID:  // Consider HTTP 422?
    case EXTENSION:     // Consider HTTP 422?
    case INVALID:       // Consider HTTP 422?
    case INVARIANT:     // Consider HTTP 422?
    case REQUIRED:      // Consider HTTP 422?
    case STRUCTURE:     // Consider HTTP 422?
    case VALUE:         // Consider HTTP 422?
    case TOO_COSTLY:    // Consider HTTP 403?
    case DUPLICATE:     // Consider HTTP 409?
        return Status.BAD_REQUEST;
    case DELETED:
        return Status.GONE;
    case CONFLICT:
        return Status.CONFLICT;
    case MULTIPLE_MATCHES:
        return Status.PRECONDITION_FAILED;
    case EXPIRED:
    case LOGIN:
    case UNKNOWN:
        return Status.UNAUTHORIZED;
    case NOT_FOUND:
    case NOT_SUPPORTED:
        return Status.NOT_FOUND;
    case TOO_LONG:
        return Status.REQUEST_ENTITY_TOO_LARGE;
    case EXCEPTION:
    case LOCK_ERROR:
    case NO_STORE:
    case TIMEOUT:
    case TRANSIENT:
    case INCOMPLETE:
    default:
        return Status.INTERNAL_SERVER_ERROR;
    }
}
 
Example 17
Source File: RuntimeExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
Status getResponseStatus() {
    return Status.INTERNAL_SERVER_ERROR;
}
 
Example 18
Source File: ApiException.java    From redpipe with Apache License 2.0 4 votes vote down vote up
public ApiException(Throwable cause){
	super(cause);
	status = Status.INTERNAL_SERVER_ERROR;
}
 
Example 19
Source File: RuntimeExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
Status getResponseStatus() {
    return Status.INTERNAL_SERVER_ERROR;
}
 
Example 20
Source File: CK3ImageBrowser.java    From docx-html-editor with GNU Affero General Public License v3.0 4 votes vote down vote up
@GET
	@Path("{url : .*}")
	public Response browse(
			@Context  HttpServletRequest request,
			@Context  HttpServletResponse response,									
			@Context  ServletContext context,
			@Context UriInfo info,
			@PathParam("url") String url,
			@QueryParam("CKEditorFuncNum") String CKEditorFuncNum
			)  {
		
		try {
			
			HttpSession session = request.getSession(false);
			
//					jul.info("request.getRequestURI()"+request.getRequestURI());
//					jul.info("info.getRequestUri().toASCIIString()"+info.getRequestUri().toASCIIString());  // pretty close
//					jul.info("request.getQueryString()"+request.getQueryString());
//					jul.info("info.getPath(false)"+info.getPath(false));
//					jul.info("info.getPath(true)"+info.getPath(true));
			
//					String browseUrl = url + "?" + request.getQueryString();
//					jul.info(browseUrl);
					
			if (url.equals("")) {
				// display all the images
				
				StringBuilder sb = new StringBuilder();
				sb.append("<html><body>");
				HashMap<String, byte[]> imageMap = SessionImageHandler.getImageMap(session);
				if (imageMap.size()==0) {
					sb.append("No images found. Click the 'upload' tab?");
				} else {
					for (Entry<String, byte[]> entry : imageMap.entrySet()) {
						String suffix = "?CKEditorFuncNum="+CKEditorFuncNum;
						String imgUrl = getUrl(response, entry.getKey() + suffix);	
						sb.append("<p><a href=\"" + imgUrl + "\">" + entry.getKey() + "</a></p>");
					}
				}
				sb.append("</body></html>");
				return Response.ok(sb.toString() ).build();
				
			} else {
				// its a request for a specific image
				String imageUrl = getUrl(response, url);
				
				String html = "<html><body><script type=\"text/javascript\">"
						  + "window.opener.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + imageUrl + "\");"
								+ "</script></body></html>";
					
						
				return Response.ok(html).build();
				
			}
					
		
		} catch (Exception e) {
			e.printStackTrace();
//			System.out.println(e.getMessage());
			throw new WebApplicationException(
					new Docx4JException(e.getMessage(), e), 
					Status.INTERNAL_SERVER_ERROR);
		}

	}