Example usage for java.lang IllegalArgumentException getLocalizedMessage

List of usage examples for java.lang IllegalArgumentException getLocalizedMessage

Introduction

In this page you can find the example usage for java.lang IllegalArgumentException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:ponzu.impl.test.Verify.java

public static void assertShallowClone(String itemName, Cloneable object) {
    try {/*from   w  w w .  j  a v a2s . com*/
        Method method = Object.class.getDeclaredMethod("clone", (Class<?>[]) null);
        method.setAccessible(true);
        Object clone = method.invoke(object);
        String prefix = itemName + " and its clone";
        Assert.assertNotSame(prefix, object, clone);
        assertEqualsAndHashCode(prefix, object, clone);
    } catch (IllegalArgumentException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (InvocationTargetException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (SecurityException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (NoSuchMethodException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (IllegalAccessException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (AssertionError e) {
        throwMangledException(e);
    }
}

From source file:ffx.potential.parsers.SystemFilter.java

/**
 * Automatically sets atom-specific flags, particularly nouse and inactive,
 * and apply harmonic restraints. Intended to be called at the end of
 * readFile() implementations./*  w  w  w. j  av a 2  s.c  om*/
 */
public void applyAtomProperties() {
    /**
     * What may be a more elegant implementation is to make readFile() a
     * public concrete, but skeletal method, and then have readFile() call a
     * protected abstract readFile method for each implementation.
     */

    Atom[] molaAtoms = activeMolecularAssembly.getAtomArray();
    int nmolaAtoms = molaAtoms.length;
    String[] nouseKeys = properties.getStringArray("nouse");
    for (String nouseKey : nouseKeys) {
        try {
            int[] nouseRange = parseAtNumArg("nouse", nouseKey, nmolaAtoms);
            logger.log(Level.INFO, String.format(" Atoms %d-%d set to be not " + "used", nouseRange[0] + 1,
                    nouseRange[1] + 1));
            for (int i = nouseRange[0]; i <= nouseRange[1]; i++) {
                molaAtoms[i].setUse(false);
            }
        } catch (IllegalArgumentException ex) {
            logger.log(Level.INFO, ex.getLocalizedMessage());
        }
        /*Matcher m = intrangePattern.matcher(nouseKey);
        if (m.matches()) {
        int start = Integer.parseInt(m.group(1)) - 1;
        int end = Integer.parseInt(m.group(2)) - 1;
        if (start > end) {
            logger.log(Level.INFO, String.format(" Input %s not valid; "
                    + "start > end", nouseKey));
        } else if (start < 0) {
            logger.log(Level.INFO, String.format(" Input %s not valid; "
                    + "atoms should be indexed starting from 1", nouseKey));
        } else {
            logger.log(Level.INFO, String.format(" Atoms %s set to be not "
                    + "used", nouseKey));
            for (int i = start; i <= end; i++) {
                if (i >= nmolaAtoms) {
                    logger.log(Level.INFO, String.format(" Atom index %d is "
                            + "out of bounds for molecular assembly of "
                            + "length %d", i + 1, nmolaAtoms));
                    break;
                }
                molaAtoms[i].setUse(false);
            }
        }
        } else {
        try {
            int atNum = Integer.parseUnsignedInt(nouseKey) - 1;
            if (atNum >= nmolaAtoms) {
                logger.log(Level.INFO, String.format(" Atom index %d is "
                        + "out of bounds for molecular assembly of "
                        + "length %d", atNum + 1, nmolaAtoms));
            } else if (atNum < 0) {
                logger.log(Level.INFO, String.format(" Input %s not valid; "
                        + "atoms should be indexed starting from 1", nouseKey));
            } else {
                logger.log(Level.INFO, String.format(" Atom %s set to be not "
                        + "used", nouseKey));
                molaAtoms[atNum].setUse(false);
            }
        } catch (NumberFormatException ex) {
            logger.log(Level.INFO, String.format(" nouse key %s cannot "
                    + "be interpreted as an atom number or range of atom "
                    + "numbers.", nouseKey));
        }
        }*/
    }

    String[] inactiveKeys = properties.getStringArray("inactive");
    for (String inactiveKey : inactiveKeys) {
        try {
            int[] inactiveRange = parseAtNumArg("inactive", inactiveKey, nmolaAtoms);
            logger.log(Level.INFO, String.format(" Atoms %d-%d set to be not " + "used", inactiveRange[0] + 1,
                    inactiveRange[1] + 1));
            for (int i = inactiveRange[0]; i <= inactiveRange[1]; i++) {
                molaAtoms[i].setActive(false);
            }
        } catch (IllegalArgumentException ex) {
            logger.log(Level.INFO, ex.getLocalizedMessage());
        }
        /*Matcher m = intrangePattern.matcher(inactiveKey);
        if (m.matches()) {
        int start = Integer.parseInt(m.group(1)) - 1;
        int end = Integer.parseInt(m.group(2)) - 1;
        if (start > end) {
            logger.log(Level.INFO, String.format(" Input %s not valid; "
                    + "start > end", inactiveKey));
        } else if (start < 0) {
            logger.log(Level.INFO, String.format(" Input %s not valid; "
                    + "atoms should be indexed starting from 1", inactiveKey));
        } else {
            logger.log(Level.INFO, String.format(" Atoms %s set to be "
                    + "inactive", inactiveKey));
            for (int i = start; i <= end; i++) {
                if (i >= nmolaAtoms) {
                    logger.log(Level.INFO, String.format(" Atom index %d is "
                            + "out of bounds for molecular assembly of "
                            + "length %d", i + 1, nmolaAtoms));
                    break;
                }
                molaAtoms[i].setActive(false);
            }
        }
        } else {
        try {
            int atNum = Integer.parseUnsignedInt(inactiveKey) - 1;
            if (atNum >= nmolaAtoms) {
                logger.log(Level.INFO, String.format(" Atom index %d is "
                        + "out of bounds for molecular assembly of "
                        + "length %d", atNum + 1, nmolaAtoms));
            } else if (atNum < 0) {
                logger.log(Level.INFO, String.format(" Input %s not valid; "
                        + "atoms should be indexed starting from 1", inactiveKey));
            } else {
                logger.log(Level.INFO, String.format(" Atom %s set to be "
                        + "inactive", inactiveKey));
                molaAtoms[atNum].setActive(false);
            }
        } catch (NumberFormatException ex) {
            logger.log(Level.INFO, String.format(" inactive key %s cannot "
                    + "be interpreted as an atom number or range of atom "
                    + "numbers.", inactiveKey));
        }
        }*/
    }

    coordRestraints = new ArrayList<>();
    String[] cRestraintStrings = properties.getStringArray("restraint");
    for (String coordRestraint : cRestraintStrings) {
        String[] toks = coordRestraint.split("\\s+");
        double forceconst;
        try {
            forceconst = Double.parseDouble(toks[0]);
        } catch (NumberFormatException ex) {
            logger.log(Level.INFO,
                    " First argument to coordinate restraint must be a positive force constant; discarding coordinate restraint.");
            continue;
        }
        if (forceconst < 0) {
            logger.log(Level.INFO, " Force constants must be positive. Discarding coordinate restraint.");
            continue;
        }
        logger.info(String.format(
                " Adding lambda-disabled coordinate restraint " + "with force constant %10.4f kcal/mol/A",
                forceconst));
        Set<Atom> restraintAtoms = new HashSet<>();

        for (int i = 1; i < toks.length; i++) {
            try {
                int[] nouseRange = parseAtNumArg("restraint", toks[i], nmolaAtoms);
                logger.info(String.format(" Adding atoms %d-%d to restraint", nouseRange[0] + 1,
                        nouseRange[1] + 1));
                for (int j = nouseRange[0]; j <= nouseRange[1]; j++) {
                    restraintAtoms.add(molaAtoms[j]);
                }
            } catch (IllegalArgumentException ex) {
                boolean atomFound = false;
                for (Atom atom : molaAtoms) {
                    if (atom.getName().equalsIgnoreCase(toks[i])) {
                        atomFound = true;
                        restraintAtoms.add(atom);
                    }
                }
                if (atomFound) {
                    logger.info(String.format(" Added atoms with name %s to restraint", toks[i]));
                } else {
                    logger.log(Level.INFO, ex.getLocalizedMessage());
                }
            }
        }
        if (!restraintAtoms.isEmpty()) {
            Atom[] ats = restraintAtoms.toArray(new Atom[restraintAtoms.size()]);
            coordRestraints.add(new CoordRestraint(ats, forceField, false, forceconst));
        } else {
            logger.warning(String.format(" Empty or unparseable restraint argument %s", coordRestraint));
        }
    }

    String[] lamRestraintStrings = properties.getStringArray("lamrestraint");
    for (String coordRestraint : lamRestraintStrings) {
        String[] toks = coordRestraint.split("\\s+");
        double forceconst = Double.parseDouble(toks[0]);
        logger.info(String.format(
                " Adding lambda-enabled coordinate restraint " + "with force constant %10.4f kcal/mol/A",
                forceconst));
        Set<Atom> restraintAtoms = new HashSet<>();

        for (int i = 1; i < toks.length; i++) {
            try {
                int[] nouseRange = parseAtNumArg("restraint", toks[i], nmolaAtoms);
                logger.info(String.format(" Adding atoms %d-%d to restraint", nouseRange[0] + 1,
                        nouseRange[1] + 1));
                for (int j = nouseRange[0]; j <= nouseRange[1]; j++) {
                    restraintAtoms.add(molaAtoms[j]);
                }
            } catch (IllegalArgumentException ex) {
                boolean atomFound = false;
                for (Atom atom : molaAtoms) {
                    if (atom.getName().equalsIgnoreCase(toks[i])) {
                        atomFound = true;
                        restraintAtoms.add(atom);
                    }
                }
                if (atomFound) {
                    logger.info(String.format(" Added atoms with name %s to restraint", toks[i]));
                } else {
                    logger.log(Level.INFO,
                            String.format(
                                    " Restraint input %s " + "could not be parsed as a numerical range or "
                                            + "an atom type present in assembly",
                                    toks[i]));
                }
            }
        }
        if (!restraintAtoms.isEmpty()) {
            Atom[] ats = restraintAtoms.toArray(new Atom[restraintAtoms.size()]);
            coordRestraints.add(new CoordRestraint(ats, forceField, true, forceconst));
        } else {
            logger.warning(String.format(" Empty or unparseable restraint argument %s", coordRestraint));
        }
    }

    String[] noElStrings = properties.getStringArray("noElectro");
    for (String noE : noElStrings) {
        String[] toks = noE.split("\\s+");
        for (String tok : toks) {
            try {
                int[] noERange = parseAtNumArg("noElectro", tok, nmolaAtoms);
                for (int i = noERange[0]; i <= noERange[1]; i++) {
                    molaAtoms[i].setElectrostatics(false);
                }
                logger.log(Level.INFO, String.format(" Disabled electrostatics " + "for atoms %d-%d",
                        noERange[0] + 1, noERange[1] + 1));
            } catch (IllegalArgumentException ex) {
                boolean atomFound = false;
                for (Atom atom : molaAtoms) {
                    if (atom.getName().equalsIgnoreCase(tok)) {
                        atomFound = true;
                        atom.setElectrostatics(false);
                    }
                }
                if (atomFound) {
                    logger.info(String.format(" Disabled electrostatics for atoms with name %s", tok));
                } else {
                    logger.log(Level.INFO,
                            String.format(" No electrostatics " + "input %s could not be parsed as a numerical "
                                    + "range or atom type present in assembly", tok));
                }
            }
        }
    }
}

From source file:org.openestate.io.is24_csv.Is24CsvRecord.java

public Currency getWaehrung() {
    String value = this.get(FIELD_WAEHRUNG);
    try {//from w ww.  j a  v a 2s .c o m
        return (value != null) ? Currency.getInstance(value) : Currency.getInstance("EUR");
    } catch (IllegalArgumentException ex) {
        LOGGER.warn("Can't read currency '" + value + "'!");
        LOGGER.warn("> " + ex.getLocalizedMessage(), ex);
        return Currency.getInstance("EUR");
    }
}

From source file:com.bigdata.rdf.sail.webapp.UpdateServlet.java

/**
* Delete all statements materialized by a DESCRIBE or CONSTRUCT query and
* then insert all statements in the request body.
* <p>/*  w  w  w  .j  a v  a 2 s .co m*/
* Note: To avoid materializing the statements, this runs the query against
* the last commit time and uses a pipe to connect the query directly to the
* process deleting the statements. This is done while it is holding the
* unisolated connection which prevents concurrent modifications. Therefore
* the entire <code>SELECT + DELETE</code> operation is ACID.
*/
private void doUpdateWithQuery(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException {

    final String baseURI = req.getRequestURL().toString();

    final String namespace = getNamespace(req);

    final String queryStr = req.getParameter(QueryServlet.ATTR_QUERY);

    final boolean suppressTruthMaintenance = getBooleanValue(req, QueryServlet.ATTR_TRUTH_MAINTENANCE, false);

    if (queryStr == null)
        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
                "Required parameter not found: " + QueryServlet.ATTR_QUERY);

    final Map<String, Value> bindings = parseBindings(req, resp);
    if (bindings == null) { // invalid bindings definition generated error response 400 while parsing
        return;
    }

    final String contentType = req.getContentType();

    if (log.isInfoEnabled())
        log.info("Request body: " + contentType);

    /**
     * <a href="https://sourceforge.net/apps/trac/bigdata/ticket/620">
     * UpdateServlet fails to parse MIMEType when doing conneg. </a>
     */

    final RDFFormat requestBodyFormat = RDFFormat.forMIMEType(new MiniMime(contentType).getMimeType());

    if (requestBodyFormat == null) {

        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
                "Content-Type not recognized as RDF: " + contentType);

        return;

    }

    final RDFParserFactory rdfParserFactory = RDFParserRegistry.getInstance().get(requestBodyFormat);

    if (rdfParserFactory == null) {

        buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN,
                "Parser factory not found: Content-Type=" + contentType + ", format=" + requestBodyFormat);

        return;

    }

    /*
     * Allow the caller to specify the default context for insert.
     */
    final Resource[] defaultContextInsert;
    {
        final String[] s = req.getParameterValues("context-uri-insert");
        if (s != null && s.length > 0) {
            try {
                defaultContextInsert = toURIs(s);
            } catch (IllegalArgumentException ex) {
                buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, ex.getLocalizedMessage());
                return;
            }
        } else {
            defaultContextInsert = null;
        }
    }

    /*
     * Allow the caller to specify the default context for delete.
     */
    final Resource[] defaultContextDelete;
    {
        final String[] s = req.getParameterValues("context-uri-delete");
        if (s != null && s.length > 0) {
            try {
                defaultContextDelete = toURIs(s);
            } catch (IllegalArgumentException ex) {
                buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, ex.getLocalizedMessage());
                return;
            }
        } else {
            defaultContextDelete = null;
        }
    }

    try {

        if (getIndexManager().isGroupCommit()) {

            // compatible with group commit serializability semantics.
            submitApiTask(new UpdateWithQueryMaterializedTask(req, resp, namespace, ITx.UNISOLATED, //
                    queryStr, //
                    baseURI, //
                    suppressTruthMaintenance, //
                    bindings, //
                    rdfParserFactory, //
                    defaultContextDelete, //
                    defaultContextInsert//
            )).get();

        } else {

            // streaming implementation. not compatible with group commit.
            submitApiTask(new UpdateWithQueryStreamingTask(req, resp, namespace, ITx.UNISOLATED, //
                    queryStr, //
                    baseURI, //
                    suppressTruthMaintenance, //
                    bindings, //
                    rdfParserFactory, //
                    defaultContextDelete, //
                    defaultContextInsert//
            )).get();

        }

    } catch (Throwable t) {

        launderThrowable(t, resp,
                "UPDATE-WITH-QUERY" + ": queryStr=" + queryStr + ", baseURI=" + baseURI
                        + (defaultContextInsert == null ? ""
                                : ",context-uri-insert=" + Arrays.toString(defaultContextInsert))
                        + (defaultContextDelete == null ? ""
                                : ",context-uri-delete=" + Arrays.toString(defaultContextDelete)));

    }

}

From source file:org.kitodo.production.forms.ProzesskopieForm.java

private void proceedField(AdditionalField field) {
    LegacyDocStructHelperInterface docStruct = getDocStruct(field);
    try {/* w  ww.  j a v a  2  s  . co  m*/
        if (field.getMetadata().equals(LIST_OF_CREATORS)) {
            throw new UnsupportedOperationException("Dead code pending removal");
        } else {
            // evaluate the content in normal fields
            LegacyMetadataTypeHelper mdt = LegacyPrefsHelper.getMetadataType(
                    ServiceManager.getRulesetService().getPreferences(this.prozessKopie.getRuleset()),
                    field.getMetadata());
            LegacyMetadataHelper md = LegacyLogicalDocStructHelper.getMetadata(docStruct, mdt);
            if (Objects.nonNull(md)) {
                field.setValue(md.getValue());
                md.setStringValue(field.getValue().replace("&amp;", "&"));
            }
        }
    } catch (IllegalArgumentException e) {
        Helper.setErrorMessage(e.getLocalizedMessage(), logger, e);
    }
}

From source file:org.apache.hadoop.hdfs.tools.DFSAdmin.java

/**
 * @param argv/*from   w w w  . j  a  v a2 s .c  o  m*/
 *     The parameters passed to this program.
 * @return 0 on success, non zero on error.
 * @throws Exception
 *     if the filesystem does not exist.
 */
@Override
public int run(String[] argv) throws Exception {

    if (argv.length < 1) {
        printUsage("");
        return -1;
    }

    int exitCode = -1;
    int i = 0;
    String cmd = argv[i++];

    //
    // verify that we have enough command line parameters
    //
    if ("-safemode".equals(cmd)) {
        if (argv.length != 2) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-report".equals(cmd)) {
        if (argv.length < 1) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-refreshNodes".equals(cmd)) {
        if (argv.length != 1) {
            printUsage(cmd);
            return exitCode;
        }
    } else if (RollingUpgradeCommand.matches(cmd)) {
        if (argv.length < 1 || argv.length > 2) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-refreshServiceAcl".equals(cmd)) {
        if (argv.length != 1) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-refresh".equals(cmd)) {
        if (argv.length < 3) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-refreshUserToGroupsMappings".equals(cmd)) {
        if (argv.length != 1) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-printTopology".equals(cmd)) {
        if (argv.length != 1) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-reconfig".equals(cmd)) {
        if (argv.length != 4) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-deleteBlockPool".equals(cmd)) {
        if ((argv.length != 3) && (argv.length != 4)) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-setBalancerBandwidth".equals(cmd)) {
        if (argv.length != 2) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-triggerBlockReport".equals(cmd)) {
        if (argv.length < 1) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-shutdownDatanode".equals(cmd)) {
        if ((argv.length != 2) && (argv.length != 3)) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-getDatanodeInfo".equals(cmd)) {
        if (argv.length != 2) {
            printUsage(cmd);
            return exitCode;
        }
    }

    // initialize DFSAdmin
    try {
        init();
    } catch (RPC.VersionMismatch v) {
        System.err.println("Version Mismatch between client and server" + "... command aborted.");
        return exitCode;
    } catch (IOException e) {
        System.err.println("Bad connection to DFS... command aborted.");
        return exitCode;
    }

    Exception debugException = null;
    exitCode = 0;
    try {
        if ("-report".equals(cmd)) {
            report(argv, i);
        } else if ("-safemode".equals(cmd)) {
            setSafeMode(argv, i);
        } else if ("-refreshNodes".equals(cmd)) {
            exitCode = refreshNodes();
        } else if (RollingUpgradeCommand.matches(cmd)) {
            exitCode = RollingUpgradeCommand.run(getDFS(), argv, i);
        } else if ("-metasave".equals(cmd)) {
            System.out.println("metasave is not supported by hops");
        } else if (ClearQuotaCommand.matches(cmd)) {
            exitCode = new ClearQuotaCommand(argv, i, getDFS()).runAll();
        } else if (SetQuotaCommand.matches(cmd)) {
            exitCode = new SetQuotaCommand(argv, i, getDFS()).runAll();
        } else if (ClearSpaceQuotaCommand.matches(cmd)) {
            exitCode = new ClearSpaceQuotaCommand(argv, i, getDFS()).runAll();
        } else if (SetSpaceQuotaCommand.matches(cmd)) {
            exitCode = new SetSpaceQuotaCommand(argv, i, getDFS()).runAll();
        } else if ("-refreshServiceAcl".equals(cmd)) {
            exitCode = refreshServiceAcl();
        } else if ("-refreshUserToGroupsMappings".equals(cmd)) {
            exitCode = refreshUserToGroupsMappings();
        } else if ("-refreshSuperUserGroupsConfiguration".equals(cmd)) {
            exitCode = refreshSuperUserGroupsConfiguration();
        } else if ("-refreshCallQueue".equals(cmd)) {
            exitCode = refreshCallQueue();
        } else if ("-refresh".equals(cmd)) {
            exitCode = genericRefresh(argv, i);
        } else if ("-printTopology".equals(cmd)) {
            exitCode = printTopology();
        } else if ("-deleteBlockPool".equals(cmd)) {
            exitCode = deleteBlockPool(argv, i);
        } else if ("-setBalancerBandwidth".equals(cmd)) {
            exitCode = setBalancerBandwidth(argv, i);
        } else if ("-triggerBlockReport".equals(cmd)) {
            exitCode = triggerBlockReport(argv);
        } else if ("-shutdownDatanode".equals(cmd)) {
            exitCode = shutdownDatanode(argv, i);
        } else if ("-getDatanodeInfo".equals(cmd)) {
            exitCode = getDatanodeInfo(argv, i);
        } else if ("-reconfig".equals(cmd)) {
            exitCode = reconfig(argv, i);
        } else if ("-help".equals(cmd)) {
            if (i < argv.length) {
                printHelp(argv[i]);
            } else {
                printHelp("");
            }
        } else {
            exitCode = -1;
            System.err.println(cmd.substring(1) + ": Unknown command");
            printUsage("");
        }
    } catch (IllegalArgumentException arge) {
        debugException = arge;
        exitCode = -1;
        System.err.println(cmd.substring(1) + ": " + arge.getLocalizedMessage());
        printUsage(cmd);
    } catch (RemoteException e) {
        //
        // This is a error returned by hadoop server. Print
        // out the first line of the error message, ignore the stack trace.
        exitCode = -1;
        debugException = e;
        try {
            String[] content;
            content = e.getLocalizedMessage().split("\n");
            System.err.println(cmd.substring(1) + ": " + content[0]);
        } catch (Exception ex) {
            System.err.println(cmd.substring(1) + ": " + ex.getLocalizedMessage());
            debugException = ex;
        }
    } catch (Exception e) {
        exitCode = -1;
        debugException = e;
        System.err.println(cmd.substring(1) + ": " + e.getLocalizedMessage());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Exception encountered:", debugException);
    }
    return exitCode;
}

From source file:org.archive.wayback.liveweb.ArcRemoteLiveWebCache.java

public Resource getCachedResource(URL url, long maxCacheMS, boolean bUseOlder)
        throws LiveDocumentNotAvailableException, LiveWebCacheUnavailableException, LiveWebTimeoutException,
        IOException {//w w  w  .j a  va 2  s  .co m
    String urlString = url.toExternalForm();

    if (requestPrefix != null) {
        urlString = requestPrefix + urlString;
    }

    HttpMethod method = null;
    try {
        method = new GetMethod(urlString);
    } catch (IllegalArgumentException e) {
        LOGGER.warning("Bad URL for live web fetch:" + urlString);
        throw new LiveDocumentNotAvailableException("Url:" + urlString + "does not look like an URL?");
    }
    boolean success = false;
    try {
        int status = http.executeMethod(method);
        if (status == 200) {

            ByteArrayInputStream bais = new ByteArrayInputStream(method.getResponseBody());
            ARCRecord r = new ARCRecord(new GZIPInputStream(bais), "id", 0L, false, false, true);
            ArcResource ar = (ArcResource) ResourceFactory.ARCArchiveRecordToResource(r, null);
            if (ar.getStatusCode() == 502) {
                throw new LiveDocumentNotAvailableException(urlString);
            } else if (ar.getStatusCode() == 504) {
                throw new LiveWebTimeoutException("Timeout:" + urlString);
            }
            success = true;
            return ar;

        } else {
            throw new LiveWebCacheUnavailableException(urlString);
        }

    } catch (ResourceNotAvailableException e) {
        throw new LiveDocumentNotAvailableException(urlString);

    } catch (NoHttpResponseException e) {

        throw new LiveWebCacheUnavailableException("No Http Response for " + urlString);

    } catch (ConnectException e) {
        throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString);
    } catch (SocketException e) {
        throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString);
    } catch (SocketTimeoutException e) {
        throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString);
    } catch (ConnectTimeoutException e) {
        throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString);
    } finally {
        if (!success) {
            method.abort();
        }
        method.releaseConnection();
    }
}

From source file:org.deegree.services.wms.controller.WMSController.java

@Override
public void doKVP(Map<String, String> map, HttpServletRequest request, HttpResponseBuffer response,
        List<FileItem> multiParts) throws ServletException, IOException {
    String v = map.get("VERSION");
    if (v == null) {
        v = map.get("WMTVER");
    }/*  w w w  . j  a v a 2 s . co  m*/
    Version version = v == null ? highestVersion : parseVersion(v);

    WMSRequestType req;
    try {
        req = (WMSRequestType) ((ImplementationMetadata) ((OWSProvider) getMetadata().getProvider())
                .getImplementationMetadata()).getRequestTypeByName(map.get("REQUEST"));
    } catch (IllegalArgumentException e) {
        controllers.get(version)
                .sendException(new OWSException(get("WMS.OPERATION_NOT_KNOWN", map.get("REQUEST")),
                        OWSException.OPERATION_NOT_SUPPORTED), response, this);
        return;
    } catch (NullPointerException e) {
        controllers.get(version).sendException(
                new OWSException(get("WMS.PARAM_MISSING", "REQUEST"), OWSException.OPERATION_NOT_SUPPORTED),
                response, this);
        return;
    }

    try {
        handleRequest(req, response, map, version);
    } catch (OWSException e) {
        if (controllers.get(version) == null) {
            // happens if non capabilities request is made with unsupported version
            version = highestVersion;
        }

        LOG.debug("The response is an exception with the message '{}'", e.getLocalizedMessage());
        LOG.trace("Stack trace of OWSException being sent", e);

        controllers.get(version).handleException(map, req, e, response, this);
    }
}

From source file:com.gs.collections.impl.test.Verify.java

public static void assertShallowClone(String itemName, Cloneable object) {
    try {/*from www . j a  v a2  s  .c  o  m*/
        Method method = Object.class.getDeclaredMethod("clone", (Class<?>[]) null);
        method.setAccessible(true);
        Object clone = method.invoke(object);
        String prefix = itemName + " and its clone";
        Assert.assertNotSame(prefix, object, clone);
        Verify.assertEqualsAndHashCode(prefix, object, clone);
    } catch (IllegalArgumentException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (InvocationTargetException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (SecurityException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (NoSuchMethodException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (IllegalAccessException e) {
        throw new AssertionError(e.getLocalizedMessage());
    } catch (AssertionError e) {
        Verify.throwMangledException(e);
    }
}

From source file:org.apache.jxtadoop.fs.FsShell.java

/**
 * run//from  www  .jav a2 s .  c  o  m
 */
public int run(String argv[]) throws Exception {

    if (argv.length < 1) {
        printUsage("");
        return -1;
    }

    int exitCode = -1;
    int i = 0;
    String cmd = argv[i++];

    //
    // verify that we have enough command line parameters
    //
    if ("-put".equals(cmd) || "-test".equals(cmd) || "-copyFromLocal".equals(cmd)
            || "-moveFromLocal".equals(cmd)) {
        if (argv.length < 3) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-get".equals(cmd) || "-copyToLocal".equals(cmd) || "-moveToLocal".equals(cmd)) {
        if (argv.length < 3) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-mv".equals(cmd) || "-cp".equals(cmd)) {
        if (argv.length < 3) {
            printUsage(cmd);
            return exitCode;
        }
    } else if ("-rm".equals(cmd) || "-rmr".equals(cmd) || "-cat".equals(cmd) || "-mkdir".equals(cmd)
            || "-touchz".equals(cmd) || "-stat".equals(cmd) || "-text".equals(cmd) || "-checksum".equals(cmd)) {
        if (argv.length < 2) {
            printUsage(cmd);
            return exitCode;
        }
    }

    // initialize FsShell
    try {
        init();
    } catch (RPC.VersionMismatch v) {
        System.err.println("Version Mismatch between client and server" + "... command aborted.");
        return exitCode;
    } catch (IOException e) {
        System.err.println("Bad connection to FS. command aborted.");
        return exitCode;
    }

    exitCode = 0;
    try {
        if ("-put".equals(cmd) || "-copyFromLocal".equals(cmd)) {
            Path[] srcs = new Path[argv.length - 2];
            for (int j = 0; i < argv.length - 1;)
                srcs[j++] = new Path(argv[i++]);
            copyFromLocal(srcs, argv[i++]);
        } else if ("-moveFromLocal".equals(cmd)) {
            Path[] srcs = new Path[argv.length - 2];
            for (int j = 0; i < argv.length - 1;)
                srcs[j++] = new Path(argv[i++]);
            moveFromLocal(srcs, argv[i++]);
        } else if ("-get".equals(cmd) || "-copyToLocal".equals(cmd)) {
            copyToLocal(argv, i);
        } else if ("-getmerge".equals(cmd)) {
            if (argv.length > i + 2)
                copyMergeToLocal(argv[i++], new Path(argv[i++]), Boolean.parseBoolean(argv[i++]));
            else
                copyMergeToLocal(argv[i++], new Path(argv[i++]));
        } else if ("-cat".equals(cmd)) {
            exitCode = doall(cmd, argv, i);
        } else if ("-text".equals(cmd)) {
            exitCode = doall(cmd, argv, i);
        } else if ("-moveToLocal".equals(cmd)) {
            moveToLocal(argv[i++], new Path(argv[i++]));
        } else if ("-setrep".equals(cmd)) {
            setReplication(argv, i);
        } else if ("-chmod".equals(cmd) || "-chown".equals(cmd) || "-chgrp".equals(cmd)) {
            FsShellPermissions.changePermissions(fs, cmd, argv, i, this);
        } else if ("-ls".equals(cmd)) {
            if (i < argv.length) {
                exitCode = doall(cmd, argv, i);
            } else {
                exitCode = ls(Path.CUR_DIR, false);
            }
        } else if ("-lsr".equals(cmd)) {
            if (i < argv.length) {
                exitCode = doall(cmd, argv, i);
            } else {
                exitCode = ls(Path.CUR_DIR, true);
            }
        } else if ("-mv".equals(cmd)) {
            exitCode = rename(argv, getConf());
        } else if ("-cp".equals(cmd)) {
            exitCode = copy(argv, getConf());
        } else if ("-rm".equals(cmd)) {
            exitCode = doall(cmd, argv, i);
        } else if ("-rmr".equals(cmd)) {
            exitCode = doall(cmd, argv, i);
        } else if ("-expunge".equals(cmd)) {
            expunge();
        } else if ("-du".equals(cmd)) {
            if (i < argv.length) {
                exitCode = doall(cmd, argv, i);
            } else {
                du(".");
            }
        } else if ("-dus".equals(cmd)) {
            if (i < argv.length) {
                exitCode = doall(cmd, argv, i);
            } else {
                dus(".");
            }
        } else if (Count.matches(cmd)) {
            exitCode = new Count(argv, i, getConf()).runAll();
        } else if ("-mkdir".equals(cmd)) {
            exitCode = doall(cmd, argv, i);
        } else if ("-touchz".equals(cmd)) {
            exitCode = doall(cmd, argv, i);
        } else if ("-test".equals(cmd)) {
            exitCode = test(argv, i);
        } else if ("-stat".equals(cmd)) {
            if (i + 1 < argv.length) {
                stat(argv[i++].toCharArray(), argv[i++]);
            } else {
                stat("%y".toCharArray(), argv[i]);
            }
        } else if ("-checksum".equals(cmd)) {
            checksum(argv[i++]);
        } else if ("-help".equals(cmd)) {
            if (i < argv.length) {
                printHelp(argv[i]);
            } else {
                printHelp("");
            }
        } else if ("-tail".equals(cmd)) {
            tail(argv, i);
        } else {
            exitCode = -1;
            System.err.println(cmd.substring(1) + ": Unknown command");
            printUsage("");
        }
    } catch (IllegalArgumentException arge) {
        exitCode = -1;
        System.err.println(cmd.substring(1) + ": " + arge.getLocalizedMessage());
        printUsage(cmd);
    } catch (RemoteException e) {
        //
        // This is a error returned by hadoop server. Print
        // out the first line of the error mesage, ignore the stack trace.
        exitCode = -1;
        try {
            String[] content;
            content = e.getLocalizedMessage().split("\n");
            System.err.println(cmd.substring(1) + ": " + content[0]);
        } catch (Exception ex) {
            System.err.println(cmd.substring(1) + ": " + ex.getLocalizedMessage());
        }
    } catch (IOException e) {
        //
        // IO exception encountered locally.
        // 
        exitCode = -1;
        System.err.println(cmd.substring(1) + ": " + e.getLocalizedMessage());
    } catch (Exception re) {
        exitCode = -1;
        System.err.println(cmd.substring(1) + ": " + re.getLocalizedMessage());
    } finally {
    }
    return exitCode;
}