Example usage for java.lang IllegalArgumentException getCause

List of usage examples for java.lang IllegalArgumentException getCause

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:jp.terasoluna.fw.util.ConvertUtilTest.java

/**
 * testConvertObjectClassboolean02() <br>
 * <br>//from w w w.  j ava  2  s .c  om
 * () <br>
 * G <br>
 * <br>
 * () obj:null<br>
 * () clazz:Object.class<br>
 * () allowsNull:false<br>
 * <br>
 * () :IllegalArgumentException<br>
 * ?: "Unable to cast 'null' to '" + clazz??? + "'"<br>
 * ??:ClassCastException<br>
 * ???: "Unable to cast 'null' to '" + clazz??? + "'"<br>
 * <br>
 * clazz?null??????obj?null?allowsNull?false????? IllegalArgumentException?????? <br>
 * @throws Exception ?????
 */
@Test
public void testConvertObjectClassboolean02() throws Exception {
    // 
    try {
        ConvertUtil.convert(null, Object.class, false);
        fail("IllegalArgumentException???????");
    } catch (IllegalArgumentException e) {
        // 
        assertEquals(IllegalArgumentException.class.getName(), e.getClass().getName());
        assertEquals("Unable to cast 'null' to '" + Object.class.getName() + "'", e.getMessage());
        assertEquals(ClassCastException.class.getName(), e.getCause().getClass().getName());
        assertEquals("Unable to cast 'null' to '" + Object.class.getName() + "'", e.getCause().getMessage());
    }
}

From source file:jp.terasoluna.fw.util.ConvertUtilTest.java

/**
 * testToList06() <br>/*from w w w.  j  a  v  a2s .  com*/
 * <br>
 * () <br>
 * G <br>
 * <br>
 * () obj:"list"<br>
 * () elementClass:Thread.class<br>
 * <br>
 * () :IllegalArgumentException<br>
 * ?: "Unable to cast '" + obj??? + "' to '" + elementClass??? + "'"<br>
 * ??:ClassCastException<br>
 * ???:"Unable to cast '" + obj??? + "' to '" + elementClass??? + "'"<br>
 * <br>
 * obj??elementClass???????????? ??????IllegalArgumentException?????? <br>
 * @throws Exception ?????
 */
@Test
public void testToList06() throws Exception {
    // 
    try {
        ConvertUtil.toList("list", Thread.class);
        fail("IllegalArgumentException???????");
    } catch (IllegalArgumentException e) {
        // 
        assertEquals(IllegalArgumentException.class.getName(), e.getClass().getName());
        assertEquals("Unable to cast '" + "list".getClass().getName() + "' to '" + Thread.class.getName() + "'",
                e.getMessage());
        assertEquals(ClassCastException.class.getName(), e.getCause().getClass().getName());
        assertEquals("Unable to cast '" + "list".getClass().getName() + "' to '" + Thread.class.getName() + "'",
                e.getCause().getMessage());
    }

}

From source file:jp.terasoluna.fw.util.ConvertUtilTest.java

/**
 * testToList10() <br>/*from  ww w  . j a  v a 2  s . com*/
 * <br>
 * () <br>
 * G <br>
 * <br>
 * () obj:????Object[]<br>
 * *?0:"foo"<br>
 * *?2:Thread<br>
 * *?3:"baz"<br>
 * () elementClass:String.class<br>
 * <br>
 * () :IllegalArgumentException<br>
 * ?: "Unable to cast '" + Thread??? + "' to '" + elementClass??? + "'"<br>
 * ??:ClassCastException<br>
 * ???: "Unable to cast '" + Thread??? + "' to '" + elementClass??? + "'"<br>
 * <br>
 * obj???elementClass?????????????? ?????????IllegalArgumentException???? ?? <br>
 * @throws Exception ?????
 */
@Test
public void testToList10() throws Exception {
    // ??
    Object[] obj = new Object[3];
    obj[0] = "foo";
    obj[1] = new Thread();
    obj[2] = "baz";

    // 
    try {
        ConvertUtil.toList(obj, String.class);
        fail("IllegalArgumentException???????");
    } catch (IllegalArgumentException e) {
        // 
        assertEquals(IllegalArgumentException.class.getName(), e.getClass().getName());
        assertEquals("Unable to cast '" + Thread.class.getName() + "' to '" + String.class.getName() + "'",
                e.getMessage());
        assertEquals(ClassCastException.class.getName(), e.getCause().getClass().getName());
        assertEquals("Unable to cast '" + Thread.class.getName() + "' to '" + String.class.getName() + "'",
                e.getCause().getMessage());
    }
}

From source file:jp.terasoluna.fw.util.ConvertUtilTest.java

/**
 * testToList14() <br>/*  w ww  .jav a  2  s.c o  m*/
 * <br>
 * () <br>
 * G <br>
 * <br>
 * () obj:????Collection<br>
 * *?0:"foo"<br>
 * *?2:Thread<br>
 * *?3:"baz"<br>
 * () elementClass:String.class<br>
 * <br>
 * () :IllegalArgumentException<br>
 * ?: "Unable to cast '" + Thread??? + "' to '" + elementClass??? + "'"<br>
 * ??:ClassCastException<br>
 * ???: "Unable to cast '" + Thread??? + "' to '" + elementClass??? + "'"<br>
 * <br>
 * obj?Collection?elementClass?????????? ?????????????IllegalArgumentException???? ?? <br>
 * @throws Exception ?????
 */
@Test
public void testToList14() throws Exception {
    // ??
    Object[] obj = new Object[3];
    obj[0] = "foo";
    obj[1] = new Thread();
    obj[2] = "baz";

    // 
    try {
        ConvertUtil.toList(obj, String.class);
        fail("IllegalArgumentException???????");
    } catch (IllegalArgumentException e) {
        // 
        assertEquals(IllegalArgumentException.class.getName(), e.getClass().getName());
        assertEquals("Unable to cast '" + Thread.class.getName() + "' to '" + String.class.getName() + "'",
                e.getMessage());
        assertEquals(ClassCastException.class.getName(), e.getCause().getClass().getName());
        assertEquals("Unable to cast '" + Thread.class.getName() + "' to '" + String.class.getName() + "'",
                e.getCause().getMessage());
    }
}

From source file:org.evosuite.testcase.ConstantInliner.java

/** {@inheritDoc} */
@Override/*from   ww w. j av a  2s  . c  o  m*/
public void afterStatement(Statement statement, Scope scope, Throwable exception) {
    try {
        for (VariableReference var : statement.getVariableReferences()) {
            if (var.equals(statement.getReturnValue())
                    || var.equals(statement.getReturnValue().getAdditionalVariableReference()))
                continue;
            Object object = var.getObject(scope);

            if (var.isPrimitive()) {
                ConstantValue value = new ConstantValue(test, var.getGenericClass());
                value.setValue(object);
                // logger.info("Statement before inlining: " +
                // statement.getCode());
                statement.replace(var, value);
                // logger.info("Statement after inlining: " +
                // statement.getCode());
            } else if (var.isString() && object != null) {
                ConstantValue value = new ConstantValue(test, var.getGenericClass());
                try {
                    String val = StringEscapeUtils.unescapeJava(new String(object.toString()));
                    if (val.length() < Properties.MAX_STRING) {
                        value.setValue(val);
                        statement.replace(var, value);
                    }
                } catch (IllegalArgumentException e) {
                    // Exceptions may happen if strings are not valid
                    // unicode
                    logger.info("Cannot escape invalid string: " + object);
                }
                // logger.info("Statement after inlining: " +
                // statement.getCode());
            } else if (var.isArrayIndex()) {
                // If this is an array index and there is an object outside
                // the array
                // then replace the array index with that object
                for (VariableReference otherVar : scope.getElements(var.getType())) {
                    Object otherObject = otherVar.getObject(scope);
                    if (otherObject == object && !otherVar.isArrayIndex()
                            && otherVar.getStPosition() < statement.getPosition()) {
                        statement.replace(var, otherVar);
                        break;
                    }
                }
            } else {
                // TODO: Ignoring exceptions during getObject, but keeping
                // the assertion for now
                if (object == null) {
                    if (statement instanceof MethodStatement) {
                        MethodStatement ms = (MethodStatement) statement;
                        if (var.equals(ms.getCallee())) {
                            // Don't put null in callee's, the compiler will not accept it
                            continue;
                        }
                    } else if (statement instanceof FieldStatement) {
                        FieldStatement fs = (FieldStatement) statement;
                        if (var.equals(fs.getSource())) {
                            // Don't put null in source, the compiler will not accept it
                            continue;
                        }
                    }
                    ConstantValue value = new ConstantValue(test, var.getGenericClass());
                    value.setValue(null);
                    // logger.info("Statement before inlining: " +
                    // statement.getCode());
                    statement.replace(var, value);
                    // logger.info("Statement after inlining: " +
                    // statement.getCode());
                }
            }
        }
    } catch (CodeUnderTestException e) {
        logger.warn("Not inlining test: " + e.getCause());
        // throw new AssertionError("This case isn't handled yet: " +
        // e.getCause()
        // + ", " + Arrays.asList(e.getStackTrace()));
    }

}

From source file:org.tango.server.servant.DeviceImpl.java

/**
 * Stops polling calls delete method {@link Delete}. Called before init and
 * at server shutdown//from ww w  . j a  v  a 2s. com
 *
 * @throws DevFailed
 */
public void deleteDevice() throws DevFailed {
    MDC.put(MDC_KEY, name);
    xlogger.entry();
    PropertiesUtils.clearCache();
    PropertiesUtils.clearDeviceCache(name);
    PropertiesUtils.clearClassCache(className);
    stopPolling();
    pollingManager.removeAll();
    if (deviceScheduler != null) {
        deviceScheduler.stop();
    }
    if (interfaceChangeSender != null) {
        interfaceChangeSender.stop();
    }
    if (deleteMethod != null) {
        try {
            deleteMethod.invoke(businessObject);
        } catch (final IllegalArgumentException e) {
            DevFailedUtils.throwDevFailed(e);
        } catch (final IllegalAccessException e) {
            DevFailedUtils.throwDevFailed(e);
        } catch (final InvocationTargetException e) {
            if (e.getCause() instanceof DevFailed) {
                throw (DevFailed) e.getCause();
            } else {
                DevFailedUtils.throwDevFailed(e.getCause());
            }
        }
    }
    xlogger.exit();
}

From source file:org.nuclos.client.main.MainController.java

public void miDelegator(ActionEvent evt, Method m) {
    try {// w ww. j  a v a 2  s .com
        if (m.getParameterTypes().length == 0)
            m.invoke(MainController.this, new Object[0]);
        else
            m.invoke(MainController.this, new Object[] { evt });
    } catch (IllegalArgumentException e) {
        throw new CommonFatalException(e);
    } catch (IllegalAccessException e) {
        throw new CommonFatalException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e.getCause());
    }
}

From source file:de.tu_dortmund.ub.hb_ng.SolRDF.java

private String doResourceRequest(String graph, String uri, String format, boolean isAuthorized)
        throws LinkedDataStorageException {

    this.logger.info("doResourceRequest: graph=" + graph);
    this.logger.info("doResourceRequest: uri=" + uri);
    this.logger.info("doResourceRequest: format=" + format);
    this.logger.info("doResourceRequest: isAuthorized=" + isAuthorized);

    if (graph == null || graph.equals("")) {

        graph = this.config.getProperty("storage.graph.default");
    }//from   w w w.  jav  a 2 s .co  m
    this.logger.info("doResourceRequest: graph=" + graph);

    String result = null;

    try {

        // query resource in de.tu_dortmund.ub.hb_ng.data.SolRDF
        String selectQuery = "SELECT ?p ?o ?c WHERE { GRAPH ?c { <" + uri + "> ?p ?o } }"; // TODO config

        String resultString = this.sparqlQuery(null, URLEncoder.encode(selectQuery, "UTF-8"), "xml",
                isAuthorized);

        // postprocessing
        SPARQLResultsXMLParser xmlRes = new SPARQLResultsXMLParser();
        TupleQueryResultBuilder build = new TupleQueryResultBuilder();
        xmlRes.setTupleQueryResultHandler(build);

        ByteArrayInputStream is = new ByteArrayInputStream(resultString.getBytes("UTF-8"));
        xmlRes.parse(is);

        TupleQueryResult tupleRes = build.getQueryResult();
        List<String> bindingNames = tupleRes.getBindingNames();

        ArrayList<Statement> statements = new ArrayList<Statement>();
        ValueFactory valueFactory = ValueFactoryImpl.getInstance();

        while (tupleRes.hasNext()) {

            BindingSet bindingSet = tupleRes.next();

            String predicate = bindingSet.getValue(bindingNames.get(0)).stringValue();
            String object = bindingSet.getValue(bindingNames.get(1)).stringValue();
            String context = bindingSet.getValue(bindingNames.get(2)).stringValue();

            // isAuthorized > public + nonpublic
            if (isAuthorized && context.contains(this.config.getProperty("storage.graph.main"))
                    || context.contains(graph)) {

                try {
                    statements.add(valueFactory.createStatement(valueFactory.createURI(uri),
                            valueFactory.createURI(predicate), valueFactory.createURI(object),
                            valueFactory.createURI(context)));
                } catch (IllegalArgumentException e) {
                    statements.add(valueFactory.createStatement(valueFactory.createURI(uri),
                            valueFactory.createURI(predicate), valueFactory.createLiteral(object),
                            valueFactory.createURI(context)));
                }
            }
            // !isAuthorized > public
            if (!isAuthorized && context.endsWith(this.config.getProperty("storage.graph.main") + "-public")
                    || context.endsWith(graph + "-public")) {

                try {
                    statements.add(valueFactory.createStatement(valueFactory.createURI(uri),
                            valueFactory.createURI(predicate), valueFactory.createURI(object),
                            valueFactory.createURI(context)));
                } catch (IllegalArgumentException e) {
                    statements.add(valueFactory.createStatement(valueFactory.createURI(uri),
                            valueFactory.createURI(predicate), valueFactory.createLiteral(object),
                            valueFactory.createURI(context)));
                }
            }
        }

        if (statements.size() == 0) {

            result = null;
        } else {

            RDFFormat formatString;
            switch (format) {

            case "html": {

                formatString = RDFFormat.RDFXML;
                break;
            }
            case "rdf.xml": {

                formatString = RDFFormat.RDFXML;
                break;
            }
            case "rdf.ttl": {

                formatString = RDFFormat.TURTLE;
                break;
            }
            case "json": {

                formatString = RDFFormat.JSONLD;
                break;
            }
            case "nquads": {

                formatString = RDFFormat.NQUADS;
                break;
            }
            default: {

                formatString = RDFFormat.NQUADS;
            }
            }

            StringWriter stringWriter = new StringWriter();
            RDFWriter writer = Rio.createWriter(formatString, stringWriter);
            writer.startRDF();
            for (Statement statement : statements) {
                writer.handleStatement(statement);
            }
            writer.endRDF();

            result = stringWriter.toString();
        }
    } catch (Exception e) {

        e.printStackTrace();
        this.logger.error("[" + this.getClass().getName() + "] " + new Date()
                + " - ERROR: Requesting Linked Media Framework: " + uri + " - " + e.getMessage());
        throw new LinkedDataStorageException(e.getMessage(), e.getCause());
    }

    return result;
}

From source file:io.druid.indexing.jdbc.JDBCIndexTask.java

@Override
public TaskStatus run(final TaskToolbox toolbox) throws Exception {
    log.info("Starting up!");
    startTime = DateTime.now();/* w w w .  j a v a2  s.co m*/
    mapper = toolbox.getObjectMapper();
    status = Status.STARTING;

    if (chatHandlerProvider.isPresent()) {
        log.info("Found chat handler of class[%s]", chatHandlerProvider.get().getClass().getName());
        chatHandlerProvider.get().register(getId(), this, false);
    } else {
        log.warn("No chat handler detected");
    }

    runThread = Thread.currentThread();

    // Set up FireDepartmentMetrics
    final FireDepartment fireDepartmentForMetrics = new FireDepartment(dataSchema,
            new RealtimeIOConfig(null, null, null), null);
    fireDepartmentMetrics = fireDepartmentForMetrics.getMetrics();
    toolbox.getMonitorScheduler()
            .addMonitor(new RealtimeMetricsMonitor(ImmutableList.of(fireDepartmentForMetrics),
                    ImmutableMap.of(DruidMetrics.TASK_ID, new String[] { getId() })));

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUsername(ioConfig.getUser());
    dataSource.setPassword(ioConfig.getPassword());
    dataSource.setUrl(ioConfig.getConnectURI());
    dataSource.setDriverClassLoader(getClass().getClassLoader());

    final String table = ioConfig.getTableName();

    if (!StringUtils.isEmpty(ioConfig.getDriverClass())) {
        dataSource.setDriverClassName(ioConfig.getDriverClass());
    }

    final Handle handle = new DBI(dataSource).open();
    try (final Appenderator appenderator0 = newAppenderator(fireDepartmentMetrics, toolbox);
            final AppenderatorDriver driver = newDriver(appenderator0, toolbox, fireDepartmentMetrics)) {
        toolbox.getDataSegmentServerAnnouncer().announce();
        appenderator = appenderator0;

        // Start up, set up initial offsets.
        final Object restoredMetadata = driver.startJob();
        if (restoredMetadata == null) {
            nextOffsets.putAll(ioConfig.getJdbcOffsets().getOffsetMaps());
        } else {
            final Map<String, Object> restoredMetadataMap = (Map) restoredMetadata;
            final JDBCOffsets restoredNextPartitions = toolbox.getObjectMapper()
                    .convertValue(restoredMetadataMap.get(METADATA_NEXT_OFFSETS), JDBCOffsets.class);
            nextOffsets.putAll(restoredNextPartitions.getOffsetMaps());

            // Sanity checks.
            if (!restoredNextPartitions.getTable().equals(ioConfig.getTableName())) {
                throw new ISE("WTF?! Restored table[%s] but expected table[%s]",
                        restoredNextPartitions.getTable(), ioConfig.getTableName());
            }

            if (!nextOffsets.equals(ioConfig.getJdbcOffsets().getOffsetMaps())) {
                throw new ISE("WTF?! Restored partitions[%s] but expected partitions[%s]", nextOffsets,
                        ioConfig.getJdbcOffsets().getOffsetMaps());
            }
        }

        // Set up sequenceNames.

        final Map<Integer, String> sequenceNames = Maps.newHashMap();
        for (Integer partitionNum : nextOffsets.keySet()) {
            sequenceNames.put(partitionNum,
                    String.format("%s_%s", ioConfig.getBaseSequenceName(), partitionNum));
        }

        // Set up committer.
        final Supplier<Committer> committerSupplier = new Supplier<Committer>() {
            @Override
            public Committer get() {
                final Map<Integer, Long> snapshot = ImmutableMap.copyOf(nextOffsets);

                return new Committer() {
                    @Override
                    public Object getMetadata() {
                        return ImmutableMap.of(METADATA_NEXT_OFFSETS,
                                new JDBCOffsets(ioConfig.getJdbcOffsets().getTable(), snapshot));

                    }

                    @Override
                    public void run() {
                        // Do nothing.
                    }
                };
            }
        };

        //      Set<Integer> assignment = assignPartitionsAndSeekToNext(handle);
        //      boolean stillReading = !assignment.isEmpty();
        status = Status.READING;
        try {
            //        while (stillReading) {
            //          if (possiblyPause(assignment)) {
            //             The partition assignments may have changed while paused by a call to setEndOffsets() so reassign
            //             partitions upon resuming. This is safe even if the end offsets have not been modified.
            //            assignment = assignPartitionsAndSeekToNext(handle);
            //            if (assignment.isEmpty()) {
            //              log.info("All partitions have been fully read");
            //              publishOnStop = true;
            //              stopRequested = true;
            //            }
            //          }
            //          if (stopRequested) {
            //            break;
            //          }

            final String query = (ioConfig.getQuery() != null) ? ioConfig.getQuery()
                    : makeQuery(ioConfig.getColumns(), ioConfig.getJdbcOffsets());
            org.skife.jdbi.v2.Query<Map<String, Object>> dbiQuery = handle.createQuery(query);

            final ResultIterator<InputRow> rowIterator = dbiQuery.map(new ResultSetMapper<InputRow>() {
                List<String> queryColumns = (ioConfig.getColumns() == null) ? Lists.<String>newArrayList()
                        : ioConfig.getColumns();
                List<Boolean> columnIsNumeric = Lists.newArrayList();

                @Override
                public InputRow map(final int index, final ResultSet r, final StatementContext ctx)
                        throws SQLException {
                    try {
                        if (queryColumns.size() == 0) {
                            ResultSetMetaData metadata = r.getMetaData();
                            for (int idx = 1; idx <= metadata.getColumnCount(); idx++) {
                                queryColumns.add(metadata.getColumnName(idx));
                            }
                            Preconditions.checkArgument(queryColumns.size() > 0,
                                    String.format("No column in table [%s]", table));
                            verifyParserSpec(parser.getParseSpec(), queryColumns);
                        }
                        if (columnIsNumeric.size() == 0) {
                            ResultSetMetaData metadata = r.getMetaData();
                            Preconditions.checkArgument(metadata.getColumnCount() >= queryColumns.size(),
                                    String.format(
                                            "number of column names [%d] exceeds the actual number of returning column values [%d]",
                                            queryColumns.size(), metadata.getColumnCount()));
                            columnIsNumeric.add(false); // dummy to make start index to 1
                            for (int idx = 1; idx <= metadata.getColumnCount(); idx++) {
                                boolean isNumeric = false;
                                int type = metadata.getColumnType(idx);
                                switch (type) {
                                case BIGINT:
                                case DECIMAL:
                                case DOUBLE:
                                case FLOAT:
                                case INTEGER:
                                case NUMERIC:
                                case SMALLINT:
                                case TINYINT:
                                    isNumeric = true;
                                    break;
                                }
                                columnIsNumeric.add(isNumeric);
                            }
                        }
                        final Map<String, Object> columnMap = Maps.newHashMap();
                        int columnIdx = 1;
                        for (String column : queryColumns) {
                            Object objToPut = null;
                            if (table != null) {
                                objToPut = r.getObject(column);
                            } else {
                                objToPut = r.getObject(columnIdx);
                            }
                            columnMap.put(column, objToPut == null ? columnIsNumeric.get(columnIdx) : objToPut);

                            columnIdx++;
                        }
                        return parser.parse(columnMap);

                    } catch (IllegalArgumentException e) {
                        throw new SQLException(e);
                    }
                }
            }).iterator();

            org.skife.jdbi.v2.Query<Map<String, Object>> maxItemQuery = handle
                    .createQuery(makeMaxQuery(ioConfig.getJdbcOffsets()));
            long currOffset = maxItemQuery != null ? (long) maxItemQuery.list(1).get(0).get("MAX") : 0;

            while (rowIterator.hasNext()) {
                InputRow row = rowIterator.next();
                try {
                    if (!ioConfig.getMinimumMessageTime().isPresent()
                            || !ioConfig.getMinimumMessageTime().get().isAfter(row.getTimestamp())) {

                        final String sequenceName = sequenceNames.get(nextOffsets.keySet().toArray()[0]); //TODO::: check data
                        final AppenderatorDriverAddResult addResult = driver.add(row, sequenceName,
                                committerSupplier);

                        if (addResult.isOk()) {
                            // If the number of rows in the segment exceeds the threshold after adding a row,
                            // move the segment out from the active segments of AppenderatorDriver to make a new segment.
                            if (addResult.getNumRowsInSegment() > tuningConfig.getMaxRowsPerSegment()) {
                                driver.moveSegmentOut(sequenceName,
                                        ImmutableList.of(addResult.getSegmentIdentifier()));
                            }
                        } else {
                            // Failure to allocate segment puts determinism at risk, bail out to be safe.
                            // May want configurable behavior here at some point.
                            // If we allow continuing, then consider blacklisting the interval for a while to avoid constant checks.
                            throw new ISE("Could not allocate segment for row with timestamp[%s]",
                                    row.getTimestamp());
                        }

                        fireDepartmentMetrics.incrementProcessed();
                    } else {
                        fireDepartmentMetrics.incrementThrownAway();
                    }
                } catch (ParseException e) {
                    if (tuningConfig.isReportParseExceptions()) {
                        throw e;
                    } else {
                        log.debug(e, "Dropping unparseable row from row[%d] .", row);

                        fireDepartmentMetrics.incrementUnparseable();
                    }
                }
            }
            nextOffsets.put((int) ioConfig.getJdbcOffsets().getOffsetMaps().keySet().toArray()[0], currOffset);
            //          if (nextOffsets.get(record.partition()).equals(endOffsets.get(record.partition()))
            //              && assignment.remove(record.partition())) {
            //            log.info("Finished reading table[%s], partition[%,d].", record.topic(), record.partition());
            //            stillReading = ioConfig.isPauseAfterRead() || !assignment.isEmpty();
            //          }
            //        }
        } finally {
            driver.persist(committerSupplier.get()); // persist pending data
        }
        synchronized (statusLock) {
            if (stopRequested && !publishOnStop) {
                throw new InterruptedException("Stopping without publishing");
            }

            status = Status.PUBLISHING;
        }

        final TransactionalSegmentPublisher publisher = (segments, commitMetadata) -> {

            final JDBCOffsets finalOffsets = toolbox.getObjectMapper()
                    .convertValue(((Map) commitMetadata).get(METADATA_NEXT_OFFSETS), JDBCOffsets.class);
            // Sanity check, we should only be publishing things that match our desired end state. //TODO::: Santiny Check!
            //        if (!endOffsets.equals(finalOffsets.getOffsetMaps())) {
            //          throw new ISE("WTF?! Driver attempted to publish invalid metadata[%s].", commitMetadata);
            //        }

            final SegmentTransactionalInsertAction action;

            if (ioConfig.isUseTransaction()) {
                action = new SegmentTransactionalInsertAction(segments,
                        new JDBCDataSourceMetadata(ioConfig.getJdbcOffsets()),
                        new JDBCDataSourceMetadata(finalOffsets) //TODO::: Check Values
                );
            } else {
                action = new SegmentTransactionalInsertAction(segments, null, null);
            }

            log.info("Publishing with isTransaction[%s].", ioConfig.isUseTransaction());

            return toolbox.getTaskActionClient().submit(action).isSuccess();
        };

        // Supervised kafka tasks are killed by JDBCSupervisor if they are stuck during publishing segments or waiting
        // for hand off. See JDBCSupervisorIOConfig.completionTimeout.
        final SegmentsAndMetadata published = driver
                .publish(publisher, committerSupplier.get(), sequenceNames.values()).get();

        final SegmentsAndMetadata handedOff;
        if (tuningConfig.getHandoffConditionTimeout() == 0) {
            handedOff = driver.registerHandoff(published).get();
        } else {
            handedOff = driver.registerHandoff(published).get(tuningConfig.getHandoffConditionTimeout(),
                    TimeUnit.MILLISECONDS);
        }

        if (handedOff == null) {
            throw new ISE("Transaction failure publishing segments, aborting");
        } else {
            log.info("Published segments[%s] with metadata[%s].", Joiner.on(", ")
                    .join(Iterables.transform(handedOff.getSegments(), new Function<DataSegment, String>() {
                        @Override
                        public String apply(DataSegment input) {
                            return input.getIdentifier();
                        }
                    })), handedOff.getCommitMetadata());
        }
    } catch (InterruptedException | RejectedExecutionException e) {
        // handle the InterruptedException that gets wrapped in a RejectedExecutionException
        if (e instanceof RejectedExecutionException
                && (e.getCause() == null || !(e.getCause() instanceof InterruptedException))) {
            throw e;
        }

        // if we were interrupted because we were asked to stop, handle the exception and return success, else rethrow
        if (!stopRequested) {
            Thread.currentThread().interrupt();
            throw e;
        }

        log.info("The task was asked to stop before completing");
    } finally

    {
        if (chatHandlerProvider.isPresent()) {
            chatHandlerProvider.get().unregister(getId());
        }
        handle.close();
    }

    toolbox.getDataSegmentServerAnnouncer().unannounce();

    //TODO::implement
    return success();

}

From source file:com.google.acre.script.AcreFetch.java

@SuppressWarnings("boxing")
public void fetch(boolean system, String response_encoding, boolean log_to_user, boolean no_redirect) {

    if (request_url.length() > 2047) {
        throw new AcreURLFetchException("fetching URL failed - url is too long");
    }/*  w  w  w  .ja v a 2 s.c  o  m*/

    DefaultHttpClient client = new DefaultHttpClient(_connectionManager, null);

    HttpParams params = client.getParams();

    // pass the deadline down to the invoked service.
    // this will be ignored unless we are fetching from another
    // acre server.
    // note that we may send a deadline that is already passed:
    // it's not our job to throw here since we don't know how
    // the target service will interpret the quota header.
    // NOTE: this is done *after* the user sets the headers to overwrite
    // whatever settings they might have tried to change for this value
    // (which could be a security hazard)
    long sub_deadline = (HostEnv.LIMIT_EXECUTION_TIME) ? _deadline - HostEnv.SUBREQUEST_DEADLINE_ADVANCE
            : System.currentTimeMillis() + HostEnv.ACRE_URLFETCH_TIMEOUT;
    int reentries = _reentries + 1;
    request_headers.put(HostEnv.ACRE_QUOTAS_HEADER, "td=" + sub_deadline + ",r=" + reentries);

    // if this is not an internal call, we need to invoke the call thru a proxy
    if (!_internal) {
        // XXX No sense wasting the resources to gzip inside the network.
        // XXX seems that twitter gets upset when we do this
        /*
        if (!request_headers.containsKey("accept-encoding")) {
        request_headers.put("accept-encoding", "gzip");
        }
        */
        String proxy_host = Configuration.Values.HTTP_PROXY_HOST.getValue();
        int proxy_port = -1;
        if (!(proxy_host.length() == 0)) {
            proxy_port = Configuration.Values.HTTP_PROXY_PORT.getInteger();
            HttpHost proxy = new HttpHost(proxy_host, proxy_port, "http");
            params.setParameter(AllClientPNames.DEFAULT_PROXY, proxy);
        }
    }

    params.setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    // in msec

    long timeout = _deadline - System.currentTimeMillis();
    if (timeout < 0)
        timeout = 0;
    params.setParameter(AllClientPNames.CONNECTION_TIMEOUT, (int) timeout);
    params.setParameter(AllClientPNames.SO_TIMEOUT, (int) timeout);

    // we're not streaming the request so this should be a win.
    params.setParameter(AllClientPNames.TCP_NODELAY, true);

    // reuse an existing socket if it is in TIME_WAIT state.
    params.setParameter(AllClientPNames.SO_REUSEADDR, true);

    // set the encoding of our POST payloads to UTF-8
    params.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    BasicCookieStore cstore = new BasicCookieStore();
    for (AcreCookie cookie : request_cookies.values()) {
        cstore.addCookie(cookie.toClientCookie());
    }
    client.setCookieStore(cstore);

    HttpRequestBase method;

    HashMap<String, String> logmsg = new HashMap<String, String>();
    logmsg.put("Method", request_method);
    logmsg.put("URL", request_url);

    params.setParameter(AllClientPNames.HANDLE_REDIRECTS, !no_redirect);
    logmsg.put("Redirect", Boolean.toString(!no_redirect));

    try {
        if (request_method.equals("GET")) {
            method = new HttpGet(request_url);
        } else if (request_method.equals("POST")) {
            method = new HttpPost(request_url);
        } else if (request_method.equals("HEAD")) {
            method = new HttpHead(request_url);
        } else if (request_method.equals("PUT")) {
            method = new HttpPut(request_url);
        } else if (request_method.equals("DELETE")) {
            method = new HttpDelete(request_url);
        } else if (request_method.equals("PROPFIND")) {
            method = new HttpPropFind(request_url);
        } else {
            throw new AcreURLFetchException("Failed: unsupported (so far) method " + request_method);
        }
        method.getParams().setBooleanParameter(AllClientPNames.USE_EXPECT_CONTINUE, false);
    } catch (java.lang.IllegalArgumentException e) {
        throw new AcreURLFetchException("Unable to fetch URL; this is most likely an issue with URL encoding.");
    } catch (java.lang.IllegalStateException e) {
        throw new AcreURLFetchException("Unable to fetch URL; possibly an illegal protocol?");
    }

    StringBuilder request_header_log = new StringBuilder();
    for (Map.Entry<String, String> header : request_headers.entrySet()) {
        String key = header.getKey();
        String value = header.getValue();

        // XXX should suppress cookie headers?
        // content-type and length?

        if ("content-type".equalsIgnoreCase(key)) {
            Matcher m = contentTypeCharsetPattern.matcher(value);
            if (m.find()) {
                content_type = m.group(1);
                content_type_charset = m.group(2);
            } else {
                content_type_charset = "utf-8";
            }
            method.addHeader(key, value);
        } else if ("content-length".equalsIgnoreCase(key)) {
            // ignore user-supplied content-length, which is
            // probably wrong due to chars vs bytes and is
            // redundant anyway
            ArrayList<String> msg = new ArrayList<String>();
            msg.add("User-supplied content-length header is ignored");
            _acre_response.log("warn", msg);
        } else if ("user-agent".equalsIgnoreCase(key)) {
            params.setParameter(AllClientPNames.USER_AGENT, value);
        } else {
            method.addHeader(key, value);
        }
        if (!("x-acre-auth".equalsIgnoreCase(key))) {
            request_header_log.append(key + ": " + value + "\r\n");
        }
    }
    logmsg.put("Headers", request_header_log.toString());

    // XXX need more detailed error checking
    if (method instanceof HttpEntityEnclosingRequestBase && request_body != null) {

        HttpEntityEnclosingRequestBase em = (HttpEntityEnclosingRequestBase) method;
        try {
            if (request_body instanceof String) {
                StringEntity ent = new StringEntity((String) request_body, content_type_charset);
                em.setEntity(ent);
            } else if (request_body instanceof JSBinary) {
                ByteArrayEntity ent = new ByteArrayEntity(((JSBinary) request_body).get_data());
                em.setEntity(ent);
            }
        } catch (UnsupportedEncodingException e) {
            throw new AcreURLFetchException(
                    "Failed to fetch URL. " + " - Unsupported charset: " + content_type_charset);
        }
    }

    if (!system && log_to_user) {
        ArrayList<Object> msg = new ArrayList<Object>();
        msg.add("urlfetch request");
        msg.add(logmsg);
        _acre_response.log("debug", msg);
    }
    _logger.info("urlfetch.request", logmsg);

    long startTime = System.currentTimeMillis();

    try {
        // this sends the http request and waits
        HttpResponse hres = client.execute(method);
        status = hres.getStatusLine().getStatusCode();
        HashMap<String, String> res_logmsg = new HashMap<String, String>();
        res_logmsg.put("URL", request_url);
        res_logmsg.put("Status", ((Integer) status).toString());

        Header content_type_header = null;

        // translate response headers
        StringBuilder response_header_log = new StringBuilder();
        Header[] rawheaders = hres.getAllHeaders();
        for (Header rawheader : rawheaders) {
            String headername = rawheader.getName().toLowerCase();
            if (headername.equalsIgnoreCase("content-type")) {
                content_type_header = rawheader;
                // XXX should strip everything after ;
                content_type = rawheader.getValue();

                // XXX don't set content_type_parameters, deprecated?
            } else if (headername.equalsIgnoreCase("x-metaweb-cost")) {
                _costCollector.merge(rawheader.getValue());
            } else if (headername.equalsIgnoreCase("x-metaweb-tid")) {
                res_logmsg.put("ITID", rawheader.getValue());
            }

            headers.put(headername, rawheader.getValue());
            response_header_log.append(headername + ": " + rawheader.getValue() + "\r\n");
        }

        res_logmsg.put("Headers", response_header_log.toString());

        if (!system && log_to_user) {
            ArrayList<Object> msg = new ArrayList<Object>();
            msg.add("urlfetch response");
            msg.add(res_logmsg);
            _acre_response.log("debug", msg);
        }

        _logger.info("urlfetch.response", res_logmsg);

        // read cookies
        for (Cookie c : cstore.getCookies()) {
            cookies.put(c.getName(), new AcreCookie(c));
        }

        // get body encoding

        String charset = null;
        if (content_type_header != null) {
            HeaderElement values[] = content_type_header.getElements();
            if (values.length == 1) {
                NameValuePair param = values[0].getParameterByName("charset");
                if (param != null) {
                    charset = param.getValue();
                }
            }
        }

        if (charset == null)
            charset = response_encoding;

        // read body
        HttpEntity ent = hres.getEntity();
        if (ent != null) {
            InputStream res_stream = ent.getContent();
            Header cenc = ent.getContentEncoding();
            if (cenc != null && res_stream != null) {
                HeaderElement[] codecs = cenc.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        res_stream = new GZIPInputStream(res_stream);
                    }
                }
            }

            long firstByteTime = 0;
            long endTime = 0;
            if (content_type != null
                    && (content_type.startsWith("image/") || content_type.startsWith("application/octet-stream")
                            || content_type.startsWith("multipart/form-data"))) {
                // HttpClient's InputStream doesn't support mark/reset, so
                // wrap it with one that does.
                BufferedInputStream bufis = new BufferedInputStream(res_stream);
                bufis.mark(2);
                bufis.read();
                firstByteTime = System.currentTimeMillis();
                bufis.reset();
                byte[] data = IOUtils.toByteArray(bufis);

                endTime = System.currentTimeMillis();
                body = new JSBinary();
                ((JSBinary) body).set_data(data);

                try {
                    if (res_stream != null) {
                        res_stream.close();
                    }
                } catch (IOException e) {
                    // ignore
                }
            } else if (res_stream == null || charset == null) {
                firstByteTime = endTime = System.currentTimeMillis();
                body = "";
            } else {
                StringWriter writer = new StringWriter();
                Reader reader = new InputStreamReader(res_stream, charset);
                int i = reader.read();
                firstByteTime = System.currentTimeMillis();
                writer.write(i);
                IOUtils.copy(reader, writer);
                endTime = System.currentTimeMillis();
                body = writer.toString();

                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    // ignore
                }
            }

            long waitingTime = firstByteTime - startTime;
            long readingTime = endTime - firstByteTime;

            _logger.debug("urlfetch.timings", "waiting time: " + waitingTime + "ms");
            _logger.debug("urlfetch.timings", "reading time: " + readingTime + "ms");

            Statistics.instance().collectUrlfetchTime(startTime, firstByteTime, endTime);

            _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waitingTime)
                    .collect((system) ? "asub" : "auub", waitingTime);
        }
    } catch (IllegalArgumentException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new AcreURLFetchException("failed to fetch URL. " + " - Request Error: " + cause.getMessage());
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage());
    } catch (RuntimeException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage());
    } finally {
        method.abort();
    }
}