Example usage for java.util List clear

List of usage examples for java.util List clear

Introduction

In this page you can find the example usage for java.util List clear.

Prototype

void clear();

Source Link

Document

Removes all of the elements from this list (optional operation).

Usage

From source file:com.amazonaws.mturk.cmd.ApproveWork.java

private void submitAssignmentsFromHitIfNecessary(List<String> assignmentList, int threshold) {
    if (assignmentList.size() < threshold) {
        return;//from  ww w  .  ja v a  2s.  c o m
    }

    String[] assignmentsToApprove = new String[assignmentList.size()];
    assignmentList.toArray(assignmentsToApprove);
    service.approveAssignments(assignmentsToApprove, null, null, this);

    assignmentList.clear();
}

From source file:com.streamsets.pipeline.stage.origin.httpserver.TestHttpServerPushSource.java

@Test
public void testWithAppIdViaQueryParam() throws Exception {
    RawHttpConfigs httpConfigs = new RawHttpConfigs();
    httpConfigs.appId = () -> "id";
    httpConfigs.port = NetworkUtils.getRandomPort();
    httpConfigs.maxConcurrentRequests = 1;
    httpConfigs.tlsConfigBean.tlsEnabled = false;
    httpConfigs.appIdViaQueryParamAllowed = true;
    HttpServerPushSource source = new HttpServerPushSource(httpConfigs, 1, DataFormat.TEXT,
            new DataParserFormatConfig());
    final PushSourceRunner runner = new PushSourceRunner.Builder(HttpServerDPushSource.class, source)
            .addOutputLane("a").build();
    runner.runInit();/*from   ww w  .  j a  va2s  .  c  o m*/
    try {
        final List<Record> records = new ArrayList<>();
        runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
            @Override
            public void processBatch(StageRunner.Output output) {
                records.clear();
                records.addAll(output.getRecords().get("a"));
            }
        });

        // wait for the HTTP server up and running
        HttpReceiverServer httpServer = (HttpReceiverServer) Whitebox.getInternalState(source, "server");
        await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer));

        String url = "http://localhost:" + httpConfigs.getPort() + "?"
                + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=id";
        Response response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, response.getStatus());
        Assert.assertEquals(1, records.size());
        Assert.assertEquals("Hello", records.get(0).get("/text").getValue());

        // Passing wrong App ID in query param should return 403 response
        url = "http://localhost:" + httpConfigs.getPort() + "?" + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM
                + "=wrongid";
        response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello"));
        Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getStatus());

        runner.setStop();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        runner.runDestroy();
    }
}

From source file:com.streamsets.pipeline.stage.origin.httpserver.TestHttpServerPushSource.java

@Test
public void testAvroData() throws Exception {
    RawHttpConfigs httpConfigs = new RawHttpConfigs();
    httpConfigs.appId = () -> "id";
    httpConfigs.port = NetworkUtils.getRandomPort();
    httpConfigs.maxConcurrentRequests = 1;
    httpConfigs.tlsConfigBean.tlsEnabled = false;
    httpConfigs.appIdViaQueryParamAllowed = true;
    DataParserFormatConfig dataFormatConfig = new DataParserFormatConfig();
    dataFormatConfig.avroSchemaSource = OriginAvroSchemaSource.SOURCE;
    HttpServerPushSource source = new HttpServerPushSource(httpConfigs, 1, DataFormat.AVRO, dataFormatConfig);
    final PushSourceRunner runner = new PushSourceRunner.Builder(HttpServerDPushSource.class, source)
            .addOutputLane("a").build();
    runner.runInit();/* w  w w . j  ava  2  s .co  m*/
    try {
        final List<Record> records = new ArrayList<>();
        runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
            @Override
            public void processBatch(StageRunner.Output output) {
                records.clear();
                records.addAll(output.getRecords().get("a"));
            }
        });

        // wait for the HTTP server up and running
        HttpReceiverServer httpServer = (HttpReceiverServer) Whitebox.getInternalState(source, "server");
        await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer));

        String url = "http://localhost:" + httpConfigs.getPort() + "?"
                + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=id";
        File avroDataFile = SdcAvroTestUtil.createAvroDataFile();
        InputStream in = new FileInputStream(avroDataFile);
        byte[] avroData = IOUtils.toByteArray(in);
        Response response = ClientBuilder.newClient().target(url).request()
                .post(Entity.entity(avroData, MediaType.APPLICATION_OCTET_STREAM_TYPE));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, response.getStatus());
        Assert.assertEquals(3, records.size());
        Assert.assertEquals("a", records.get(0).get("/name").getValue());
        Assert.assertEquals("b", records.get(1).get("/name").getValue());
        Assert.assertEquals("c", records.get(2).get("/name").getValue());
        runner.setStop();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        runner.runDestroy();
    }
}

From source file:com.baidu.rigel.biplatform.ma.report.utils.QueryUtils.java

/**
 * ??//  w w w  .  j  av  a2s.c o m
 * 
 * @param reportModel
 * @param area
 * @param queryAction
 * @return
 * @throws QueryModelBuildException
 */
private static Map<String, MetaCondition> buildQueryConditions(ReportDesignModel reportModel, ExtendArea area,
        QueryAction queryAction) throws QueryModelBuildException {
    Map<String, MetaCondition> rs = new HashMap<String, MetaCondition>();
    Map<Item, Object> items = new HashMap<Item, Object>();
    items.putAll(queryAction.getColumns());
    items.putAll(queryAction.getRows());
    items.putAll(queryAction.getSlices());
    int firstIndex = 0;
    for (Map.Entry<Item, Object> entry : items.entrySet()) {
        Item item = entry.getKey();
        OlapElement olapElement = ReportDesignModelUtils.getDimOrIndDefineWithId(reportModel.getSchema(),
                area.getCubeId(), item.getOlapElementId());
        if (olapElement == null) {
            Cube cube = com.baidu.rigel.biplatform.ma.report.utils.QueryUtils.getCubeWithExtendArea(reportModel,
                    area);
            for (Dimension dim : cube.getDimensions().values()) {
                if (dim.getId().equals(item.getOlapElementId())) {
                    olapElement = dim;
                    break;
                }
            }
        }
        if (olapElement == null) {
            continue;
        }
        if (olapElement instanceof Dimension) {
            DimensionCondition condition = new DimensionCondition(olapElement.getName());
            Object valueObj = entry.getValue();
            if (valueObj != null) {
                List<String> values = Lists.newArrayList();
                if (valueObj instanceof String[]) {
                    values = Lists.newArrayList();
                    String[] tmp = resetValues(olapElement.getName(), (String[]) valueObj);
                    CollectionUtils.addAll(values, (String[]) tmp);
                } else {
                    String tmp = resetValues(olapElement.getName(), valueObj.toString())[0];
                    values.add(tmp);
                }

                List<QueryData> datas = Lists.newArrayList();
                // TODO ?UniqueName?
                String rootUniqueName = "[" + olapElement.getName() + "].[All_" + olapElement.getName();
                // TODO QeuryData value?
                for (String value : values) {
                    if (!queryAction.isChartQuery() && value.indexOf(rootUniqueName) != -1) {
                        datas.clear();
                        break;
                    }
                    QueryData data = new QueryData(value);
                    Object drillValue = queryAction.getDrillDimValues().get(item);
                    String tmpValue = null;
                    if (valueObj instanceof String[]) {
                        tmpValue = ((String[]) valueObj)[0];
                    } else {
                        tmpValue = valueObj.toString();
                    }
                    if (drillValue != null && tmpValue.equals(drillValue)) {
                        data.setExpand(true);
                    } else if ((item.getPositionType() == PositionType.X
                            || item.getPositionType() == PositionType.S) && queryAction.isChartQuery()) {
                        data.setExpand(true);
                        data.setShow(false);
                    }
                    // ?
                    if (item.getParams().get(Constants.LEVEL) != null) {
                        if (item.getParams().get(Constants.LEVEL).equals(1)) {
                            data.setExpand(!queryAction.isChartQuery());
                            data.setShow(true);
                        } else if (item.getParams().get(Constants.LEVEL).equals(2)) {
                            data.setExpand(true);
                            data.setShow(false);
                        }
                        if (MetaNameUtil.isAllMemberUniqueName(data.getUniqueName())
                                && queryAction.isChartQuery()) {
                            data.setExpand(true);
                            data.setShow(false);
                        }
                    }
                    datas.add(data);
                }
                if (values.isEmpty() && queryAction.isChartQuery()) {
                    QueryData data = new QueryData(rootUniqueName + "s]");
                    data.setExpand(true);
                    data.setShow(false);
                    datas.add(data);
                }
                condition.setQueryDataNodes(datas);
            } else {
                List<QueryData> datas = new ArrayList<QueryData>();
                Dimension dim = (Dimension) olapElement;
                if ((item.getPositionType() == PositionType.X || item.getPositionType() == PositionType.S)
                        && queryAction.isChartQuery()) {
                    QueryData data = new QueryData(dim.getAllMember().getUniqueName());
                    data.setExpand(true);
                    data.setShow(false);
                    datas.add(data);
                } else if (dim.getType() == DimensionType.CALLBACK) {
                    QueryData data = new QueryData(dim.getAllMember().getUniqueName());
                    data.setExpand(firstIndex == 0);
                    data.setShow(firstIndex != 0);
                    datas.add(data);
                }
                condition.setQueryDataNodes(datas);
            }
            // ??????
            if (item.getPositionType() == PositionType.X && olapElement instanceof TimeDimension
                    && firstIndex == 0 && !queryAction.isChartQuery()) {
                condition.setMemberSortType(SortType.DESC);
                ++firstIndex;
            }
            rs.put(condition.getMetaName(), condition);
        }
    }
    return rs;
}

From source file:jms.PublisherThread.java

private void resend(List<Message> currentBatch) {
    try {//from www  .j  av a 2 s. co m
        jmsPublisher.rollback();
        for (Message message : currentBatch) {
            jmsPublisher.send(message);
        }
        jmsPublisher.commit();
        sentCount.addAndGet(currentBatch.size());
        publishRate.mark(currentBatch.size());
        currentBatch.clear();
    } catch (JMSException e) {
        try {
            jmsPublisher.rollback();
            resend(currentBatch);
        } catch (JMSException e1) {
            log.error("Roll back failed on resend", e);
            resend(currentBatch);
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.httpserver.TestHttpServerPushSource.java

@Test
public void testSource() throws Exception {
    RawHttpConfigs httpConfigs = new RawHttpConfigs();
    httpConfigs.appId = () -> "id";
    httpConfigs.port = NetworkUtils.getRandomPort();
    httpConfigs.maxConcurrentRequests = 1;
    httpConfigs.tlsConfigBean.tlsEnabled = false;
    HttpServerPushSource source = new HttpServerPushSource(httpConfigs, 1, DataFormat.TEXT,
            new DataParserFormatConfig());
    final PushSourceRunner runner = new PushSourceRunner.Builder(HttpServerDPushSource.class, source)
            .addOutputLane("a").build();
    runner.runInit();//w w w  . ja  va  2 s  .c om
    try {
        final List<Record> records = new ArrayList<>();
        runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
            @Override
            public void processBatch(StageRunner.Output output) {
                records.clear();
                records.addAll(output.getRecords().get("a"));
            }
        });

        // wait for the HTTP server up and running
        HttpReceiverServer httpServer = (HttpReceiverServer) Whitebox.getInternalState(source, "server");
        await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer));

        HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:" + httpConfigs.getPort())
                .openConnection();
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty(Constants.X_SDC_APPLICATION_ID_HEADER, "id");
        connection.setRequestProperty("customHeader", "customHeaderValue");
        connection.getOutputStream().write("Hello".getBytes());
        Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
        Assert.assertEquals(1, records.size());
        Assert.assertEquals("Hello", records.get(0).get("/text").getValue());
        Assert.assertEquals("id",
                records.get(0).getHeader().getAttribute(Constants.X_SDC_APPLICATION_ID_HEADER));
        Assert.assertEquals("customHeaderValue", records.get(0).getHeader().getAttribute("customHeader"));

        // passing App Id via query param should fail when appIdViaQueryParamAllowed is false
        String url = "http://localhost:" + httpConfigs.getPort() + "?"
                + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=id";
        Response response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello"));
        Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getStatus());

        runner.setStop();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        runner.runDestroy();
    }
}

From source file:umontreal.iro.lecuyer.charts.BoxSeriesCollection.java

/**
 * Creates a new <TT>BoxSeriesCollection</TT> instance with default
 *    parameters and given data series. The input parameter represents series
 *    of point sets.//www . j  a va  2 s  .c o  m
 * 
 * @param data series of point sets.
 * 
 * 
 */
public BoxSeriesCollection(double[]... data) {
    renderer = new BoxAndWhiskerRenderer();
    seriesCollection = new DefaultBoxAndWhiskerCategoryDataset();

    DefaultBoxAndWhiskerCategoryDataset tempSeriesCollection = (DefaultBoxAndWhiskerCategoryDataset) seriesCollection;

    for (int i = 0; i < data.length; i++) {
        if (data[i].length == 0)
            throw new IllegalArgumentException("Unable to render the plot. data[" + i + "] contains no row");
        final List<Double> list = new ArrayList<Double>();
        for (int j = 0; j < data[i].length - 1; j++)
            list.add(data[i][j]);
        tempSeriesCollection.add(list, 0, "Serie " + i);
        list.clear();
    }
    ((BoxAndWhiskerRenderer) renderer).setMaximumBarWidth(BARWIDTH);
}

From source file:nz.co.senanque.base.ObjectTest.java

@SuppressWarnings("unused")
@Test// w  w w  .j  a  va 2  s .c  o m
public void test1() throws Exception {
    ValidationSession validationSession = m_validationEngine.createSession();

    // create a customer
    Customer customer = m_customerDAO.createCustomer();
    validationSession.bind(customer);
    Invoice invoice = new Invoice();
    invoice.setDescription("test invoice");
    customer.getInvoices().add(invoice);
    boolean exceptionFound = false;
    try {
        customer.setName("ttt");
    } catch (ValidationException e) {
        exceptionFound = true;
    }
    assertTrue(exceptionFound);

    final ObjectMetadata customerMetadata = validationSession.getMetadata(customer);
    final FieldMetadata customerTypeMetadata = customerMetadata.getFieldMetadata(Customer.CUSTOMERTYPE);

    assertFalse(customerTypeMetadata.isActive());
    assertFalse(customerTypeMetadata.isReadOnly());
    assertFalse(customerTypeMetadata.isRequired());

    customer.setName("aaaab");
    assertTrue(customerTypeMetadata.isActive());
    assertTrue(customerTypeMetadata.isReadOnly());
    assertTrue(customerTypeMetadata.isRequired());
    exceptionFound = false;
    try {
        customer.setCustomerType("B");
    } catch (Exception e) {
        exceptionFound = true;
    }
    assertTrue(exceptionFound);
    exceptionFound = false;
    try {
        customer.setCustomerType("XXX");
    } catch (Exception e) {
        exceptionFound = true;
    }
    assertTrue(exceptionFound);
    customer.setBusiness(IndustryType.AG);
    customer.setAmount(new Double(500.99));
    final long id = m_customerDAO.save(customer);
    log.info(id);

    // fetch customer back
    customer = m_customerDAO.getCustomer(id);
    final int invoiceCount = customer.getInvoices().size();
    validationSession.bind(customer);
    invoice = new Invoice();
    invoice.setDescription("test invoice2");
    customer.getInvoices().add(invoice);
    m_customerDAO.save(customer);

    // fetch customer again
    customer = m_customerDAO.getCustomer(id);
    customer.toString();
    validationSession.bind(customer);
    final Invoice inv = customer.getInvoices().get(0);
    customer.getInvoices().remove(inv);

    //ObjectMetadata metadata = validationSession.getMetadata(customer);
    ObjectMetadata metadata = customer.getMetadata();
    org.junit.Assert.assertEquals("this is a description",
            metadata.getFieldMetadata(Customer.NAME).getDescription());
    List<ChoiceBase> choices = metadata.getFieldMetadata(Customer.BUSINESS).getChoiceList();
    assertEquals(1, choices.size());
    List<ChoiceBase> choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList();
    assertEquals(2, choices2.size());
    choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList();
    assertEquals(2, choices2.size());

    customer.setName("aab");
    choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList();
    assertEquals(6, choices2.size());

    // Convert customer to XML
    QName qname = new QName("http://www.example.org/sandbox", "Session");
    JAXBElement<Session> sessionJAXB = new JAXBElement<Session>(qname, Session.class, new Session());
    sessionJAXB.getValue().getCustomers().add(customer); //??This fails to actually add
    StringWriter marshallWriter = new StringWriter();
    Result marshallResult = new StreamResult(marshallWriter);
    m_marshaller.marshal(sessionJAXB, marshallResult);
    marshallWriter.flush();
    String result = marshallWriter.getBuffer().toString().trim();
    String xml = result.replaceAll("\\Qhttp://www.example.org/sandbox\\E", "http://www.example.org/sandbox");
    log.info(xml);

    // Convert customer back to objects
    SAXBuilder builder = new SAXBuilder();
    org.jdom.Document resultDOM = builder.build(new StringReader(xml));
    @SuppressWarnings("unchecked")
    JAXBElement<Session> request = (JAXBElement<Session>) m_unmarshaller.unmarshal(new JDOMSource(resultDOM));
    validationSession = m_validationEngine.createSession();
    validationSession.bind(request.getValue());
    assertEquals(3, validationSession.getProxyCount());
    List<Customer> customers = request.getValue().getCustomers();
    assertEquals(1, customers.size());
    customers.clear();
    assertEquals(1, validationSession.getProxyCount());
    request.toString();
    validationSession.close();
}

From source file:com.healthmarketscience.jackcess.ImportUtil.java

/**
 * Copy a delimited text file into a new (or optionally exixsting) table in
 * this database.// w  ww .  ja  va  2s.c  om
 * 
 * @param name Name of the new table to create
 * @param in Source reader to import
 * @param delim Regular expression representing the delimiter string.
 * @param quote the quote character
 * @param filter valid import filter
 * @param useExistingTable if {@code true} use current table if it already
 *                         exists, otherwise, create new table with unique
 *                         name
 * @param header if {@code false} the first line is not a header row, only
 *               valid if useExistingTable is {@code true}
 *
 * @return the name of the imported table
 * 
 * @see Builder
 */
public static String importReader(BufferedReader in, Database db, String name, String delim, char quote,
        ImportFilter filter, boolean useExistingTable, boolean header) throws IOException {
    String line = in.readLine();
    if (line == null || line.trim().length() == 0) {
        return null;
    }

    Pattern delimPat = Pattern.compile(delim);

    try {
        name = Database.escapeIdentifier(name);
        Table table = null;
        if (!useExistingTable || ((table = db.getTable(name)) == null)) {

            List<Column> columns = new LinkedList<Column>();
            Object[] columnNames = splitLine(line, delimPat, quote, in, 0);

            for (int i = 0; i < columnNames.length; i++) {
                columns.add(new ColumnBuilder((String) columnNames[i], DataType.TEXT).escapeName()
                        .setLength((short) DataType.TEXT.getMaxSize()).toColumn());
            }

            table = createUniqueTable(db, name, columns, null, filter);

            // the first row was a header row
            header = true;
        }

        List<Object[]> rows = new ArrayList<Object[]>(COPY_TABLE_BATCH_SIZE);
        int numColumns = table.getColumnCount();

        if (!header) {
            // first line is _not_ a header line
            Object[] data = splitLine(line, delimPat, quote, in, numColumns);
            data = filter.filterRow(data);
            if (data != null) {
                rows.add(data);
            }
        }

        while ((line = in.readLine()) != null) {
            Object[] data = splitLine(line, delimPat, quote, in, numColumns);
            data = filter.filterRow(data);
            if (data == null) {
                continue;
            }
            rows.add(data);
            if (rows.size() == COPY_TABLE_BATCH_SIZE) {
                table.addRows(rows);
                rows.clear();
            }
        }
        if (rows.size() > 0) {
            table.addRows(rows);
        }

        return table.getName();

    } catch (SQLException e) {
        throw (IOException) new IOException(e.getMessage()).initCause(e);
    }
}

From source file:de.blizzy.documentr.markdown.MarkdownProcessor.java

private void fixParaNodes(Node node) {
    if ((node instanceof MacroNode) || (node instanceof PageHeaderNode)) {
        List<Node> children = ((SuperNode) node).getChildren();
        if ((children.size() == 1) && (children.get(0) instanceof ParaNode)) {
            List<Node> newChildren = ((ParaNode) children.get(0)).getChildren();
            children.clear();
            children.addAll(newChildren);
        }/*from ww  w  . j ava2  s  . c  om*/
    }

    if (node instanceof SuperNode) {
        for (Node child : ((SuperNode) node).getChildren()) {
            fixParaNodes(child);
        }
    }
}