Search in sources :

Example 16 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project j2objc by google.

the class Options method load.

/**
   * Load the options from a command-line, returning the arguments that were
   * not option-related (usually files).  If help is requested or an error is
   * detected, the appropriate status method is invoked and the app terminates.
   * @throws IOException
   */
public String[] load(String[] args) throws IOException {
    setLogLevel(Level.WARNING);
    mappings.addJreMappings();
    // Create a temporary directory as the sourcepath's first entry, so that
    // modified sources will take precedence over regular files.
    fileUtil.setSourcePathEntries(Lists.newArrayList());
    int nArg = 0;
    String[] noFiles = new String[0];
    while (nArg < args.length) {
        String arg = args[nArg];
        if (arg.isEmpty()) {
            ++nArg;
            continue;
        }
        if (arg.equals("-classpath")) {
            if (++nArg == args.length) {
                return noFiles;
            }
            fileUtil.getClassPathEntries().addAll(getPathArgument(args[nArg]));
        } else if (arg.equals("-sourcepath")) {
            if (++nArg == args.length) {
                usage("-sourcepath requires an argument");
            }
            fileUtil.getSourcePathEntries().addAll(getPathArgument(args[nArg]));
        } else if (arg.equals("-processorpath")) {
            if (++nArg == args.length) {
                usage("-processorpath requires an argument");
            }
            processorPathEntries.addAll(getPathArgument(args[nArg]));
        } else if (arg.equals("-d")) {
            if (++nArg == args.length) {
                usage("-d requires an argument");
            }
            fileUtil.setOutputDirectory(new File(args[nArg]));
        } else if (arg.equals("--mapping")) {
            if (++nArg == args.length) {
                usage("--mapping requires an argument");
            }
            mappings.addMappingsFiles(args[nArg].split(","));
        } else if (arg.equals("--header-mapping")) {
            if (++nArg == args.length) {
                usage("--header-mapping requires an argument");
            }
            headerMap.setMappingFiles(args[nArg]);
        } else if (arg.equals("--output-header-mapping")) {
            if (++nArg == args.length) {
                usage("--output-header-mapping requires an argument");
            }
            headerMap.setOutputMappingFile(new File(args[nArg]));
        } else if (arg.equals("--dead-code-report")) {
            if (++nArg == args.length) {
                usage("--dead-code-report requires an argument");
            }
            proGuardUsageFile = new File(args[nArg]);
        } else if (arg.equals("--prefix")) {
            if (++nArg == args.length) {
                usage("--prefix requires an argument");
            }
            addPrefixOption(args[nArg]);
        } else if (arg.equals("--prefixes")) {
            if (++nArg == args.length) {
                usage("--prefixes requires an argument");
            }
            packagePrefixes.addPrefixesFile(args[nArg]);
        } else if (arg.equals("-x")) {
            if (++nArg == args.length) {
                usage("-x requires an argument");
            }
            String s = args[nArg];
            if (s.equals("objective-c")) {
                language = OutputLanguageOption.OBJECTIVE_C;
            } else if (s.equals("objective-c++")) {
                language = OutputLanguageOption.OBJECTIVE_CPLUSPLUS;
            } else {
                usage("unsupported language: " + s);
            }
        } else if (arg.equals("--ignore-missing-imports")) {
            ErrorUtil.error("--ignore-missing-imports is no longer supported");
        } else if (arg.equals("-use-reference-counting")) {
            checkMemoryManagementOption(MemoryManagementOption.REFERENCE_COUNTING);
        } else if (arg.equals("--no-package-directories")) {
            headerMap.setOutputStyle(HeaderMap.OutputStyleOption.NONE);
        } else if (arg.equals("--preserve-full-paths")) {
            headerMap.setOutputStyle(HeaderMap.OutputStyleOption.SOURCE);
        } else if (arg.equals("-XcombineJars")) {
            headerMap.setCombineJars();
        } else if (arg.equals("-XincludeGeneratedSources")) {
            headerMap.setIncludeGeneratedSources();
        } else if (arg.equals("-use-arc")) {
            checkMemoryManagementOption(MemoryManagementOption.ARC);
        } else if (arg.equals("-g")) {
            emitLineDirectives = true;
        } else if (arg.equals("-g:none")) {
            emitLineDirectives = false;
        } else if (arg.equals("-Werror")) {
            warningsAsErrors = true;
        } else if (arg.equals("--generate-deprecated")) {
            deprecatedDeclarations = true;
        } else if (arg.equals("-l") || arg.equals("--list")) {
            setLogLevel(Level.INFO);
        } else if (arg.equals("-t") || arg.equals(TIMING_INFO_ARG)) {
            timingLevel = TimingLevel.ALL;
        } else if (arg.startsWith(TIMING_INFO_ARG + ':')) {
            String timingArg = arg.substring(TIMING_INFO_ARG.length() + 1);
            try {
                timingLevel = TimingLevel.valueOf(timingArg.toUpperCase());
            } catch (IllegalArgumentException e) {
                usage("invalid --timing-info argument");
            }
        } else if (arg.equals("-v") || arg.equals("--verbose")) {
            setLogLevel(Level.FINEST);
        } else if (arg.startsWith(XBOOTCLASSPATH)) {
            bootclasspath = arg.substring(XBOOTCLASSPATH.length());
        } else if (arg.equals("-Xno-jsni-delimiters")) {
        // TODO(tball): remove flag when all client builds stop using it.
        } else if (arg.equals("-Xno-jsni-warnings")) {
            jsniWarnings = false;
        } else if (arg.equals("-encoding")) {
            if (++nArg == args.length) {
                usage("-encoding requires an argument");
            }
            try {
                fileUtil.setFileEncoding(args[nArg]);
            } catch (UnsupportedCharsetException e) {
                ErrorUtil.warning(e.getMessage());
            }
        } else if (arg.equals("--strip-gwt-incompatible")) {
            stripGwtIncompatible = true;
        } else if (arg.equals("--strip-reflection")) {
            stripReflection = true;
        } else if (arg.equals("--no-segmented-headers")) {
            segmentedHeaders = false;
        } else if (arg.equals("--build-closure")) {
            buildClosure = true;
        } else if (arg.equals("--extract-unsequenced")) {
            extractUnsequencedModifications = true;
        } else if (arg.equals("--no-extract-unsequenced")) {
            extractUnsequencedModifications = false;
        } else if (arg.equals("--doc-comments")) {
            docCommentsEnabled = true;
        } else if (arg.equals("--doc-comment-warnings")) {
            reportJavadocWarnings = true;
        } else if (arg.startsWith(BATCH_PROCESSING_MAX_FLAG)) {
            batchTranslateMaximum = Integer.parseInt(arg.substring(BATCH_PROCESSING_MAX_FLAG.length()));
        } else if (arg.equals("--static-accessor-methods")) {
            staticAccessorMethods = true;
        } else if (arg.equals("--swift-friendly")) {
            swiftFriendly = true;
        } else if (arg.equals("-processor")) {
            if (++nArg == args.length) {
                usage("-processor requires an argument");
            }
            processors = args[nArg];
        } else if (arg.equals("--allow-inherited-constructors")) {
            disallowInheritedConstructors = false;
        } else if (arg.equals("--nullability")) {
            nullability = true;
        } else if (arg.startsWith("-Xlint")) {
            lintArgument = arg;
            lintOptions = LintOption.parse(arg);
        } else if (arg.equals("-Xtranslate-bootclasspath")) {
            translateBootclasspath = true;
        } else if (arg.equals("-Xuse-jdt")) {
            javaFrontEnd = FrontEnd.JDT;
        } else if (arg.equals("-Xuse-javac")) {
            javaFrontEnd = FrontEnd.JAVAC;
        } else if (arg.equals("-Xdump-ast")) {
            dumpAST = true;
        } else if (arg.equals("-version")) {
            version();
        } else if (arg.startsWith("-h") || arg.equals("--help")) {
            help(false);
        } else if (arg.equals("-X")) {
            xhelp();
        } else if (arg.equals("-source")) {
            if (++nArg == args.length) {
                usage("-source requires an argument");
            }
            // Handle aliasing of version numbers as supported by javac.
            try {
                sourceVersion = SourceVersion.parse(args[nArg]);
            } catch (IllegalArgumentException e) {
                usage("invalid source release: " + args[nArg]);
            }
        } else if (arg.equals("-target")) {
            // Dummy out passed target argument, since we don't care about target.
            if (++nArg == args.length) {
                usage("-target requires an argument");
            }
        // ignore
        } else if (obsoleteFlags.contains(arg)) {
        // also ignore
        } else if (arg.startsWith("-")) {
            usage("invalid flag: " + arg);
        } else {
            break;
        }
        ++nArg;
    }
    if (headerMap.useSourceDirectories() && buildClosure) {
        ErrorUtil.error("--build-closure is not supported with -XcombineJars or --preserve-full-paths or " + "-XincludeGeneratedSources");
    }
    if (memoryManagementOption == null) {
        memoryManagementOption = MemoryManagementOption.REFERENCE_COUNTING;
    }
    if (swiftFriendly) {
        staticAccessorMethods = true;
        nullability = true;
    }
    // Pull source version from system properties if it is not passed with -source flag.
    if (sourceVersion == null) {
        sourceVersion = SourceVersion.parse(System.getProperty("java.version").substring(0, 3));
    }
    if (isJDT()) {
        // Java 6 had a 1G max heap limit, removed in Java 7.
        if (batchTranslateMaximum == -1) {
            // Not set by flag.
            batchTranslateMaximum = SourceVersion.java7Minimum(sourceVersion) ? 300 : 0;
        }
    } else {
        // javac performs best when all sources are compiled by one task.
        batchTranslateMaximum = Integer.MAX_VALUE;
    }
    int nFiles = args.length - nArg;
    String[] files = new String[nFiles];
    for (int i = 0; i < nFiles; i++) {
        String path = args[i + nArg];
        files[i] = path;
    }
    return files;
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) File(java.io.File)

Example 17 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project jdk8u_jdk by JetBrains.

the class Test4625418 method test.

private void test(String string) {
    try {
        File file = new File("4625418." + this.encoding + ".xml");
        FileOutputStream output = new FileOutputStream(file);
        XMLEncoder encoder = new XMLEncoder(output, this.encoding, true, 0);
        encoder.setExceptionListener(this);
        encoder.writeObject(string);
        encoder.close();
        FileInputStream input = new FileInputStream(file);
        XMLDecoder decoder = new XMLDecoder(input);
        decoder.setExceptionListener(this);
        Object object = decoder.readObject();
        decoder.close();
        if (!string.equals(object))
            throw new Error(this.encoding + " - can't read properly");
        file.delete();
    } catch (FileNotFoundException exception) {
        throw new Error(this.encoding + " - file not found", exception);
    } catch (IllegalCharsetNameException exception) {
        throw new Error(this.encoding + " - illegal charset name", exception);
    } catch (UnsupportedCharsetException exception) {
        throw new Error(this.encoding + " - unsupported charset", exception);
    } catch (UnsupportedOperationException exception) {
        throw new Error(this.encoding + " - unsupported encoder", exception);
    }
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) XMLEncoder(java.beans.XMLEncoder) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) FileOutputStream(java.io.FileOutputStream) XMLDecoder(java.beans.XMLDecoder) FileNotFoundException(java.io.FileNotFoundException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 18 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project opennms by OpenNMS.

the class HttpPostMonitor method poll.

/**
     * {@inheritDoc}
     *
     * Poll the specified address for service availability.
     *
     * During the poll an attempt is made to execute the named method (with optional input) connect on the specified port. If
     * the exec on request is successful, the banner line generated by the
     * interface is parsed and if the banner text indicates that we are talking
     * to Provided that the interface's response is valid we set the service
     * status to SERVICE_AVAILABLE and return.
     */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // Process parameters
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Port
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
    //URI
    String strURI = ParameterMap.getKeyedString(parameters, PARAMETER_URI, DEFAULT_URI);
    //Username
    String strUser = ParameterMap.getKeyedString(parameters, PARAMETER_USERNAME, null);
    //Password
    String strPasswd = ParameterMap.getKeyedString(parameters, PARAMETER_PASSWORD, null);
    //BannerMatch
    String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);
    //Scheme
    String strScheme = ParameterMap.getKeyedString(parameters, PARAMETER_SCHEME, DEFAULT_SCHEME);
    //Payload
    String strPayload = ParameterMap.getKeyedString(parameters, PARAMETER_PAYLOAD, null);
    //Mimetype
    String strMimetype = ParameterMap.getKeyedString(parameters, PARAMETER_MIMETYPE, DEFAULT_MIMETYPE);
    //Charset
    String strCharset = ParameterMap.getKeyedString(parameters, PARAMETER_CHARSET, DEFAULT_CHARSET);
    //SSLFilter
    boolean boolSSLFilter = ParameterMap.getKeyedBoolean(parameters, PARAMETER_SSLFILTER, DEFAULT_SSLFILTER);
    // Get the address instance.
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
    // Give it a whirl
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        HttpClientWrapper clientWrapper = null;
        try {
            tracker.startAttempt();
            clientWrapper = HttpClientWrapper.create().setConnectionTimeout(tracker.getSoTimeout()).setSocketTimeout(tracker.getSoTimeout()).setRetries(DEFAULT_RETRY);
            if (boolSSLFilter) {
                clientWrapper.trustSelfSigned(strScheme);
            }
            HttpEntity postReq;
            if (strUser != null && strPasswd != null) {
                clientWrapper.addBasicCredentials(strUser, strPasswd);
            }
            try {
                postReq = new StringEntity(strPayload, ContentType.create(strMimetype, strCharset));
            } catch (final UnsupportedCharsetException e) {
                serviceStatus = PollStatus.unavailable("Unsupported encoding encountered while constructing POST body " + e);
                break;
            }
            URIBuilder ub = new URIBuilder();
            ub.setScheme(strScheme);
            ub.setHost(hostAddress);
            ub.setPort(port);
            ub.setPath(strURI);
            LOG.debug("HttpPostMonitor: Constructed URL is {}", ub);
            HttpPost post = new HttpPost(ub.build());
            post.setEntity(postReq);
            CloseableHttpResponse response = clientWrapper.execute(post);
            LOG.debug("HttpPostMonitor: Status Line is {}", response.getStatusLine());
            if (response.getStatusLine().getStatusCode() > 399) {
                LOG.info("HttpPostMonitor: Got response status code {}", response.getStatusLine().getStatusCode());
                LOG.debug("HttpPostMonitor: Received server response: {}", response.getStatusLine());
                LOG.debug("HttpPostMonitor: Failing on bad status code");
                serviceStatus = PollStatus.unavailable("HTTP(S) Status code " + response.getStatusLine().getStatusCode());
                break;
            }
            LOG.debug("HttpPostMonitor: Response code is valid");
            double responseTime = tracker.elapsedTimeInMillis();
            HttpEntity entity = response.getEntity();
            InputStream responseStream = entity.getContent();
            String Strresponse = IOUtils.toString(responseStream);
            if (Strresponse == null)
                continue;
            LOG.debug("HttpPostMonitor: banner = {}", Strresponse);
            LOG.debug("HttpPostMonitor: responseTime= {}ms", responseTime);
            //Could it be a regex?
            if (!Strings.isNullOrEmpty(strBannerMatch) && strBannerMatch.startsWith("~")) {
                if (!Strresponse.matches(strBannerMatch.substring(1))) {
                    serviceStatus = PollStatus.unavailable("Banner does not match Regex '" + strBannerMatch + "'");
                    break;
                } else {
                    serviceStatus = PollStatus.available(responseTime);
                }
            } else {
                if (Strresponse.indexOf(strBannerMatch) > -1) {
                    serviceStatus = PollStatus.available(responseTime);
                } else {
                    serviceStatus = PollStatus.unavailable("Did not find expected Text '" + strBannerMatch + "'");
                    break;
                }
            }
        } catch (final URISyntaxException e) {
            final String reason = "URISyntaxException for URI: " + strURI + " " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } catch (final Exception e) {
            final String reason = "Exception: " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } finally {
            IOUtils.closeQuietly(clientWrapper);
        }
    }
    // return the status of the service
    return serviceStatus;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) PollStatus(org.opennms.netmgt.poller.PollStatus) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) URISyntaxException(java.net.URISyntaxException) URISyntaxException(java.net.URISyntaxException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InetAddress(java.net.InetAddress)

Example 19 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project CshBBrain by CshBBrain.

the class MyStringUtil method parseKeyValue.

/**
	 * 
	 * <li>方法名:decodeParams
	 * <li>@param msg
	 * <li>@param requestData
	 * <li>返回类型:void
	 * <li>说明:解析请求参数键值对
	 * <li>创建人:CshBBrain
	 * <li>创建日期:2011-11-25
	 * <li>修改人: 
	 * <li>修改日期:
	 */
public static HashMap<String, String> parseKeyValue(String msg) {
    if (isBlank(msg)) {
        return null;
    }
    String values = null;
    try {
        values = URLDecoder.decode(msg, CoderUtils.UTF8);
    } catch (UnsupportedEncodingException e) {
        throw new UnsupportedCharsetException(CoderUtils.UTF8);
    }
    HashMap<String, String> requestData = new HashMap<String, String>();
    Matcher m = PARAM_PATTERN.matcher(values);
    int pos = 0;
    while (m.find(pos)) {
        pos = m.end();
        requestData.put(m.group(1), m.group(2));
    }
    return requestData;
}
Also used : HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 20 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project logging-log4j2 by apache.

the class PropertiesUtilTest method testGetCharsetProperty.

@Test
public void testGetCharsetProperty() throws Exception {
    Properties p = new Properties();
    p.setProperty("e.1", StandardCharsets.US_ASCII.name());
    p.setProperty("e.2", "wrong-charset-name");
    PropertiesUtil pu = new PropertiesUtil(p);
    assertEquals(Charset.defaultCharset(), pu.getCharsetProperty("e.0"));
    assertEquals(StandardCharsets.US_ASCII, pu.getCharsetProperty("e.1"));
    try {
        pu.getCharsetProperty("e.2");
        fail("No expected UnsupportedCharsetException");
    } catch (UnsupportedCharsetException ignored) {
    }
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Properties(java.util.Properties) Test(org.junit.Test)

Aggregations

UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)46 Charset (java.nio.charset.Charset)18 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)13 IOException (java.io.IOException)10 File (java.io.File)9 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 FileOutputStream (java.io.FileOutputStream)4 PrintStream (java.io.PrintStream)4 HashMap (java.util.HashMap)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 FileInputStream (java.io.FileInputStream)3 InputStream (java.io.InputStream)3 Test (org.junit.Test)3 FormBuilder (com.jgoodies.forms.builder.FormBuilder)2 FormLayout (com.jgoodies.forms.layout.FormLayout)2 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)2 InputStreamReader (java.io.InputStreamReader)2 StringReader (java.io.StringReader)2 ReadableByteChannel (java.nio.channels.ReadableByteChannel)2 WritableByteChannel (java.nio.channels.WritableByteChannel)2