javax.ws.rs.InternalServerErrorException Java Examples

The following examples show how to use javax.ws.rs.InternalServerErrorException. 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: WebAPI.java    From Web-API with MIT License 6 votes vote down vote up
public static void runOnMain(Runnable runnable) throws WebApplicationException {
    if (Sponge.getServer().isMainThread()) {
        runnable.run();
    } else {
        CompletableFuture future = CompletableFuture.runAsync(runnable, WebAPI.syncExecutor);
        try {
            future.get();
        } catch (InterruptedException ignored) {
        } catch (ExecutionException e) {
            // Rethrow any web application exceptions we get, because they're handled by the servlets
            if (e.getCause() instanceof WebApplicationException)
                throw (WebApplicationException)e.getCause();

            e.printStackTrace();
            WebAPI.sentryCapture(e);
            throw new InternalServerErrorException(e.getMessage());
        }
    }
}
 
Example #2
Source File: PersonServiceWithJDBC.java    From microshed-testing with Apache License 2.0 6 votes vote down vote up
@POST
  public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
                           @QueryParam("age") @PositiveOrZero int age){
Person p = new Person(name, age);

try (Connection conn = defaultDataSource.getConnection();
	 PreparedStatement ps = conn.prepareStatement("INSERT INTO people VALUES(?,?,?)")){
	ps.setLong(1, p.id);
	ps.setString(2, name);
	ps.setInt(3, age);
	ps.execute();		
	return p.id;	
} catch (SQLException e) {
	e.printStackTrace(System.out);
}
throw new InternalServerErrorException("Could not create new person");    
  }
 
Example #3
Source File: PersonServiceWithJDBC.java    From microshed-testing with Apache License 2.0 6 votes vote down vote up
@POST
  @Path("/{personId}")
  public void updatePerson(@PathParam("personId") long id, @Valid Person p) {
      try (Connection conn = defaultDataSource.getConnection();
	 PreparedStatement ps = conn.prepareStatement("UPDATE people SET name = ?, age = ? WHERE id = ?")){
	ps.setString(1, p.name);
	ps.setInt(2, p.age);		
	ps.setLong(3, p.id);
	if (ps.executeUpdate() > 0) {
		return;
	};	
	throw new NotFoundException("Person with id " + id + " not found.");
} catch (SQLException e) {
	e.printStackTrace(System.out);
} 
throw new InternalServerErrorException("Could not update person");   
  }
 
Example #4
Source File: RestBotAdministration.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public List<BotDeploymentStatus> getDeploymentStatuses(Deployment.Environment environment) {
    RuntimeUtilities.checkNotNull(environment, "environment");

    try {
        List<BotDeploymentStatus> botDeploymentStatuses = new LinkedList<>();
        for (IBot latestBot : botFactory.getAllLatestBots(environment)) {
            String botId = latestBot.getBotId();
            Integer botVersion = latestBot.getBotVersion();
            DocumentDescriptor documentDescriptor = documentDescriptorStore.readDescriptor(botId, botVersion);
            botDeploymentStatuses.add(new BotDeploymentStatus(
                    environment,
                    botId,
                    botVersion,
                    latestBot.getDeploymentStatus(),
                    documentDescriptor));
        }

        botDeploymentStatuses.sort(Comparator.comparing(o -> o.getDescriptor().getLastModifiedOn()));
        Collections.reverse(botDeploymentStatuses);

        return botDeploymentStatuses;
    } catch (ServiceException | ResourceStoreException | ResourceNotFoundException e) {
        throw new InternalServerErrorException(e.getLocalizedMessage(), e);
    }
}
 
Example #5
Source File: RestBotAdministration.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public Response undeployBot(Deployment.Environment environment, String botId, Integer version) {
    RuntimeUtilities.checkNotNull(environment, "environment");
    RuntimeUtilities.checkNotNull(botId, "botId");
    RuntimeUtilities.checkNotNull(version, "version");

    try {
        Long activeConversationCount = conversationMemoryStore.getActiveConversationCount(botId, version);
        if (activeConversationCount > 0) {
            String message = "%s active (thus not ENDED) conversation(s) going on with this bot!" +
                    "\nCheck GET /conversationstore/conversations/active/%s?botVersion=%s " +
                    "to see active conversations and end conversations with " +
                    "POST /conversationstore/conversations/end , " +
                    "providing the list you receive with GET";
            message = String.format(message, activeConversationCount, botId, version);
            return Response.status(Response.Status.CONFLICT).entity(message).type(MediaType.TEXT_PLAIN).build();
        }

        undeploy(environment, botId, version);
        return Response.accepted().build();
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException(e.getLocalizedMessage(), e);
    }
}
 
Example #6
Source File: RestBotAdministration.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public Response deployBot(final Deployment.Environment environment,
                          final String botId, final Integer version, final Boolean autoDeploy) {
    RuntimeUtilities.checkNotNull(environment, "environment");
    RuntimeUtilities.checkNotNull(botId, "botId");
    RuntimeUtilities.checkNotNull(version, "version");
    RuntimeUtilities.checkNotNull(autoDeploy, "autoDeploy");

    try {
        deploy(environment, botId, version, autoDeploy);
        return Response.accepted().build();
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException(e.getLocalizedMessage(), e);
    }
}
 
Example #7
Source File: PersonServiceWithJDBC.java    From microprofile-sandbox with Apache License 2.0 6 votes vote down vote up
@POST
  public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
                           @QueryParam("age") @PositiveOrZero int age){
Person p = new Person(name, age);

try (Connection conn = defaultDataSource.getConnection();
	 PreparedStatement ps = conn.prepareStatement("INSERT INTO people VALUES(?,?,?)")){
	ps.setLong(1, p.id);
	ps.setString(2, name);
	ps.setInt(3, age);
	ps.execute();		
	return p.id;	
} catch (SQLException e) {
	e.printStackTrace(System.out);
}
throw new InternalServerErrorException("Could not create new person");    
  }
 
Example #8
Source File: RestGitBackupService.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public Response gitInit(String botId) {
    try {
        deleteFileIfExists(Paths.get(tmpPath + botId));
        Path gitPath = Files.createDirectories(Paths.get(tmpPath + botId));
        Git git = Git.cloneRepository()
                .setBranch(gitBranch)
                .setURI(gitUrl)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitUsername, gitPassword))
                .setDirectory(gitPath.toFile())
                .call();
        StoredConfig config = git.getRepository().getConfig();
        config.setString( CONFIG_BRANCH_SECTION, "local-branch", "remote", gitBranch);
        config.setString( CONFIG_BRANCH_SECTION, "local-branch", "merge", "refs/heads/" + gitBranch );
        config.save();

    } catch (IOException | GitAPIException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException();
    }
    return Response.accepted().build();
}
 
Example #9
Source File: RestImportService.java    From EDDI with Apache License 2.0 6 votes vote down vote up
private void importBotZipFile(InputStream zippedBotConfigFiles, File targetDir, AsyncResponse response) throws IOException {
    this.zipArchive.unzip(zippedBotConfigFiles, targetDir);

    String targetDirPath = targetDir.getPath();
    Files.newDirectoryStream(Paths.get(targetDirPath),
            path -> path.toString().endsWith(BOT_FILE_ENDING))
            .forEach(botFilePath -> {
                try {
                    String botFileString = readFile(botFilePath);
                    BotConfiguration botConfiguration =
                            jsonSerialization.deserialize(botFileString, BotConfiguration.class);
                    botConfiguration.getPackages().forEach(packageUri ->
                            parsePackage(targetDirPath, packageUri, botConfiguration, response));

                    URI newBotUri = createNewBot(botConfiguration);
                    updateDocumentDescriptor(Paths.get(targetDirPath), buildOldBotUri(botFilePath), newBotUri);
                    response.resume(Response.ok().location(newBotUri).build());
                } catch (IOException | RestInterfaceFactory.RestInterfaceFactoryException e) {
                    log.error(e.getLocalizedMessage(), e);
                    response.resume(new InternalServerErrorException());
                }
            });
}
 
Example #10
Source File: ExchangesApi.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{name}/permissions/actions/{action}/groups")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Add new user group(s) for a particular action on the exchange.", notes = "Grant exchange permission for new user group(s).", response = ResponseMessage.class, authorizations = {
    @Authorization(value = "basicAuth")
}, tags={  })
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "User groups added.", response = ResponseMessage.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = Error.class),
    @ApiResponse(code = 401, message = "Authentication Data is missing or invalid", response = Error.class),
    @ApiResponse(code = 403, message = "Requested action unauthorized.", response = Error.class),
    @ApiResponse(code = 409, message = "Duplicate resource", response = Error.class),
    @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format.", response = Error.class) })
public Response addExchangeActionUserGroups(@Context Request request, @PathParam("name") @ApiParam("Name of the exchange.") String name,@PathParam("action") @ApiParam("Name of the action.") String action,
                                            @Valid UserGroupList body) {
    try {
        return grantApiDelegate.addUserGroupsToAction(ResourceType.EXCHANGE, name, ResourceAction.getResourceAction(action), body,
                                                      (Subject) request.getSession().getAttribute(BrokerAuthConstants.AUTHENTICATION_ID));
    } catch (Exception e) {
        throw new InternalServerErrorException(e.getMessage(), e);
    }
}
 
Example #11
Source File: CacheService.java    From Web-API with MIT License 6 votes vote down vote up
/**
 * Gets a specific player by UUID.
 * @param uuid The UUID of the player.
 * @return An optional containing the cached player if found, or empty otherwise.
 */
public Optional<CachedPlayer> getPlayer(UUID uuid) {
    if (!players.containsKey(uuid)) {
        return WebAPI.runOnMain(() -> {
            Optional<UserStorageService> optSrv = Sponge.getServiceManager().provide(UserStorageService.class);
            if (!optSrv.isPresent())
                throw new InternalServerErrorException("User storage service is not available");

            Optional<User> optUser = optSrv.get().get(uuid);
            return optUser.<CachedPlayer>map(CachedPlayer::new);
        });
    }

    final CachedPlayer res = players.get(uuid);
    if (res.isExpired()) {
        return WebAPI.runOnMain(() -> {
            Optional<Player> player = Sponge.getServer().getPlayer(uuid);
            return player.map(this::updatePlayer);
        });
    } else {
        return Optional.of(res);
    }
}
 
Example #12
Source File: RestConversationStore.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public Response endActiveConversations(List<ConversationStatus> conversationStatuses) {
    try {
        for (ConversationStatus conversationStatus : conversationStatuses) {
            String conversationId = conversationStatus.getConversationId();
            conversationMemoryStore.setConversationState(
                    conversationId,
                    ConversationState.ENDED);

            ConversationDescriptor conversationDescriptor = conversationDescriptorStore.
                    readDescriptor(conversationId, 0);
            conversationDescriptor.setConversationState(ConversationState.ENDED);
            conversationDescriptorStore.setDescriptor(conversationId, 0, conversationDescriptor);

            log.info(String.format("conversation (%s) has been set to ENDED", conversationId));
        }

        return Response.ok().build();
    } catch (IResourceStore.ResourceStoreException | IResourceStore.ResourceNotFoundException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException();
    }
}
 
Example #13
Source File: QueuesApi.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/{queueName}/permissions/actions/{action}/groups/{groupName}")
@Produces({ "application/json" })
@ApiOperation(value = "Remove permission to an action from a user group for a queue.", notes = "Revoke permissions for a user group from invoking a particular action on a specific queue.", response = ResponseMessage.class, authorizations = {
    @Authorization(value = "basicAuth")
}, tags={  })
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "User group removed.", response = ResponseMessage.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = Error.class),
    @ApiResponse(code = 401, message = "Authentication Data is missing or invalid", response = Error.class),
    @ApiResponse(code = 403, message = "Requested action unauthorized.", response = Error.class),
    @ApiResponse(code = 409, message = "Duplicate resource", response = Error.class),
    @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format.", response = Error.class) })
public Response deleteUserGroup(@Context Request request, @PathParam("queueName") @ApiParam("Name of the queue.") String queueName,@PathParam("action") @ApiParam("Name of the action.") String action,@PathParam("groupName") @ApiParam("Name of the user group") String groupName) {
    try {
        return authGrantApiDelegate.removeUserGroup(ResourceType.QUEUE, queueName, ResourceAction.getResourceAction(action), groupName,
                                                    (Subject) request.getSession().getAttribute(BrokerAuthConstants.AUTHENTICATION_ID));
    } catch (Exception e) {
        throw new InternalServerErrorException(e.getMessage(), e);
    }
}
 
Example #14
Source File: UserStatsResource.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@GET
public UserStats getActiveUserStats() {
  try {
    final UserStats.Builder activeUserStats = new UserStats.Builder();
    activeUserStats.setEdition(editionProvider.getEdition());

    final SearchJobsRequest request = SearchJobsRequest.newBuilder()
      .setFilterString(String.format(FILTER, getStartOfLastMonth(), System.currentTimeMillis()))
      .build();
    final Iterable<JobSummary> resultantJobs = jobsService.searchJobs(request);
    for (JobSummary job : resultantJobs) {
      activeUserStats.addUserStat(job.getStartTime(), job.getQueryType().name(), job.getUser());
    }
    return activeUserStats.build();
  } catch (Exception e) {
    logger.error("Error while computing active user stats", e);
    throw new InternalServerErrorException(e);
  }
}
 
Example #15
Source File: MCRContentAbstractWriter.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void writeTo(MCRContent content, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
    throws IOException, WebApplicationException {
    String format = getTransfomerFormat().getSubtype();
    String detail = mediaType.getParameters().getOrDefault(MCRDetailLevel.MEDIA_TYPE_PARAMETER,
        MCRDetailLevel.normal.toString());
    LogManager.getLogger().debug("MediaType={}, format={}, detail={}", mediaType, format, detail);
    Optional<String> transformerId = getTransformerId(annotations, format, detail);
    LogManager.getLogger().debug("Transformer for {} would be {}.", content.getSystemId(),
        transformerId.orElse(null));
    Optional<MCRContentTransformer> transformer = transformerId
        .map(MCRContentTransformerFactory::getTransformer);
    if (transformer.isPresent()) {
        transformer.get().transform(content, entityStream);
    } else if (MCRDetailLevel.normal.toString().equals(detail)) {
        handleFallback(content, entityStream);
    } else if (transformerId.isPresent()) {
        throw new InternalServerErrorException("MCRContentTransformer " + transformerId.get() + " is not defined.");
    } else {
        LogManager.getLogger().warn("Could not get MCRContentTransformer from request");
        handleFallback(content, entityStream);
    }
}
 
Example #16
Source File: FacebookEndpoint.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public Response webHook(final String botId, final Integer botVersion,
                        final String callbackPayload, final String sha1PayloadSignature) {
    SystemRuntime.getRuntime().submitCallable((Callable<Void>) () -> {
        try {
            log.info("web hook called");
            getMessageClient(botId, botVersion).getReceiveClient().
                    processCallbackPayload(callbackPayload, sha1PayloadSignature);
        } catch (MessengerVerificationException e) {
            log.error(e.getLocalizedMessage(), e);
            throw new InternalServerErrorException("Error when processing callback payload");
        }
        return null;
    }, null);

    return Response.ok().build();
}
 
Example #17
Source File: RestUserConversationStore.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public UserConversation readUserConversation(String intent, String userId) {
    try {
        String cacheKey = calculateCacheKey(intent, userId);
        UserConversation userConversation = userConversationCache.get(cacheKey);
        if (userConversation == null) {
            userConversation = userConversationStore.readUserConversation(intent, userId);
            if (userConversation != null) {
                userConversationCache.put(cacheKey, userConversation);
            }
        }

        if (userConversation == null) {
            String message = "UserConversation with intent=%s and userId=%s does not exist.";
            message = String.format(message, intent, userId);
            throw new NotFoundException(message);
        }

        return userConversation;

    } catch (IResourceStore.ResourceStoreException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException(e.getLocalizedMessage());
    }
}
 
Example #18
Source File: JerseyHandlerFilter.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    Timer.start("JERSEY_FILTER_DOFILTER");
    // we use a latch to make the processing inside Jersey synchronous
    CountDownLatch jerseyLatch = new CountDownLatch(1);

    ContainerRequest req = servletRequestToContainerRequest(servletRequest);
    req.setWriter(new JerseyServletResponseWriter(servletResponse, jerseyLatch));

    req.setProperty(JERSEY_SERVLET_RESPONSE_PROPERTY, servletResponse);

    jersey.handle(req);
    try {
        jerseyLatch.await();
    } catch (InterruptedException e) {
        log.error("Interrupted while processing request", e);
        throw new InternalServerErrorException(e);
    }
    Timer.stop("JERSEY_FILTER_DOFILTER");
    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example #19
Source File: SellingTest.java    From robozonky with Apache License 2.0 6 votes vote down vote up
@Test
void noSaleDueToHttp500Error() {
    final Loan loan = MockLoanBuilder.fresh();
    final Investment i = mockInvestment(loan);
    final Zonky zonky = harmlessZonky();
    doThrow(InternalServerErrorException.class).when(zonky)
        .sell(any());
    when(zonky.getLoan(eq(loan.getId()))).thenReturn(loan);
    when(zonky.getInvestments(any())).thenAnswer(inv -> Stream.of(i));
    when(zonky.getSoldInvestments()).thenAnswer(inv -> Stream.empty());
    final PowerTenant tenant = mockTenant(zonky, false);
    when(tenant.getSellStrategy()).thenReturn(Optional.of(ALL_ACCEPTING_STRATEGY));
    final Selling s = new Selling();
    s.accept(tenant);
    final List<Event> e = getEventsRequested();
    assertThat(e).hasSize(3);
    assertSoftly(softly -> {
        softly.assertThat(e.get(0))
            .isInstanceOf(SellingStartedEvent.class);
        softly.assertThat(e.get(1))
            .isInstanceOf(SaleRecommendedEvent.class);
        softly.assertThat(e.get(2))
            .isInstanceOf(SellingCompletedEvent.class);
    });
    verify(zonky, times(1)).sell(argThat(inv -> i.getLoanId() == inv.getLoanId()));
}
 
Example #20
Source File: Selling.java    From robozonky with Apache License 2.0 6 votes vote down vote up
private static Optional<Investment> processSale(final PowerTenant tenant, final RecommendedInvestment r,
        final SoldParticipationCache sold) {
    final InvestmentDescriptor d = r.descriptor();
    final Investment i = d.item();
    final int loanId = i.getLoanId();
    try {
        final boolean isRealRun = !tenant.getSessionInfo()
            .isDryRun();
        if (isRealRun) {
            LOGGER.debug("Will send sell request for loan #{}.", loanId);
            var call = d.sellInfo()
                .map(sellInfo -> (Consumer<Zonky>) zonky -> zonky.sell(i, sellInfo))
                .orElseGet(() -> z -> z.sell(i));
            tenant.run(call);
        } else {
            LOGGER.debug("Will not send a real sell request for loan #{}, dry run.", loanId);
        }
        sold.markAsOffered(loanId);
        tenant.fire(EventFactory.saleOffered(i, d.related(), () -> tenant.getSellInfo(i.getId())));
        LOGGER.info("Offered to sell investment in loan #{}.", loanId);
        return Optional.of(i);
    } catch (final InternalServerErrorException ex) { // The sell endpoint has been seen to throw these.
        LOGGER.warn("Failed offering to sell investment in loan #{}.", loanId, ex);
        return Optional.empty();
    }
}
 
Example #21
Source File: RestPackageStore.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public List<DocumentDescriptor> readPackageDescriptors(String filter,
                                                       Integer index,
                                                       Integer limit,
                                                       String containingResourceUri,
                                                       Boolean includePreviousVersions) {

    if (validateUri(containingResourceUri) == null) {
        return createMalFormattedResourceUriException(containingResourceUri);
    }

    try {
        return packageStore.getPackageDescriptorsContainingResource(
                containingResourceUri,
                includePreviousVersions);
    } catch (IResourceStore.ResourceNotFoundException | IResourceStore.ResourceStoreException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException();
    }
}
 
Example #22
Source File: AuthenticatedProducerConsumerTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies: on 500 server error, broker invalidates session and client receives 500 correctly.
 *
 * @throws Exception
 */
@Test
public void testAuthenticationFilterNegative() throws Exception {
    log.info("-- Starting {} test --", methodName);

    Map<String, String> authParams = new HashMap<>();
    authParams.put("tlsCertFile", TLS_CLIENT_CERT_FILE_PATH);
    authParams.put("tlsKeyFile", TLS_CLIENT_KEY_FILE_PATH);
    Authentication authTls = new AuthenticationTls();
    authTls.configure(authParams);
    internalSetup(authTls);

    final String cluster = "test";
    final ClusterData clusterData = new ClusterData(brokerUrl.toString(), brokerUrlTls.toString(),
            pulsar.getBrokerServiceUrl(), pulsar.getBrokerServiceUrlTls());
    // this will cause NPE and it should throw 500
    doReturn(null).when(pulsar).getGlobalZkCache();
    try {
        admin.clusters().createCluster(cluster, clusterData);
    } catch (PulsarAdminException e) {
        Assert.assertTrue(e.getCause() instanceof InternalServerErrorException);
    }

    log.info("-- Exiting {} test --", methodName);
}
 
Example #23
Source File: MCRSessionFilter.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * If request was authenticated via JSON Web Token add a new token if <code>aud</code> was
 * {@link MCRRestAPIAuthentication#AUDIENCE}.
 *
 * If the response has a status code that represents a client error (4xx), the JSON Web Token is ommited.
 * If the response already has a JSON Web Token no changes are made.
 */
private static void addJWTToResponse(ContainerRequestContext requestContext,
    ContainerResponseContext responseContext) {
    MCRSession currentSession = MCRSessionMgr.getCurrentSession();
    boolean renewJWT = Optional.ofNullable(requestContext.getProperty(PROP_RENEW_JWT))
        .map(Boolean.class::cast)
        .orElse(Boolean.FALSE);
    Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.AUTHORIZATION))
        .filter(s -> s.startsWith("Bearer "))
        .filter(s -> !responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.CLIENT_ERROR))
        .filter(s -> responseContext.getHeaderString(HttpHeaders.AUTHORIZATION) == null)
        .map(h -> renewJWT ? ("Bearer " + MCRRestAPIAuthentication
            .getToken(currentSession.getUserInformation(), currentSession.getCurrentIP())
            .orElseThrow(() -> new InternalServerErrorException("Could not get JSON Web Token"))) : h)
        .ifPresent(h -> {
            responseContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, h);
            //Authorization header may never be cached in public caches
            Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.CACHE_CONTROL))
                .map(CacheControl::valueOf)
                .filter(cc -> !cc.isPrivate())
                .ifPresent(cc -> {
                    cc.setPrivate(true);
                    responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cc);
                });
        });
}
 
Example #24
Source File: MCRMetaDefaultListXMLWriter.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void writeTo(List<? extends MCRMetaDefault> mcrMetaDefaults, Class<?> type, Type genericType,
    Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
    OutputStream entityStream) throws IOException, WebApplicationException {
    Optional<String> wrapper = getWrapper(annotations);
    if (!wrapper.isPresent()) {
        throw new InternalServerErrorException("Could not get XML wrapping element from annotations.");
    }
    httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_TYPE);
    Element root = new Element(wrapper.get());
    root.addContent(mcrMetaDefaults.stream()
        .map(MCRMetaDefault::createXML)
        .collect(Collectors.toList()));
    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
    xout.output(root, entityStream);
}
 
Example #25
Source File: RestBotStore.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public Response duplicateBot(String id, Integer version, Boolean deepCopy) {
    validateParameters(id, version);
    BotConfiguration botConfiguration = restBotStore.readBot(id, version);
    if (deepCopy) {
        List<URI> packages = botConfiguration.getPackages();
        for (int i = 0; i < packages.size(); i++) {
            URI packageUri = packages.get(i);
            ResourceId resourceId = URIUtilities.extractResourceId(packageUri);
            Response duplicateResourceResponse = restPackageStore.
                    duplicatePackage(resourceId.getId(), resourceId.getVersion(), true);
            URI newResourceLocation = duplicateResourceResponse.getLocation();
            packages.set(i, newResourceLocation);
        }
    }

    try {
        Response createBotResponse = restBotStore.createBot(botConfiguration);
        createDocumentDescriptorForDuplicate(documentDescriptorStore, id, version, createBotResponse.getLocation());

        return createBotResponse;
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException();
    }
}
 
Example #26
Source File: RestVersionInfo.java    From EDDI with Apache License 2.0 5 votes vote down vote up
protected Response create(T document) {
    RuntimeUtilities.checkNotNull(document, "document");

    try {
        IResourceStore.IResourceId resourceId = resourceStore.create(document);
        URI createdUri = RestUtilities.createURI(resourceURI, resourceId.getId(), versionQueryParam, resourceId.getVersion());
        return Response.created(createdUri).location(createdUri).build();
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException();
    }
}
 
Example #27
Source File: PersonServiceWithJDBC.java    From microshed-testing with Apache License 2.0 5 votes vote down vote up
@GET
  public Collection<Person> getAllPeople(){
      Set<Person> allPeople = new HashSet<>();

try (Connection conn = defaultDataSource.getConnection();
	 ResultSet rs = conn.prepareStatement("SELECT name, age, id FROM people").executeQuery()){
	while (rs.next()) {
		allPeople.add(new Person(rs.getString("name"),rs.getInt("age"),rs.getLong("id")));
	}			
	return allPeople;
} catch (SQLException e) {
	e.printStackTrace(System.out);
} 
      throw new InternalServerErrorException("Could not get all people");  
  }
 
Example #28
Source File: RestUserConversationStore.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public Response deleteUserConversation(String intent, String userId) {
    try {
        userConversationStore.deleteUserConversation(intent, userId);
        userConversationCache.remove(calculateCacheKey(intent, userId));
        return Response.ok().build();
    } catch (IResourceStore.ResourceStoreException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException(e.getLocalizedMessage());
    }
}
 
Example #29
Source File: RestBotTriggerStore.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public Response deleteBotTrigger(String intent) {
    try {
        botTriggerStore.deleteBotTrigger(intent);
        botTriggersCache.remove(intent);
        return Response.ok().build();
    } catch (IResourceStore.ResourceStoreException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException(e.getLocalizedMessage());
    }
}
 
Example #30
Source File: RestUserStore.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public void updateUser(String userId, User user) {
    try {
        userStore.updateUser(userId, user);
    } catch (IResourceStore.ResourceStoreException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException();
    }
}