List of usage examples for java.nio.charset StandardCharsets ISO_8859_1
Charset ISO_8859_1
To view the source code for java.nio.charset StandardCharsets ISO_8859_1.
Click Source Link
From source file:org.eclipse.hawkbit.ddi.rest.resource.DdiArtifactDownloadTest.java
@Test @WithUser(principal = TestdataFactory.DEFAULT_CONTROLLER_ID, authorities = "ROLE_CONTROLLER", allSpPermissions = true) @Description("Test various HTTP range requests for artifact download, e.g. chunk download or download resume.") public void rangeDownloadArtifact() throws Exception { // create target final Target target = testdataFactory.createTarget(); final List<Target> targets = Arrays.asList(target); // create ds//from w w w . j a va 2s . c o m final DistributionSet ds = testdataFactory.createDistributionSet(""); final int resultLength = 5 * 1000 * 1024; // create artifact final byte random[] = RandomUtils.nextBytes(resultLength); final Artifact artifact = artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(random), getOsModule(ds), "file1", false, resultLength)); assertThat(random.length).isEqualTo(resultLength); // now assign and download successful assignDistributionSet(ds, targets); final int range = 100 * 1024; // full file download with standard range request final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (int i = 0; i < resultLength / range; i++) { final String rangeString = "" + i * range + "-" + ((i + 1) * range - 1); final MvcResult result = mvc.perform(get( "/{tenant}/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/{filename}", tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), "file1") .header("Range", "bytes=" + rangeString)) .andExpect(status().isPartialContent()) .andExpect(header().string("ETag", artifact.getSha1Hash())) .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)) .andExpect(header().string("Accept-Ranges", "bytes")) .andExpect( header().string("Last-Modified", dateFormat.format(new Date(artifact.getCreatedAt())))) .andExpect(header().longValue("Content-Length", range)) .andExpect(header().string("Content-Range", "bytes " + rangeString + "/" + resultLength)) .andExpect(header().string("Content-Disposition", "attachment;filename=file1")).andReturn(); outputStream.write(result.getResponse().getContentAsByteArray()); } assertThat(outputStream.toByteArray()).isEqualTo(random); // return last 1000 Bytes MvcResult result = mvc.perform(get( "/{tenant}/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/{filename}", tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), "file1").header("Range", "bytes=-1000")) .andExpect(status().isPartialContent()).andExpect(header().string("ETag", artifact.getSha1Hash())) .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)) .andExpect(header().string("Accept-Ranges", "bytes")) .andExpect(header().string("Last-Modified", dateFormat.format(new Date(artifact.getCreatedAt())))) .andExpect(header().longValue("Content-Length", 1000)) .andExpect(header().string("Content-Range", "bytes " + (resultLength - 1000) + "-" + (resultLength - 1) + "/" + resultLength)) .andExpect(header().string("Content-Disposition", "attachment;filename=file1")).andReturn(); assertThat(result.getResponse().getContentAsByteArray()) .isEqualTo(Arrays.copyOfRange(random, resultLength - 1000, resultLength)); // skip first 1000 Bytes and return the rest result = mvc.perform(get( "/{tenant}/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/{filename}", tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), "file1").header("Range", "bytes=1000-")) .andExpect(status().isPartialContent()).andExpect(header().string("ETag", artifact.getSha1Hash())) .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)) .andExpect(header().string("Accept-Ranges", "bytes")) .andExpect(header().string("Last-Modified", dateFormat.format(new Date(artifact.getCreatedAt())))) .andExpect(header().longValue("Content-Length", resultLength - 1000)) .andExpect(header().string("Content-Range", "bytes " + 1000 + "-" + (resultLength - 1) + "/" + resultLength)) .andExpect(header().string("Content-Disposition", "attachment;filename=file1")).andReturn(); assertThat(result.getResponse().getContentAsByteArray()) .isEqualTo(Arrays.copyOfRange(random, 1000, resultLength)); // Start download from file end fails mvc.perform(get( "/{tenant}/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/{filename}", tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), "file1").header("Range", "bytes=" + random.length + "-")) .andExpect(status().isRequestedRangeNotSatisfiable()) .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)) .andExpect(header().string("Accept-Ranges", "bytes")) .andExpect(header().string("Last-Modified", dateFormat.format(new Date(artifact.getCreatedAt())))) .andExpect(header().string("Content-Range", "bytes */" + random.length)) .andExpect(header().string("Content-Disposition", "attachment;filename=file1")); // multipart download - first 20 bytes in 2 parts result = mvc.perform(get( "/{tenant}/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/{filename}", tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), "file1").header("Range", "bytes=0-9,10-19")) .andExpect(status().isPartialContent()).andExpect(header().string("ETag", artifact.getSha1Hash())) .andExpect(content().contentType("multipart/byteranges; boundary=THIS_STRING_SEPARATES_MULTIPART")) .andExpect(header().string("Accept-Ranges", "bytes")) .andExpect(header().string("Last-Modified", dateFormat.format(new Date(artifact.getCreatedAt())))) .andExpect(header().string("Content-Disposition", "attachment;filename=file1")).andReturn(); outputStream.reset(); outputStream.write("\r\n--THIS_STRING_SEPARATES_MULTIPART\r\n".getBytes(StandardCharsets.ISO_8859_1)); outputStream .write(("Content-Range: bytes 0-9/" + resultLength + "\r\n").getBytes(StandardCharsets.ISO_8859_1)); outputStream.write(Arrays.copyOfRange(random, 0, 10)); outputStream.write("\r\n--THIS_STRING_SEPARATES_MULTIPART\r\n".getBytes(StandardCharsets.ISO_8859_1)); outputStream.write( ("Content-Range: bytes 10-19/" + resultLength + "\r\n").getBytes(StandardCharsets.ISO_8859_1)); outputStream.write(Arrays.copyOfRange(random, 10, 20)); outputStream.write("\r\n--THIS_STRING_SEPARATES_MULTIPART--".getBytes(StandardCharsets.ISO_8859_1)); assertThat(result.getResponse().getContentAsByteArray()).isEqualTo(outputStream.toByteArray()); }
From source file:carolina.pegaLatLong.LatLong.java
private void geraCsv(List<InformacaoGerada> gerados) throws IOException { JFileChooser escolha = new JFileChooser(); escolha.setAcceptAllFileFilterUsed(false); escolha.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int i = escolha.showSaveDialog(null); if (i != 1) { System.err.println(escolha.getSelectedFile().getPath() + "\\teste.txt"); String caminho = escolha.getSelectedFile().getPath(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(caminho + "\\teste.csv"), StandardCharsets.ISO_8859_1)); //FileWriter arquivo = new FileWriter(caminho + "\\teste.csv"); //PrintWriter writer = new PrintWriter(arquivo); writer.write("Endereco;Latitude;Longitude"); writer.newLine();//from ww w . jav a 2 s . com gerados.stream().forEach((gerado) -> { try { System.err.println(gerado.getEnderecoFormatado() + ";" + gerado.getLatitude() + ";" + gerado.getLongitude() + "\n"); writer.write(gerado.getEnderecoFormatado() + ";" + gerado.getLatitude() + ";" + gerado.getLongitude()); writer.newLine(); } catch (IOException ex) { System.err.println("Erro"); } }); writer.close(); JOptionPane.showMessageDialog(null, "Finalizado!"); } }
From source file:JDBCPool.dbcp.demo.sourcecode.BasicDataSourceFactory.java
/** * <p>Parse properties from the string. Format of the string must be [propertyName=property;]*<p> * @param propText/*from www . j a v a 2 s . com*/ * @return Properties * @throws Exception */ private static Properties getProperties(String propText) throws Exception { Properties p = new Properties(); if (propText != null) { p.load(new ByteArrayInputStream(propText.replace(';', '\n').getBytes(StandardCharsets.ISO_8859_1))); } return p; }
From source file:MSUmpire.SpectrumParser.mzXMLParser.java
private List<MzXMLthreadUnit> ParseScans(final BitSet IncludedScans) { List<MzXMLthreadUnit> ScanList = new ArrayList<>(); ArrayList<ForkJoinTask<?>> futures = new ArrayList<>(); final ForkJoinPool fjp = new ForkJoinPool(NoCPUs); Iterator<Entry<Integer, Long>> iter = ScanIndex.entrySet().iterator(); Entry<Integer, Long> ent = iter.next(); long currentIdx = ent.getValue(); int nextScanNo = ent.getKey(); final RandomAccessFile fileHandler; try {//from ww w. j a v a2s . co m fileHandler = new RandomAccessFile(filename, "r"); } catch (FileNotFoundException e) { throw new RuntimeException(e); } byte[] buffer = new byte[1 << 10]; if (step == -1) step = fjp.getParallelism() * 32; while (iter.hasNext()) { ent = iter.next(); long startposition = currentIdx; long nexposition = ent.getValue(); int currentScanNo = nextScanNo; nextScanNo = ent.getKey(); currentIdx = nexposition; if (IncludedScans.get(currentScanNo)) { try { final int bufsize = (int) (nexposition - startposition); if (buffer.length < bufsize) buffer = new byte[Math.max(bufsize, buffer.length << 1)]; // byte[] buffer = new byte[bufsize]; // RandomAccessFile fileHandler = new RandomAccessFile(filename, "r"); fileHandler.seek(startposition); fileHandler.read(buffer, 0, bufsize); // fileHandler.close(); // String xmltext = new String(buffer); String xmltext = new String(buffer, 0, bufsize, StandardCharsets.ISO_8859_1); if (ent.getKey() == Integer.MAX_VALUE) { xmltext = xmltext.replaceAll("</msRun>", ""); } boolean ReadPeak = true; final MzXMLthreadUnit unit = new MzXMLthreadUnit(xmltext, parameter, datatype, ReadPeak); futures.add(fjp.submit(unit)); ScanList.add(unit); if ((ScanList.size() % step) == 0) { futures.get(futures.size() - step).get(); if (iter.hasNext() && fjp.getActiveThreadCount() < fjp.getParallelism()) { step *= 2; // System.out.println("MzXMLthreadUnit: fjp.getActiveThreadCount()\t" + fjp.getActiveThreadCount()+"\t"+step); } } } catch (Exception ex) { Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex)); } } } try { fileHandler.close(); } catch (IOException ex) { throw new RuntimeException(ex); } fjp.shutdown(); try { fjp.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException ex) { throw new RuntimeException(ex); } // for (MzXMLthreadUnit unit : ScanList) { // executorPool.execute(unit); // } // executorPool.shutdown(); // // try { // executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); // } catch (InterruptedException e) { // Logger.getRootLogger().info("interrupted.."); // } return ScanList; }
From source file:com.evolveum.midpoint.model.intest.TestNotifications.java
@Test public void test210SendSmsUsingPost() { final String TEST_NAME = "test210SendSmsUsingPost"; TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN/*from w ww .j av a2 s . c o m*/ Task task = taskManager.createTaskInstance(TestNotifications.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); Event event = new CustomEvent(lightweightIdentifierGenerator, "post", null, "hello world", EventOperationType.ADD, EventStatusType.SUCCESS, null); notificationManager.processEvent(event, task, result); // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("processEvent result", result); assertNotNull("No http request found", httpHandler.lastRequest); assertEquals("Wrong HTTP method", "POST", httpHandler.lastRequest.method); assertEquals("Wrong URI", "/send", httpHandler.lastRequest.uri.toString()); assertEquals("Wrong Content-Type header", singletonList("application/x-www-form-urlencoded"), httpHandler.lastRequest.headers.get("content-type")); assertEquals("Wrong X-Custom header", singletonList("test"), httpHandler.lastRequest.headers.get("x-custom")); String username = "a9038321"; String password = "5ecr3t"; String expectedAuthorization = "Basic " + Base64.getEncoder() .encodeToString((username + ":" + password).getBytes(StandardCharsets.ISO_8859_1)); assertEquals("Wrong Authorization header", singletonList(expectedAuthorization), httpHandler.lastRequest.headers.get("authorization")); assertEquals("Wrong 1st line of body", "Body=\"hello+world\"&To=%2B421905123456&From=%2B421999000999", httpHandler.lastRequest.body.get(0)); }
From source file:com.evolveum.midpoint.model.intest.TestNotifications.java
@Test public void test215SendSmsUsingGeneralPost() { final String TEST_NAME = "test215SendSmsUsingGeneralPost"; TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN//w w w. j a va2s . co m Task task = taskManager.createTaskInstance(TestNotifications.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); Event event = new CustomEvent(lightweightIdentifierGenerator, "general-post", null, "hello world", EventOperationType.ADD, EventStatusType.SUCCESS, null); notificationManager.processEvent(event, task, result); // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("processEvent result", result); assertNotNull("No http request found", httpHandler.lastRequest); assertEquals("Wrong HTTP method", "POST", httpHandler.lastRequest.method); assertEquals("Wrong URI", "/send", httpHandler.lastRequest.uri.toString()); assertEquals("Wrong Content-Type header", singletonList("application/x-www-form-urlencoded"), httpHandler.lastRequest.headers.get("content-type")); assertEquals("Wrong X-Custom header", singletonList("test"), httpHandler.lastRequest.headers.get("x-custom")); String username = "a9038321"; String password = "5ecr3t"; String expectedAuthorization = "Basic " + Base64.getEncoder() .encodeToString((username + ":" + password).getBytes(StandardCharsets.ISO_8859_1)); assertEquals("Wrong Authorization header", singletonList(expectedAuthorization), httpHandler.lastRequest.headers.get("authorization")); assertEquals("Wrong 1st line of body", "Body=\"body\"&To=[%2B123, %2B456, %2B789]&From=from", httpHandler.lastRequest.body.get(0)); }
From source file:org.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java
@Initializer(before = InitMilestone.JOB_LOADED) public static void replaceWorkspacePath() throws Exception { final File prj = new File(Jenkins.getInstance().getRootDir(), "jobs/p"); final File workspace = new File(prj, "workspace"); final String ORIG_WS = "/space/tmp/AbstractStepExecutionImpl-upgrade/jobs/p/workspace"; final String newWs = workspace.getAbsolutePath(); File controlDir = new File(workspace, ".eb6272d3"); if (!controlDir.isDirectory()) { return;/*from ww w. j ava 2s. co m*/ } System.err.println("Patching " + controlDir); RiverReader.customResolver = new ObjectResolver() { @Override public Object readResolve(Object replacement) { Class<?> c = replacement.getClass(); //System.err.println("replacing " + c.getName()); while (c != Object.class) { for (Field f : c.getDeclaredFields()) { if (f.getType() == String.class) { try { f.setAccessible(true); Object v = f.get(replacement); if (ORIG_WS.equals(v)) { //System.err.println("patching " + f); f.set(replacement, newWs); patchedFields.add(f.toString()); } else if (newWs.equals(v)) { //System.err.println(f + " was already patched, somehow?"); } else { //System.err.println("some other value " + v + " for " + f); } } catch (Exception x) { x.printStackTrace(); } } } c = c.getSuperclass(); } return replacement; } @Override public Object writeReplace(Object original) { throw new IllegalStateException(); } }; Files.walkFileTree(prj.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { File f = file.toFile(); String name = f.getName(); if (name.equals("program.dat")) { /* TODO could not get this to work; stream appeared corrupted: patchedFiles.add(name); String origContent = FileUtils.readFileToString(f, StandardCharsets.ISO_8859_1); String toReplace = String.valueOf((char) Protocol.ID_STRING_SMALL) + String.valueOf((char) ORIG_WS.length()) + ORIG_WS; int newLen = newWs.length(); String replacement = String.valueOf((char) Protocol.ID_STRING_MEDIUM) + String.valueOf((char) (newLen & 0xff00) >> 8) + String.valueOf((char) newLen & 0xff) + newWs; // TODO breaks if not ASCII String replacedContent = origContent.replace(toReplace, replacement); assertNotEquals("failed to replace " + toReplace + "", replacedContent, origContent); FileUtils.writeStringToFile(f, replacedContent, StandardCharsets.ISO_8859_1); */ } else { String origContent = FileUtils.readFileToString(f, StandardCharsets.ISO_8859_1); String replacedContent = origContent.replace(ORIG_WS, newWs); if (!replacedContent.equals(origContent)) { patchedFiles.add(name); FileUtils.writeStringToFile(f, replacedContent, StandardCharsets.ISO_8859_1); } } return super.visitFile(file, attrs); } }); FilePath controlDirFP = new FilePath(controlDir); controlDirFP.child("jenkins-result.txt").write("0", null); FilePath log = controlDirFP.child("jenkins-log.txt"); log.write(log.readToString() + "simulated later output\n", null); }
From source file:org.zaproxy.zap.extension.zest.ExtensionZest.java
private static int getResponseBodyLength(HttpMessage message) { // The following code mimics the behaviour of HttpMethodBase.getResponseBodyAsString() which // is the method used by the // Zest engine to obtain the response body after sending a request. byte[] body = message.getResponseBody().getBytes(); String charset = message.getResponseHeader().getCharset(); if (charset == null) { charset = StandardCharsets.ISO_8859_1.name(); }//from w ww . j a va2 s . c o m try { return new String(body, charset).length(); } catch (UnsupportedEncodingException e) { return new String(body).length(); } }
From source file:com.ehsy.solr.util.SimplePostTool.java
private static boolean checkResponseCode(HttpURLConnection urlc) throws IOException { if (urlc.getResponseCode() >= 400) { warn("Solr returned an error #" + urlc.getResponseCode() + " (" + urlc.getResponseMessage() + ") for url: " + urlc.getURL()); Charset charset = StandardCharsets.ISO_8859_1; final String contentType = urlc.getContentType(); // code cloned from ContentStreamBase, but post.jar should be standalone! if (contentType != null) { int idx = contentType.toLowerCase(Locale.ROOT).indexOf("charset="); if (idx > 0) { charset = Charset.forName(contentType.substring(idx + "charset=".length()).trim()); }/* w w w . j a v a2s . co m*/ } // Print the response returned by Solr try (InputStream errStream = urlc.getErrorStream()) { if (errStream != null) { BufferedReader br = new BufferedReader(new InputStreamReader(errStream, charset)); final StringBuilder response = new StringBuilder("Response: "); int ch; while ((ch = br.read()) != -1) { response.append((char) ch); } warn(response.toString().trim()); } } return false; } return true; }
From source file:org.madsonic.service.MediaFileService.java
private String checkForCommentFile(File file) { File commentFile = new File(file.getPath(), "comment.txt"); if (commentFile.exists()) { LOG.info("## CommentFile found: " + commentFile); Path path = Paths.get(commentFile.getPath()); List<String> lines = null; String listString = ""; try {// w w w . j a v a 2s. c om lines = Files.readAllLines(path, StandardCharsets.UTF_8); } catch (IOException e) { LOG.warn("## error reading commentfile: " + commentFile); // e.printStackTrace(); } if (lines == null) { try { lines = Files.readAllLines(path, StandardCharsets.ISO_8859_1); } catch (IOException e) { LOG.warn("## error reading commentfile: " + commentFile); // e.printStackTrace(); } } for (String s : lines) { s = s.replace("", "'"); listString += s + " \\\\"; } return listString; } return null; }