List of usage examples for org.apache.commons.io IOUtils toInputStream
public static InputStream toInputStream(String input)
From source file:com.elasticbox.jenkins.k8s.services.TestSlaveProvisioningFailing.java
@Test(expected = ServiceException.class) public void testSlaveProvisioningWithoutLabelAndItNeverGetsOnline() throws Exception { final KubernetesCloud mockKubernetesCloud = Mockito.mock(KubernetesCloud.class); when(mockKubernetesCloud.getInstanceCap()).thenReturn(10); when(mockKubernetesCloud.getName()).thenReturn("FakeCloudName"); when(mockKubernetesCloud.getNamespace()).thenReturn("FakeNamespace"); final String podYamlDefault = getPodYamlDefault(); final PodSlaveConfig fakePodSlaveConfig = getFakePodSlaveConfig(podYamlDefault); List<PodSlaveConfig> podSlaveConfigurations = new ArrayList<>(); podSlaveConfigurations.add(fakePodSlaveConfig); final Pod pod = new DefaultKubernetesClient().pods().inNamespace(mockKubernetesCloud.getNamespace()) .load(IOUtils.toInputStream(fakePodSlaveConfig.getPodYaml())).get(); pod.setStatus(new PodStatus(null, null, null, null, "Running", null, null, null)); final PodRepository podRepository = injector.getInstance(PodRepository.class); when(podRepository.getPod(anyString(), anyString(), anyString())).thenReturn(pod); when(podRepository.pod(anyString(), anyString(), anyString())).thenReturn(pod); doNothing().when(podRepository).create(anyString(), anyString(), any(Pod.class)); final List<PodSlaveConfigurationParams> podSlaveConfigurationParams = new ArrayList<>(); for (PodSlaveConfig config : podSlaveConfigurations) { podSlaveConfigurationParams.add(config.getPodSlaveConfigurationParams()); }//from w w w. ja v a2s. c o m final SlaveProvisioningService slaveProvisioningService = injector .getInstance(SlaveProvisioningService.class); slaveProvisioningService.slaveProvision(mockKubernetesCloud, podSlaveConfigurationParams, null); }
From source file:com.telefonica.euro_iaas.paasmanager.dao.sdc.impl.ProductReleaseSdcDaoImplTest.java
/** * Tests the findAllProducts functionality * //ww w . jav a 2 s.c o m * @throws SdcException */ @Test public void testFindAllProductReleasesOfaProduct() throws SdcException { // given String productReleasesList = "{\"productRelease\":{\"releaseNotes\":\"Tomcat server 6\",\"version\":\"6\",\"product\":{\"name\":\"tomcat\",\"description\":\"tomcat J2EE container\",\"attributes\":{\"key\":\"clave\",\"value\":\"valor\"}},\"supportedOOSS\":[{\"description\":\"Ubuntu 10.04\",\"name\":\"Ubuntu\",\"osType\":\"94\",\"version\":\"10.04\"},{\"description\":\"Debian 5\",\"name\":\"Debian\",\"osType\":\"95\",\"version\":\"5\"},{\"description\":\"Centos 2.9\",\"name\":\"Centos\",\"osType\":\"76\",\"version\":\"2.9\"}]}}"; InputStream inputStream = IOUtils.toInputStream(productReleasesList); when(builder.get(InputStream.class)).thenReturn(inputStream); List<ProductRelease> productReleases = productReleaseSdcDaoImpl.findAllProductReleasesOfProduct("tomcat", "token", "tenant"); // then assertNotNull(productReleases); assertEquals(1, productReleases.size()); }
From source file:info.magnolia.repository.DefaultRepositoryManager.java
private void loadRepositories() throws Exception { final String path = SystemProperty.getProperty(SystemProperty.MAGNOLIA_REPOSITORIES_CONFIG); if (path == null) { throw new RepositoryNotInitializedException("No value found for property " + SystemProperty.MAGNOLIA_REPOSITORIES_CONFIG + ": can not start repository."); }/*from w w w . ja v a2 s . c om*/ final String tokenizedConfig = ConfigUtil.getTokenizedConfigFile(path); InputStream stream = IOUtils.toInputStream(tokenizedConfig); RepositoryMappingDefinitionReader reader = new RepositoryMappingDefinitionReader(); RepositoryMappingDefinition mapping = reader.read(stream); for (RepositoryDefinition repositoryDefinition : mapping.getRepositories()) { if (repositoryDefinition.getWorkspaces().isEmpty()) { repositoryDefinition.addWorkspace("default"); } workspaceMapping.addRepositoryDefinition(repositoryDefinition); loadRepository(repositoryDefinition); } for (WorkspaceMappingDefinition workspaceMapping : mapping.getWorkspaceMappings()) { this.workspaceMapping.addWorkspaceMappingDefinition(workspaceMapping); } }
From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java
protected static InputStream getJsonPropertyValue(final InputStream src, final String name) throws Exception { ObjectMapper mapper = new ObjectMapper(); final JsonNode srcNode = mapper.readTree(src); JsonNode node = getJsonProperty(srcNode, new String[] { name }, 0); return IOUtils.toInputStream(node.asText()); }
From source file:com.google.code.jerseyclients.httpclientfour.ApacheHttpClientFourHandler.java
public ClientResponse handle(final ClientRequest clientRequest) throws ClientHandlerException { if (this.jerseyHttpClientConfig.getApplicationCode() != null) { clientRequest.getHeaders().add(this.jerseyHttpClientConfig.getApplicationCodeHeader(), this.jerseyHttpClientConfig.getApplicationCode()); }//from w w w.ja v a 2s . c om if (this.jerseyHttpClientConfig.getOptionnalHeaders() != null) { for (Entry<String, String> entry : this.jerseyHttpClientConfig.getOptionnalHeaders().entrySet()) { clientRequest.getHeaders().add(entry.getKey(), entry.getValue()); } } // final Map<String, Object> props = cr.getProperties(); final HttpRequestBase method = getHttpMethod(clientRequest); // Set the read timeout final Integer readTimeout = jerseyHttpClientConfig.getReadTimeOut(); if (readTimeout != null) { HttpConnectionParams.setSoTimeout(method.getParams(), readTimeout.intValue()); } // FIXME penser au header http // DEBUG|wire.header|>> "Cache-Control: no-cache[\r][\n]" // DEBUG|wire.header|>> "Pragma: no-cache[\r][\n]" if (method instanceof HttpEntityEnclosingRequestBase) { final HttpEntityEnclosingRequestBase entMethod = (HttpEntityEnclosingRequestBase) method; if (clientRequest.getEntity() != null) { final RequestEntityWriter re = getRequestEntityWriter(clientRequest); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { re.writeRequestEntity(new CommittingOutputStream(baos) { @Override protected void commit() throws IOException { writeOutBoundHeaders(clientRequest.getHeaders(), method); } }); } catch (IOException ex) { throw new ClientHandlerException(ex); } final byte[] content = baos.toByteArray(); HttpEntity httpEntity = new ByteArrayEntity(content); entMethod.setEntity(httpEntity); } } else { writeOutBoundHeaders(clientRequest.getHeaders(), method); } try { StopWatch stopWatch = new StopWatch(); stopWatch.reset(); stopWatch.start(); HttpResponse httpResponse = client.execute(method); int httpReturnCode = httpResponse.getStatusLine().getStatusCode(); stopWatch.stop(); log.info("time to call rest url " + clientRequest.getURI() + ", " + stopWatch.getTime() + " ms"); if (httpReturnCode == Status.NO_CONTENT.getStatusCode()) { return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse), IOUtils.toInputStream(""), getMessageBodyWorkers()); } return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse), httpResponse.getEntity() == null ? IOUtils.toInputStream("") : httpResponse.getEntity().getContent(), getMessageBodyWorkers()); } catch (Exception e) { throw new ClientHandlerException(e); } }
From source file:eu.openanalytics.rsb.RestAdminITCase.java
@Test public void putCatalogFile() throws Exception { final String testFileName = "fake-" + RandomStringUtils.randomAlphanumeric(20) + ".R"; WebConversation wc = new WebConversation(); WebRequest request = new PutMethodWebRequest( RSB_BASE_URI + "/api/rest/admin/catalog/R_SCRIPTS/" + testFileName, IOUtils.toInputStream("fake R script content for " + testFileName), "text/plain"); WebResponse response = wc.sendRequest(request); assertEquals(201, response.getResponseCode()); assertTrue(StringUtils.isNotBlank(response.getHeaderField("Location"))); SuiteITCase.registerCreatedCatalogFile(CatalogSection.R_SCRIPTS, testFileName); wc = new WebConversation(); request = new PutMethodWebRequest(RSB_BASE_URI + "/api/rest/admin/catalog/R_SCRIPTS/" + testFileName, IOUtils.toInputStream("fake R script replacement content for " + testFileName), "text/plain"); response = wc.sendRequest(request);/* w ww .ja v a2 s . c o m*/ assertEquals(204, response.getResponseCode()); assertTrue(StringUtils.isBlank(response.getHeaderField("Location"))); }
From source file:info.magnolia.cms.util.ConfigUtil.java
/** * Uses a map to find the dtds in the resources. * @deprecated since 4.0 - not used/*from w ww. j ava2 s . com*/ */ public static org.jdom.Document string2JDOM(String xml, final Map dtds) throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder(); builder.setEntityResolver(new MapDTDEntityResolver(dtds)); return builder.build(IOUtils.toInputStream(xml)); }
From source file:ee.ria.xroad.asyncdb.AsyncDBIntegrationTest.java
private static void addRequestToExistentProvider() throws Exception { LOG.info("TEST 2: addRequestToExistentProvider - STARTED"); SoapMessageImpl requestMessage = AsyncDBTestUtil.getSecondSoapRequest(); String contentType = "application/json"; String attachmentContent = "{name:'Vitali'}"; InputStream attachmentIS = IOUtils.toInputStream(attachmentContent); WritingCtx writingCtx = queue.startWriting(); SoapMessageConsumer consumer = writingCtx.getConsumer(); consumer.soap(requestMessage);// ww w . j a v a2 s. co m consumer.attachment(contentType, attachmentIS, null); writingCtx.commit(); QueueInfo expectedQueueInfo = new QueueInfo(AsyncDBTestUtil.getProvider(), new QueueState(2, 0, null, 0, "", null, "")); validateQueueInfo(expectedQueueInfo); int requestNo = 1; RequestInfo expectedRequestInfo = getSecondRequest(); validateRequestInfo(expectedRequestInfo); validateSavedMessage(requestNo, Arrays.asList(requestMessage.getXml(), attachmentContent)); validateContentType(requestNo); SUCCESSFUL_STEPS.add("addRequestToExistentProvider"); LOG.info("TEST 2: addRequestToExistentProvider - FINISHED"); }
From source file:mx.com.quadrum.service.impl.ContratoServiceImpl.java
@Override public Boolean firmar(Firma f) { Contrato contrato = f.getContrato(); if (f.validaCampos()) { try {/* w ww .j a va 2 s . c o m*/ ByteArrayOutputStream byteArrayOutputStreamCer = new ByteArrayOutputStream(); ByteArrayOutputStream byteArrayOutputStreamKey = new ByteArrayOutputStream(); IOUtils.copy(f.getCer().getInputStream(), byteArrayOutputStreamCer); IOUtils.copy(f.getKey().getInputStream(), byteArrayOutputStreamKey); if (!f.esValidoCerKeyAndPassword()) { return false; } if (f.firmar()) { if (f.guardarArchivos()) { AtributosCertificado cer = new AtributosCertificado( new ByteArrayInputStream(byteArrayOutputStreamCer.toByteArray())); InputStream leyenda = IOUtils.toInputStream(regresarLeyenda(contrato.getNombre())); CadenaOriginal objetoCadenaOriginal = new CadenaOriginal(); byte[] cadenaOriginal = objetoCadenaOriginal.generaCadenaDos(leyenda, CADENA_ORIGINAL); Sello miSello = new Sello(f.getPassword(), f.getKey().getBytes(), cadenaOriginal); cer.obtenDatosCertificado(); Calendar c = Calendar.getInstance(); contrato.setSello(miSello.GeneraSelloDigital()); contrato.setEstatus(new Estatus(48)); contrato.setTieneArchivos(Boolean.TRUE); contrato.setFechaFirma(convierteStringToFecha(c.get(Calendar.DATE) + "/" + (c.get(Calendar.MONTH) + 1) + "/" + c.get(Calendar.YEAR))); contratoRepository.editar(contrato); EnviarCorreo enviar = new EnviarCorreo(); try { enviar.enviaCredenciales(contrato.getUsuario().getMail(), clienteFirmo(contrato), ASUNTO_FIRMADO); } catch (MessagingException ex) { Logger.getLogger(ContratoServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } return true; } } } catch (IOException ex) { Logger.getLogger(ContratoServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } return false; }
From source file:com.streamsets.pipeline.stage.executor.s3.TestAmazonS3Executor.java
@Test public void testCopyObject() throws Exception { String newName = UUID.randomUUID().toString(); AmazonS3ExecutorConfig config = getConfig(); config.taskConfig.taskType = TaskType.COPY_OBJECT; config.taskConfig.copyTargetLocation = newName; AmazonS3Executor executor = new AmazonS3Executor(config); TargetRunner runner = new TargetRunner.Builder(AmazonS3DExecutor.class, executor).build(); runner.runInit();/*from w w w.j a va2 s . c o m*/ try { s3client.putObject(new PutObjectRequest(BUCKET_NAME, objectName, IOUtils.toInputStream("content"), new ObjectMetadata())); runner.runWrite(ImmutableList.of(getTestRecord())); S3Object object = s3client.getObject(BUCKET_NAME, newName); S3ObjectInputStream objectContent = object.getObjectContent(); List<String> stringList = IOUtils.readLines(objectContent); Assert.assertEquals(1, stringList.size()); Assert.assertEquals("content", stringList.get(0)); Assert.assertTrue(s3client.doesObjectExist(BUCKET_NAME, objectName)); Assert.assertEquals(1, runner.getEventRecords().size()); assertEvent(runner.getEventRecords().get(0), newName); } finally { runner.runDestroy(); } }