Java Code Examples for com.sun.jersey.api.client.ClientResponse#getStatus()

The following examples show how to use com.sun.jersey.api.client.ClientResponse#getStatus() . 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: AgentManagementServiceImpl.java    From Insights with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if vault and UI has same secrets and creates new version if difference
 * found.
 * 
 * @param agentId
 * @param vaultData
 * @param dataMap
 * @throws InsightsCustomException
 * @throws RuntimeException
 * @throws ClientHandlerException
 * @throws UniformInterfaceException
 */
private void updateVaultSecret(String agentId, JsonObject vaultData, Map<String, String> dataMap)
		throws InsightsCustomException {
	Gson gson = new Gson();
	JsonObject uidata = gson.toJsonTree(dataMap).getAsJsonObject();
	if (!dataMap.isEmpty() && !uidata.equals(vaultData)) {
		HashMap<String, Map<String, String>> updateMap = new HashMap<String, Map<String, String>>();
		updateMap.put("data", dataMap);
		ClientResponse updatedVaultResponse = storeToVault(updateMap, agentId);
		if (updatedVaultResponse.getStatus() != 200) {
			log.debug("updated vault response {} -- ", updatedVaultResponse);
			throw new InsightsCustomException("Failed : HTTP error code : " + updatedVaultResponse.getStatus());
		}
		updatedVaultResponse.getEntity(String.class);
	} else {
		log.debug("Secrets not modified !!");
	}
}
 
Example 2
Source File: JiraExporterTest.java    From rtc2jira with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testIsConfigured_serverNotOK(@Mocked ClientResponse clientResponse, @Mocked StorageEngine store)
    throws Exception {
  new Expectations() {
    {
      settings.hasJiraProperties();
      result = true;

      clientResponse.getStatus();
      result = Status.NOT_FOUND.getStatusCode();
    }
  };

  JiraExporter jiraExporter = JiraExporter.INSTANCE;

  try {
    jiraExporter.initialize(settings, store);
    Assert.fail("Exception should have been thrown");
  } catch (Exception e) {
  }
  boolean isConfigured = jiraExporter.isConfigured();
  assertEquals(true, isConfigured);
}
 
Example 3
Source File: YarnHttpClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteApplication(DeleteApplicationRequest deleteApplicationRequest) throws CloudbreakOrchestratorFailedException, MalformedURLException {

    // Add the application name to the URL
    YarnEndpoint dashEndpoint = new YarnEndpoint(apiEndpoint,
            YarnResourceConstants.APPLICATIONS_PATH
                    + '/' + deleteApplicationRequest.getName());

    ClientConfig clientConfig = new DefaultClientConfig();
    Client client = Client.create(clientConfig);

    // Delete the application
    WebResource webResource = client.resource(dashEndpoint.getFullEndpointUrl().toString());
    ClientResponse response = webResource.accept("application/json").type("application/json").delete(ClientResponse.class);

    // Validate HTTP 204 return
    String msg;
    switch (response.getStatus()) {
        case YarnResourceConstants.HTTP_NO_CONTENT:
            msg = String.format("Successfully deleted application %s", deleteApplicationRequest.getName());
            LOGGER.debug(msg);
            break;
        case YarnResourceConstants.HTTP_NOT_FOUND:
            msg = String.format("Application %s not found, already deleted?", deleteApplicationRequest.getName());
            LOGGER.debug(msg);
            break;
        default:
            msg = String.format("Received %d status code from url %s, reason: %s",
                    response.getStatus(),
                    dashEndpoint.getFullEndpointUrl().toString(),
                    response.getEntity(String.class));
            LOGGER.debug(msg);
            throw new CloudbreakOrchestratorFailedException(msg);
    }

}
 
Example 4
Source File: CompactionControlClient.java    From emodb with Apache License 2.0 5 votes vote down vote up
private RuntimeException convertException(UniformInterfaceException e) {
    ClientResponse response = e.getResponse();
    String exceptionType = response.getHeaders().getFirst("X-BV-Exception");

    if (response.getStatus() == Response.Status.BAD_REQUEST.getStatusCode() &&
            IllegalArgumentException.class.getName().equals(exceptionType)) {
        return new IllegalArgumentException(response.getEntity(String.class), e);
    }
    return e;
}
 
Example 5
Source File: NiFiClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
public List<String> getResources(ResourceLookupContext context) throws Exception {
    final WebResource resource = getWebResource();
    final ClientResponse response = getResponse(resource, "application/json");

    if (Response.Status.OK.getStatusCode() != response.getStatus()) {
        String errorMsg = IOUtils.toString(response.getEntityInputStream());
        throw new Exception("Unable to retrieve resources from NiFi due to: " + errorMsg);
    }

    JsonNode rootNode = mapper.readTree(response.getEntityInputStream());
    if (rootNode == null) {
        throw new Exception("Unable to retrieve resources from NiFi");
    }

    JsonNode resourcesNode = rootNode.findValue("resources");
    List<String> identifiers = resourcesNode.findValuesAsText("identifier");

    final String userInput = context.getUserInput();
    if (StringUtils.isBlank(userInput)) {
        return identifiers;
    } else {
        List<String> filteredIdentifiers = new ArrayList<>();

        for (String identifier : identifiers) {
            if (identifier.contains(userInput)) {
                filteredIdentifiers.add(identifier);
            }
        }

        return filteredIdentifiers;
    }
}
 
Example 6
Source File: WebServiceClient.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
public boolean isAuthorized(int timeout) throws WebServiceException {
	
	this.timeout = timeout;  
	ClientResponse response = createRootResource().path("storage").get(ClientResponse.class);
	// use timeout just for isAuthorized
	this.timeout = UNDEFINED;
	
	if (response.getStatus() == 401) {
		return false;
	}
	
	checkForException(response);
	
	return true;
}
 
Example 7
Source File: JMasarJerseyClient.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private ClientResponse getCall(String relativeUrl){
    WebResource webResource = client.resource(jmasarServiceUrl + relativeUrl);

    ClientResponse response = webResource.accept(CONTENT_TYPE_JSON).get(ClientResponse.class);
    if (response.getStatus() != 200) {
        String message = response.getEntity(String.class);
        throw new DataProviderException("Failed : HTTP error code : " + response.getStatus() + ", error message: " + message);
    }

    return response;
}
 
Example 8
Source File: JiraUserManager.java    From rtc2jira with GNU General Public License v2.0 5 votes vote down vote up
public void deactivateUser(JiraUser jiraUser) {
  jiraUser.setActive(false);
  ClientResponse putResponse =
      getRestAccess().delete(
          "/group/user?groupname=" + BASIC_JIRA_USER_GROUP_NAME + "&username=" + jiraUser.getName());
  if (putResponse.getStatus() != 200) {
    LOGGER.log(Level.SEVERE, "Problems while removing user " + jiraUser.getEmailAddress()
        + "  from jira-users group. " + putResponse.getEntity(String.class));
  }
}
 
Example 9
Source File: YarnHttpClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteApplication(DeleteApplicationRequest deleteApplicationRequest) throws YarnClientException, MalformedURLException {

    // Add the application name to the URL
    YarnEndpoint dashEndpoint = new YarnEndpoint(apiEndpoint,
            YarnResourceConstants.APPLICATIONS_PATH
                    + '/' + deleteApplicationRequest.getName());

    ClientConfig clientConfig = new DefaultClientConfig();
    Client client = Client.create(clientConfig);

    // Delete the application
    WebResource webResource = client.resource(dashEndpoint.getFullEndpointUrl().toString());
    ClientResponse response = webResource.accept("application/json").type("application/json").delete(ClientResponse.class);

    // Validate HTTP 204 return
    String msg;
    switch (response.getStatus()) {
        case YarnResourceConstants.HTTP_NO_CONTENT:
            msg = String.format("Successfully deleted application %s", deleteApplicationRequest.getName());
            LOGGER.debug(msg);
            break;
        case YarnResourceConstants.HTTP_NOT_FOUND:
            msg = String.format("Application %s not found, already deleted?", deleteApplicationRequest.getName());
            LOGGER.debug(msg);
            break;
        default:
            msg = String.format("Received %d status code from url %s, reason: %s",
                    response.getStatus(),
                    dashEndpoint.getFullEndpointUrl().toString(),
                    response.getEntity(String.class));
            LOGGER.debug(msg);
            throw new YarnClientException(msg);
    }

}
 
Example 10
Source File: RestServerTest.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateDelete() throws Exception {
    SyncConfig syncConfig = new SyncConfig();
    syncConfig.setSource(new TestConfig().withObjectCount(10).withMaxSize(10240).withDiscardData(false));
    syncConfig.setTarget(new TestConfig().withReadData(true).withDiscardData(false));

    // create sync job
    ClientResponse response = client.resource(endpoint).path("/job").type(XML).put(ClientResponse.class, syncConfig);
    String jobIdStr = response.getHeaders().getFirst("x-emc-job-id");
    try {
        Assert.assertEquals(response.getEntity(String.class), 201, response.getStatus());
        response.close(); // must close all responses

        Assert.assertNotNull(jobIdStr);
        int jobId = Integer.parseInt(jobIdStr);

        // wait for job to complete
        while (!client.resource(endpoint).path("/job/" + jobId + "/control").get(JobControl.class).getStatus().isFinalState()) {
            Thread.sleep(1000);
        }

        // get status (should be complete)
        JobControl jobControl = client.resource(endpoint).path("/job/" + jobId + "/control").get(JobControl.class);
        Assert.assertNotNull(jobControl);
        Assert.assertEquals(JobControlStatus.Complete, jobControl.getStatus());
    } finally {
        // delete job
        response = client.resource(endpoint).path("/job/" + jobIdStr).delete(ClientResponse.class);
        if (response.getStatus() != 200)
            log.warn("could not delete job: {}", response.getEntity(String.class));
        response.close(); // must close all responses
    }
}
 
Example 11
Source File: EcsSyncCtl.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
private void delete(int jobId) {
    String uri = String.format("%s/job/%d?keepDatabase=true", endpoint, jobId);
    ClientResponse resp = client.resource(uri).delete(ClientResponse.class);

    if(resp.getStatus() == 404) {
        System.out.println("No job running");
        System.exit(EXIT_NO_JOB);
    } else if(resp.getStatus() == 200) {
        System.out.println("Job deleted");
        System.exit(EXIT_SUCCESS);
    } else {
        System.err.printf("Error deleting job: HTTP %d: %s", resp.getStatus(), resp.getStatusInfo().getReasonPhrase());
        System.exit(EXIT_UNKNOWN_ERROR);
    }
}
 
Example 12
Source File: ReplicationClient.java    From emodb with Apache License 2.0 5 votes vote down vote up
private RuntimeException convertException(UniformInterfaceException e) {
    ClientResponse response = e.getResponse();
    String exceptionType = response.getHeaders().getFirst("X-BV-Exception");

    if (response.getStatus() == Response.Status.BAD_REQUEST.getStatusCode() &&
            IllegalArgumentException.class.getName().equals(exceptionType)) {
        return new IllegalArgumentException(response.getEntity(String.class), e);
    }
    return e;
}
 
Example 13
Source File: LdapPolicyMgrUserGroupBuilder.java    From ranger with Apache License 2.0 4 votes vote down vote up
private String tryGetEntityWithCookie(String apiURL, int retrievedCount) {
	if (LOG.isDebugEnabled()) {
		LOG.debug("==> LdapPolicyMgrUserGroupBuilder.tryGetEntityWithCookie()");
	}
	String response = null;
	ClientResponse clientResp = null;

	Map<String, String> queryParams = new HashMap<String, String>();
	queryParams.put("pageSize", recordsToPullPerCall);
	queryParams.put("startIndex", String.valueOf(retrievedCount));
	try {
		clientResp = ldapUgSyncClient.get(apiURL, queryParams, sessionId);
	}
	catch(Throwable t){
		LOG.error("Failed to get response, Error is : ", t);
	}
	if (clientResp != null) {
		if (!(clientResp.toString().contains(apiURL))) {
			clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND);
			sessionId = null;
			isValidRangerCookie = false;
		} else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
			sessionId = null;
			isValidRangerCookie = false;
		} else if (clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT || clientResp.getStatus() == HttpServletResponse.SC_OK) {
			List<NewCookie> respCookieList = clientResp.getCookies();
			for (NewCookie cookie : respCookieList) {
				if (cookie.getName().equalsIgnoreCase(rangerCookieName)) {
					if (!(sessionId.getValue().equalsIgnoreCase(cookie.toCookie().getValue()))) {
						sessionId = cookie.toCookie();
					}
					isValidRangerCookie = true;
					break;
				}
			}
		}

		if (clientResp.getStatus() != HttpServletResponse.SC_OK	&& clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT
				&& clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
			sessionId = null;
			isValidRangerCookie = false;
		}
		clientResp.bufferEntity();
		response = clientResp.getEntity(String.class);
	}
	if (LOG.isDebugEnabled()) {
		LOG.debug("<== LdapPolicyMgrUserGroupBuilder.tryGetEntityWithCookie()");
	}
	return response;
}
 
Example 14
Source File: StartMojo.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws MojoExecutionException {
    initCertStore();

    /** First check that the runner.jar is ready and up-to-date */
    if ( ! isReadyToDeploy() ) {
        LOG.info( "{} is NOT present, calling chop:runner goal now...", RUNNER_JAR );
        RunnerMojo runnerMojo = new RunnerMojo( this );
        runnerMojo.execute();
    }
    if ( ! isReadyToDeploy() ) {
        throw new MojoExecutionException( "Runner file was not ready and chop:runner failed" );
    }

    Properties props = new Properties();
    try {
        File extractedConfigPropFile = new File( getExtractedRunnerPath(), PROJECT_FILE );
        FileInputStream inputStream = new FileInputStream( extractedConfigPropFile );
        props.load( inputStream );
        inputStream.close();
    }
    catch ( Exception e ) {
        LOG.error( "Error while reading project.properties in runner.jar", e );
        throw new MojoExecutionException( e.getMessage() );
    }

    /** Start tests TODO use chop-client module to talk to the coordinator */
    DefaultClientConfig clientConfig = new DefaultClientConfig();
    Client client = Client.create( clientConfig );
    WebResource resource = client.resource( endpoint ).path( "/start" );

    LOG.info( "Commit ID: {}", props.getProperty( Project.GIT_UUID_KEY ) );
    LOG.info( "Artifact Id: {}", props.getProperty( Project.ARTIFACT_ID_KEY ) );
    LOG.info( "Group Id: {}", props.getProperty( Project.GROUP_ID_KEY ) );
    LOG.info( "Version: {}", props.getProperty( Project.PROJECT_VERSION_KEY ) );
    LOG.info( "Username: {}", username );

    ClientResponse resp = resource
            .queryParam( RestParams.COMMIT_ID, props.getProperty( Project.GIT_UUID_KEY ) )
            .queryParam( RestParams.MODULE_ARTIFACTID, props.getProperty( Project.ARTIFACT_ID_KEY ) )
            .queryParam( RestParams.MODULE_GROUPID, props.getProperty( Project.GROUP_ID_KEY ) )
            .queryParam( RestParams.MODULE_VERSION, props.getProperty( Project.PROJECT_VERSION_KEY ) )
            .queryParam( RestParams.USERNAME, username )
            .type( MediaType.APPLICATION_JSON )
            .accept( MediaType.APPLICATION_JSON )
            .post( ClientResponse.class );

    if( resp.getStatus() != Response.Status.OK.getStatusCode() &&
            resp.getStatus() != Response.Status.CREATED.getStatusCode() ) {
        LOG.error( "Could not get the status from coordinator, HTTP status: {}", resp.getStatus() );
        LOG.error( "Error Message: {}", resp.getEntity( String.class ) );

        throw new MojoExecutionException( "Start plugin goal has failed" );
    }

    String result = resp.getEntity( String.class );

    // In case tests are stopped by the user, reset them automatically
    if ( result.contains( "is in " + State.STOPPED + " state" ) ) {
        LOG.info( "Resetting the runners before starting..." );
        ResetMojo resetMojo = new ResetMojo( this );
        resetMojo.execute();
        this.execute();
    }
    else {
        LOG.info( "====== Response from the coordinator ======" );
        LOG.info( "Coordinator message: {}", result );
        LOG.info( "===========================================" );
    }

}
 
Example 15
Source File: JiraExporter.java    From rtc2jira with GNU General Public License v2.0 4 votes vote down vote up
private boolean isResponseOk(ClientResponse cr) {
  return cr.getStatus() >= Status.OK.getStatusCode() && cr.getStatus() <= Status.PARTIAL_CONTENT.getStatusCode();
}
 
Example 16
Source File: ScalingServiceMgr.java    From open-Autoscaler with Apache License 2.0 4 votes vote down vote up
private JSONObject registerAppWithServer(String appId, String serviceId, String bindingId , String serverUrl) throws ScalingServerFailureException {

        String registerUrl = serverUrl + Constants.REGISTER_APP_URL;

        JSONObject registerJSON = new JSONObject();
        registerJSON.put("appId", appId);
        registerJSON.put("serviceId", serviceId);
        registerJSON.put("bindingId", bindingId);
        registerJSON.put("agentUsername", "agent");
        registerJSON.put("agentPassword", UUID.randomUUID().toString());
        
        ServiceInstance serviceInstance = dataService.getServiceInstanceByServiceId(serviceId);
        if (serviceInstance != null) {
        	if (serviceInstance.getOrgId() != null 	&& !serviceInstance.getOrgId().isEmpty()) {
        		registerJSON.put("orgId", serviceInstance.getOrgId());
        	}

        	if (serviceInstance.getSpaceId() != null && !serviceInstance.getSpaceId().isEmpty()) {
        		registerJSON.put("spaceId", serviceInstance.getSpaceId());
        	}
        }

        logger.info("registerUrl is  " + registerUrl + " with appId " + appId);
        logger.info("registerJSON is  " + registerJSON.toString());

        String authorization = ConfigManager.getInternalAuthToken();
        ClientResponse response  = restClient.resource(registerUrl)
        		.header("Authorization", "Basic " + authorization)
    			.type(MediaType.APPLICATION_JSON)
    			.post(ClientResponse.class, registerJSON.toString());
        
        int responseCode = response.getStatus();
        if (responseCode == 201) {
            JSONObject credentials = new JSONObject();
            credentials.put("url", serverUrl);
            credentials.put("app_id", appId);
            credentials.put("service_id", serviceId);
            credentials.put("agentUsername", registerJSON.get("agentUsername"));
            credentials.put("agentPassword", registerJSON.get("agentPassword"));
            credentials.put("api_url", getAPIServiceUrl());
            return credentials;
        } else { 
        	  //handle failure
              String jsonResponse = response.getEntity(String.class);
              logger.error("bind failed for service  " + serviceId + " appId " + appId + 
            		  " with error returned from service side with code " +  responseCode + ", reason " + jsonResponse);
              String errorMsg = null;
              try {
            	  JSONObject jsonObject = new JSONObject(jsonResponse);
            	  errorMsg = (String) jsonObject.get("error");
              } catch (JSONException e) {
            	  errorMsg = jsonResponse;
              }
              throw new ScalingServerFailureException(errorMsg);
        } 
    }
 
Example 17
Source File: DestroyMojo.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws MojoExecutionException {
    initCertStore();

    /** First check that the runner.jar is ready and up-to-date */
    if ( ! isReadyToDeploy() ) {
        throw new MojoExecutionException( "Runner file was not ready, quitting." );
    }

    Properties props = new Properties();
    try {
        File extractedConfigPropFile = new File( getExtractedRunnerPath(), PROJECT_FILE );
        FileInputStream inputStream = new FileInputStream( extractedConfigPropFile );
        props.load( inputStream );
        inputStream.close();
    }
    catch ( Exception e ) {
        LOG.error( "Error while reading project.properties in runner.jar", e );
        throw new MojoExecutionException( e.getMessage() );
    }

    /** Destroy stack TODO use chop-client module to talk to the coordinator */
    DefaultClientConfig clientConfig = new DefaultClientConfig();
    Client client = Client.create( clientConfig );
    WebResource resource = client.resource( endpoint ).path( "/destroy" );

    LOG.info( "Commit ID: {}", props.getProperty( Project.GIT_UUID_KEY ) );
    LOG.info( "Artifact Id: {}", props.getProperty( Project.ARTIFACT_ID_KEY ) );
    LOG.info( "Group Id: {}", props.getProperty( Project.GROUP_ID_KEY ) );
    LOG.info( "Version: {}", props.getProperty( Project.PROJECT_VERSION_KEY ) );
    LOG.info( "Username: {}", username );

    ClientResponse resp = resource.path( "/stack" )
            .queryParam( RestParams.COMMIT_ID, props.getProperty( Project.GIT_UUID_KEY ) )
            .queryParam( RestParams.MODULE_ARTIFACTID, props.getProperty( Project.ARTIFACT_ID_KEY ) )
            .queryParam( RestParams.MODULE_GROUPID, props.getProperty( Project.GROUP_ID_KEY ) )
            .queryParam( RestParams.MODULE_VERSION, props.getProperty( Project.PROJECT_VERSION_KEY ) )
            .queryParam( RestParams.USERNAME, username )
            .type( MediaType.APPLICATION_JSON )
            .accept( MediaType.APPLICATION_JSON )
            .post( ClientResponse.class );

    if( resp.getStatus() != Response.Status.OK.getStatusCode() &&
            resp.getStatus() != Response.Status.CREATED.getStatusCode() ) {
        LOG.error( "Could not get the status from coordinator, HTTP status: {}", resp.getStatus() );
        LOG.error( "Error Message: {}", resp.getEntity( String.class ) );

        throw new MojoExecutionException( "Destroy plugin goal has failed" );
    }

    LOG.info( "====== Response from the coordinator ======" );
    LOG.info( resp.getEntity( String.class ) );
    LOG.info( "===========================================" );
}
 
Example 18
Source File: ViolationSubscriber.java    From SeaCloudsPlatform with Apache License 2.0 4 votes vote down vote up
private boolean isOk(ClientResponse response) {
    
    return response.getStatus() == Response.Status.CREATED.getStatusCode() ||
            response.getStatus() == Response.Status.OK.getStatusCode();
}
 
Example 19
Source File: YandexTranslate.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final StopWatch stopWatch = new StopWatch(true);
    final String key = context.getProperty(KEY).getValue();
    final String sourceLanguage = context.getProperty(SOURCE_LANGUAGE).evaluateAttributeExpressions(flowFile).getValue();
    final String targetLanguage = context.getProperty(TARGET_LANGUAGE).evaluateAttributeExpressions(flowFile).getValue();
    final String encoding = context.getProperty(CHARACTER_SET).evaluateAttributeExpressions(flowFile).getValue();

    final List<String> attributeNames = new ArrayList<>();
    final List<String> textValues = new ArrayList<>();
    for (final PropertyDescriptor descriptor : context.getProperties().keySet()) {
        if (descriptor.isDynamic()) {
            attributeNames.add(descriptor.getName()); // add to list so that we know the order when the translations come back.
            textValues.add(context.getProperty(descriptor).evaluateAttributeExpressions(flowFile).getValue());
        }
    }

    if (context.getProperty(TRANSLATE_CONTENT).asBoolean()) {
        final byte[] buff = new byte[(int) flowFile.getSize()];
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(final InputStream in) throws IOException {
                StreamUtils.fillBuffer(in, buff);
            }
        });
        final String content = new String(buff, Charset.forName(encoding));
        textValues.add(content);
    }

    final WebResource.Builder builder = prepareResource(key, textValues, sourceLanguage, targetLanguage);

    final ClientResponse response;
    try {
        response = builder.post(ClientResponse.class);
    } catch (final Exception e) {
        getLogger().error("Failed to make request to Yandex to transate text for {} due to {}; routing to comms.failure", new Object[]{flowFile, e});
        session.transfer(flowFile, REL_COMMS_FAILURE);
        return;
    }

    if (response.getStatus() != Status.OK.getStatusCode()) {
        getLogger().error("Failed to translate text using Yandex for {}; response was {}: {}; routing to {}", new Object[]{
            flowFile, response.getStatus(), response.getStatusInfo().getReasonPhrase(), REL_TRANSLATION_FAILED.getName()});
        flowFile = session.putAttribute(flowFile, "yandex.translate.failure.reason", response.getStatusInfo().getReasonPhrase());
        session.transfer(flowFile, REL_TRANSLATION_FAILED);
        return;
    }

    final Map<String, String> newAttributes = new HashMap<>();
    final Translation translation = response.getEntity(Translation.class);
    final List<String> texts = translation.getText();
    for (int i = 0; i < texts.size(); i++) {
        final String text = texts.get(i);
        if (i < attributeNames.size()) {
            final String attributeName = attributeNames.get(i);
            newAttributes.put(attributeName, text);
        } else {
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(final OutputStream out) throws IOException {
                    out.write(text.getBytes(encoding));
                }
            });

            newAttributes.put("language", targetLanguage);
        }
    }

    if (!newAttributes.isEmpty()) {
        flowFile = session.putAllAttributes(flowFile, newAttributes);
    }

    stopWatch.stop();
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Successfully translated {} items for {} from {} to {} in {}; routing to success",
            new Object[]{texts.size(), flowFile, sourceLanguage, targetLanguage, stopWatch.getDuration()});
}
 
Example 20
Source File: AgentManagementServiceImpl.java    From Insights with Apache License 2.0 3 votes vote down vote up
/**
 * Prepare vault based structure and store in vault.
 * 
 * @param agentId
 * @param json
 * @return
 * @throws InsightsCustomException
 * @throws RuntimeException
 * @throws ClientHandlerException
 * @throws UniformInterfaceException
 * @throws IOException
 */
private HashMap<String, Map<String, String>> prepareSecret(String agentId, JsonObject json)
		throws InsightsCustomException, IOException {
	HashMap<String, Map<String, String>> dataMap = getToolbasedSecret(json, agentId);
	ClientResponse vaultresponse = storeToVault(dataMap, agentId);
	if (vaultresponse.getStatus() != 200) {
		log.debug("vault response {} -- ", vaultresponse);
		throw new InsightsCustomException("Failed : HTTP error code : " + vaultresponse.getStatus());
	}
	vaultresponse.getEntity(String.class);
	return dataMap;
}