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.packagedrone.testing.server.channel.UploadApiV3Test.java
protected CloseableHttpResponse upload(final URIBuilder uri, final File file) throws IOException, URISyntaxException { final HttpPut http = new HttpPut(uri.build()); final String encodedAuth = Base64.getEncoder() .encodeToString(uri.getUserInfo().getBytes(StandardCharsets.ISO_8859_1)); http.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth); http.setEntity(new FileEntity(file)); return httpclient.execute(http); }
From source file:org.sonar.scanner.scan.filesystem.ByteCharsetDetectorTest.java
@Test public void tryOtherUserCharset() { when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(Result.INVALID); when(validation.isUTF16(any(byte[].class), anyBoolean())).thenReturn(new Result(Validation.MAYBE, null)); when(validation.tryDecode(any(byte[].class), eq(StandardCharsets.ISO_8859_1))).thenReturn(true); charsets = new ByteCharsetDetector(validation, StandardCharsets.ISO_8859_1); assertThat(charsets.detect(new byte[1])).isEqualTo(StandardCharsets.ISO_8859_1); }
From source file:tv.phantombot.httpserver.HTTPServerCommon.java
public static void handle(HttpExchange exchange, String serverPassword, String serverWebAuth) throws IOException { Boolean hasPassword = false;//from ww w .ja v a2 s.co m Boolean doRefresh = false; Boolean doMarquee = false; String myPassword = ""; String myHdrUser = ""; String myHdrMessage = ""; String[] uriQueryList = null; int marqueeWidth = 420; int msgLength = 40; // Get the path and query string from the URI URI uriData = exchange.getRequestURI(); String uriPath = uriData.getPath(); String uriQuery = uriData.getQuery(); if (uriQuery != null) { uriQueryList = uriQuery.split("&"); } // Get the headers Headers headers = exchange.getRequestHeaders(); // Get the Request Method (GET/PUT) String requestMethod = exchange.getRequestMethod(); // Get any data from the body, although, we just discard it, this is required InputStream inputStream = exchange.getRequestBody(); while (inputStream.read() != -1) { inputStream.skip(0x10000); } inputStream.close(); if (headers.containsKey("password")) { myPassword = headers.getFirst("password"); if (myPassword.equals(serverPassword) || myPassword.equals("oauth:" + serverPassword)) { hasPassword = true; } } if (headers.containsKey("webauth")) { myPassword = headers.getFirst("webauth"); if (myPassword.equals(serverWebAuth)) { hasPassword = true; } } if (headers.containsKey("user")) { myHdrUser = headers.getFirst("user"); } if (headers.containsKey("message")) { myHdrMessage = headers.getFirst("message"); byte[] myHdrMessageBytes = myHdrMessage.getBytes(StandardCharsets.ISO_8859_1); myHdrMessage = new String(myHdrMessageBytes, StandardCharsets.UTF_8); } // Check the uriQueryList for the webauth if (uriQuery != null) { for (String query : uriQueryList) { if (query.startsWith("webauth=")) { String[] webAuthData = query.split("="); myPassword = webAuthData[1]; if (myPassword.equals(serverWebAuth)) { hasPassword = true; } } else if (query.startsWith("refresh")) { doRefresh = true; } else if (query.startsWith("marquee")) { doMarquee = true; } else if (query.startsWith("width")) { String[] splitData = query.split("="); try { marqueeWidth = Integer.parseInt(splitData[1]); } catch (NumberFormatException ex) { marqueeWidth = 420; } } else if (query.startsWith("cutoff")) { String[] splitData = query.split("="); try { msgLength = Integer.parseInt(splitData[1]); } catch (NumberFormatException ex) { msgLength = 40; } } } } if (requestMethod.equals("GET")) { if (uriPath.contains("..")) { sendHTMLError(403, "Invalid URL", exchange); } else if (uriPath.startsWith("/inistore")) { handleIniStore(uriPath, exchange, hasPassword); } else if (uriPath.startsWith("/dbquery")) { handleDBQuery(uriPath, uriQueryList, exchange, hasPassword); } else if (uriPath.startsWith("/addons") && !doRefresh && !doMarquee) { handleFile(uriPath, exchange, hasPassword, true); } else if (uriPath.startsWith("/addons") && doMarquee) { handleRefresh(uriPath, exchange, true, hasPassword, true, marqueeWidth, msgLength); } else if (uriPath.startsWith("/addons") && doRefresh) { handleRefresh(uriPath, exchange, false, hasPassword, true, 0, 0); } else if (uriPath.startsWith("/logs")) { handleFile(uriPath, exchange, hasPassword, true); } else if (uriPath.equals("/playlist")) { handleFile("/web/playlist/index.html", exchange, hasPassword, false); } else if (uriPath.equals("/")) { handleFile("/web/index.html", exchange, hasPassword, false); } else if (uriPath.equals("/alerts")) { handleFile("/web/alerts/index.html", exchange, hasPassword, false); } else if (uriPath.startsWith("/config/audio-hooks")) { handleFile(uriPath, exchange, hasPassword, false); } else if (uriPath.startsWith("/config/gif-alerts")) { handleFile(uriPath, exchange, hasPassword, false); } else if (uriPath.startsWith("/get-lang")) { handleLangFiles("", exchange, hasPassword, true); } else if (uriPath.startsWith("/lang")) { handleLangFiles(headers.getFirst("lang-path"), exchange, hasPassword, true); } else if (uriPath.startsWith("/games")) { handleGamesList(exchange, hasPassword, true); } else { handleFile("/web" + uriPath, exchange, hasPassword, false); } } if (requestMethod.equals("PUT")) { if (myHdrUser.isEmpty() && headers.containsKey("lang-path")) { handlePutRequestLang(headers.getFirst("lang-path"), headers.getFirst("lang-data"), exchange, hasPassword); } else { handlePutRequest(myHdrUser, myHdrMessage, exchange, hasPassword); } } }
From source file:io.undertow.servlet.test.security.basic.ServletBasicAuthTestCase.java
@Test public void testBasicAuthNonAscii() throws Exception { testCall("authType", "BASIC", StandardCharsets.UTF_8, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", "charsetUser", "password-", 200); testCall("authType", "BASIC", StandardCharsets.ISO_8859_1, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", "charsetUser", "password-", 401); testCall("authType", "BASIC", StandardCharsets.ISO_8859_1, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1", "charsetUser", "password-", 200); testCall("authType", "BASIC", StandardCharsets.UTF_8, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1", "charsetUser", "password-", 401); }
From source file:org.apache.taverna.download.impl.DownloadManagerImpl.java
private String downloadHash(URI source) throws DownloadException { try {/*from w w w.j a v a 2 s . c o m*/ // We want to handle http/https with HTTPClient if (source.getScheme().equalsIgnoreCase("http") || source.getScheme().equalsIgnoreCase("https")) { logger.info("Downloading checksum " + source); return Request.Get(source).userAgent(getUserAgent()).connectTimeout(TIMEOUT).socketTimeout(TIMEOUT) .execute().returnContent().asString(StandardCharsets.ISO_8859_1); } else { // Try as a supported Path, e.g. file: or relative path try { Path path = Paths.get(source); return Files.readAllLines(path, StandardCharsets.ISO_8859_1).get(0); } catch (FileSystemNotFoundException e) { throw new DownloadException("Unsupported URL scheme: " + source.getScheme()); } } } catch (IOException e) { throw new DownloadException(String.format("Error downloading %1$s", source), e); } }
From source file:org.forgerock.cloudfoundry.TestHelper.java
public static String createBasicAuth(String username, String password) { return "Basic " + Base64.encode((username + ":" + password).getBytes(StandardCharsets.ISO_8859_1)); }
From source file:org.openhab.binding.robonect.internal.RobonectClient.java
private void addPreemptiveAuthentication(HttpClient httpClient, RobonectEndpoint endpoint) { AuthenticationStore auth = httpClient.getAuthenticationStore(); URI uri = URI.create(baseUrl); auth.addAuthenticationResult(new BasicResult(HttpHeader.AUTHORIZATION, uri, "Basic " + B64Code.encode(endpoint.getUser() + ":" + endpoint.getPassword(), StandardCharsets.ISO_8859_1))); }
From source file:ee.ria.xroad.common.util.MultipartEncoder.java
private void writeString(String string) throws IOException { out.write(string.getBytes(StandardCharsets.ISO_8859_1)); }
From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java
/** * Default public constructor./*from w w w . j a v a2s. co m*/ * * @param http * @param url * @param knownMetadata * @throws IOException * @throws HttpException */ public HttpResponse(HttpProtocol http, URL url, Metadata knownMetadata) throws IOException, HttpException { this.http = http; this.url = url; Scheme scheme = null; if ("http".equals(url.getProtocol())) { scheme = Scheme.HTTP; } else if ("https".equals(url.getProtocol())) { scheme = Scheme.HTTPS; } else { throw new IOException("Unknown scheme (not http/https) for url:" + url); } String path = "".equals(url.getFile()) ? "/" : url.getFile(); // some servers will redirect a request with a host line like // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they // don't want the :80... String host = url.getHost(); int port; String portString; if (url.getPort() == -1) { if (scheme == Scheme.HTTP) { port = 80; } else { port = 443; } portString = ""; } else { port = url.getPort(); portString = ":" + port; } Socket socket = null; try { socket = new Socket(); // create the socket socket.setSoTimeout(http.getTimeout()); // connect String sockHost = http.useProxy() ? http.getProxyHost() : host; int sockPort = http.useProxy() ? http.getProxyPort() : port; InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort); socket.connect(sockAddr, http.getTimeout()); if (scheme == Scheme.HTTPS) { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true); sslsocket.setUseClientMode(true); // Get the protocols and ciphers supported by this JVM Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols())); Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites())); // Intersect with preferred protocols and ciphers protocols.retainAll(http.getTlsPreferredProtocols()); ciphers.retainAll(http.getTlsPreferredCipherSuites()); sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()])); sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); sslsocket.startHandshake(); socket = sslsocket; } this.conf = http.getConf(); if (ConfUtils.getBoolean(conf, "store.ip.address", false) == true) { headers.setValue("_ip_", sockAddr.getAddress().getHostAddress()); } // make request OutputStream req = socket.getOutputStream(); StringBuffer reqStr = new StringBuffer("GET "); if (http.useProxy()) { reqStr.append(url.getProtocol() + "://" + host + portString + path); } else { reqStr.append(path); } reqStr.append(" HTTP/1.0\r\n"); reqStr.append("Host: "); reqStr.append(host); reqStr.append(portString); reqStr.append("\r\n"); reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n"); String userAgent = http.getUserAgent(); if ((userAgent == null) || (userAgent.length() == 0)) { if (HttpProtocol.LOGGER.isErrorEnabled()) { HttpProtocol.LOGGER.error("User-agent is not set!"); } } else { reqStr.append("User-Agent: "); reqStr.append(userAgent); reqStr.append("\r\n"); } reqStr.append("Accept-Language: "); reqStr.append(this.http.getAcceptLanguage()); reqStr.append("\r\n"); reqStr.append("Accept: "); reqStr.append(this.http.getAccept()); reqStr.append("\r\n"); if (knownMetadata != null) { String ifModifiedSince = knownMetadata.getFirstValue("cachedLastModified"); if (StringUtils.isNotBlank(ifModifiedSince)) { reqStr.append("If-Modified-Since: "); reqStr.append(ifModifiedSince); reqStr.append("\r\n"); } String ifNoneMatch = knownMetadata.getFirstValue("cachedEtag"); if (StringUtils.isNotBlank(ifNoneMatch)) { reqStr.append("If-None-Match: "); reqStr.append(ifNoneMatch); reqStr.append("\r\n"); } } reqStr.append("\r\n"); // @see http://www.w3.org/Protocols/rfc2068/rfc2068.txt for default // charset // TODO use UTF-8 and set a charset value explicitely byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.ISO_8859_1); req.write(reqBytes); req.flush(); PushbackInputStream in = // process response new PushbackInputStream( new BufferedInputStream(socket.getInputStream(), HttpProtocol.BUFFER_SIZE), HttpProtocol.BUFFER_SIZE); StringBuffer line = new StringBuffer(); boolean haveSeenNonContinueStatus = false; while (!haveSeenNonContinueStatus) { // parse status code line this.code = parseStatusLine(in, line); // parse headers parseHeaders(in, line); haveSeenNonContinueStatus = code != 100; // 100 is // "Continue" } String transferEncoding = getHeader(HttpHeaders.TRANSFER_ENCODING); if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) { readChunkedContent(in, line); } else { readPlainContent(in); } String contentEncoding = getHeader(HttpHeaders.CONTENT_ENCODING); if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) { content = http.processGzipEncoded(content, url); } else if ("deflate".equals(contentEncoding)) { content = http.processDeflateEncoded(content, url); } else { HttpProtocol.LOGGER.trace("fetched {} bytes from {}", content.length, url); } } finally { if (socket != null) socket.close(); } }
From source file:org.polymap.p4.data.importer.prompts.CharsetPrompt.java
private void initCharsets() { charsets = new TreeMap<String, Charset>(); for (Charset charset : Charset.availableCharsets().values()) { charsets.put(displayName(charset), charset); }//from ww w . j av a2 s . c o m displayNames = new ListOrderedSet<String>(); // add all defaults on top displayNames.add(displayName(StandardCharsets.ISO_8859_1)); displayNames.add(displayName(StandardCharsets.US_ASCII)); displayNames.add(displayName(StandardCharsets.UTF_8)); displayNames.add(displayName(StandardCharsets.UTF_16)); displayNames.add(displayName(StandardCharsets.UTF_16BE)); displayNames.add(displayName(StandardCharsets.UTF_16LE)); // a separator charsets.put(SEPARATOR, selection); displayNames.add(SEPARATOR); // add the rest for (String displayName : charsets.keySet()) { displayNames.add(displayName); } }