javax.ws.rs.NotSupportedException#javax.ws.rs.InternalServerErrorException源码实例Demo

下面列出了javax.ws.rs.NotSupportedException#javax.ws.rs.InternalServerErrorException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: microshed-testing   文件: PersonServiceWithJDBC.java
@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");    
  }
 
源代码2 项目: microshed-testing   文件: PersonServiceWithJDBC.java
@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");   
  }
 
@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");    
  }
 
源代码4 项目: ballerina-message-broker   文件: ExchangesApi.java
@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);
    }
}
 
源代码5 项目: Web-API   文件: CacheService.java
/**
 * 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);
    }
}
 
源代码6 项目: ballerina-message-broker   文件: QueuesApi.java
@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);
    }
}
 
源代码7 项目: dremio-oss   文件: UserStatsResource.java
@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);
  }
}
 
源代码8 项目: mycore   文件: MCRContentAbstractWriter.java
@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);
    }
}
 
源代码9 项目: mycore   文件: MCRMetaDefaultListXMLWriter.java
@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);
}
 
源代码10 项目: mycore   文件: MCRSessionFilter.java
/**
 * 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);
                });
        });
}
 
源代码11 项目: pulsar   文件: AuthenticatedProducerConsumerTest.java
/**
 * 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);
}
 
源代码12 项目: robozonky   文件: Selling.java
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();
    }
}
 
源代码13 项目: robozonky   文件: SellingTest.java
@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()));
}
 
@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);
}
 
源代码15 项目: EDDI   文件: FacebookEndpoint.java
@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();
}
 
源代码16 项目: Web-API   文件: WebAPI.java
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());
        }
    }
}
 
源代码17 项目: EDDI   文件: RestUserConversationStore.java
@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());
    }
}
 
源代码18 项目: EDDI   文件: RestPackageStore.java
@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();
    }
}
 
源代码19 项目: EDDI   文件: RestBotStore.java
@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();
    }
}
 
源代码20 项目: EDDI   文件: RestConversationStore.java
@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();
    }
}
 
源代码21 项目: EDDI   文件: RestImportService.java
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());
                }
            });
}
 
源代码22 项目: EDDI   文件: RestGitBackupService.java
@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();
}
 
源代码23 项目: EDDI   文件: RestBotAdministration.java
@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);
    }
}
 
源代码24 项目: EDDI   文件: RestBotAdministration.java
@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);
    }
}
 
源代码25 项目: EDDI   文件: RestBotAdministration.java
@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);
    }
}
 
源代码26 项目: microshed-testing   文件: PersonServiceWithJDBC.java
@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");  
  }
 
源代码27 项目: microshed-testing   文件: PersonServiceWithJDBC.java
@GET
  @Path("/{personId}")
  public Person getPerson(@PathParam("personId") long id) {
      try (Connection conn = defaultDataSource.getConnection();
	 ResultSet rs = conn.prepareStatement("SELECT name, age FROM people WHERE id = "+id).executeQuery()){
	if (rs.next()) {
		return new Person(rs.getString("name"),rs.getInt("age"),id);
	}			
	throw new NotFoundException("Person with id " + id + " not found.");
} catch (SQLException e) {
	e.printStackTrace(System.out);
}
throw new InternalServerErrorException("Could not get person");  
  }
 
源代码28 项目: microshed-testing   文件: PersonServiceWithJDBC.java
@DELETE
  @Path("/{personId}")
  public void removePerson(@PathParam("personId") long id) {
      try (Connection conn = defaultDataSource.getConnection();
	 PreparedStatement ps = conn.prepareStatement("DELETE FROM people WHERE id = ?")){
	ps.setLong(1,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 delete person"); 
  }
 
源代码29 项目: quarkus   文件: TenantLogout.java
@GET
@Path("post-logout")
public String postLogout(@QueryParam("state") String postLogoutState) {
    Cookie cookie = headers.getCookies().get("q_post_logout_tenant-logout");
    if (cookie == null) {
        throw new InternalServerErrorException("q_post_logout cookie is not available");
    }
    if (postLogoutState == null) {
        throw new InternalServerErrorException("'state' query parameter is not available");
    }
    if (!postLogoutState.equals(cookie.getValue())) {
        throw new InternalServerErrorException("'state' query parameter is not equal to the q_post_logout cookie value");
    }
    return "You were logged out";
}
 
@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");  
  }