Java Code Examples for java.util.List.clear()

The following are Jave code examples for showing how to use clear() of the java.util.List class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hbase-client   File: Batch.java   View Source Code Vote up 6 votes
/**
 * Method perform a HBase batch operation.
 */
public void call() throws Exception {
    List<Row> rowList = new ArrayList<>(batchSize);
    final Object[] results = new Object[batchSize];
    for ( T object : objectCollection ) {
        final Row row = objectMapper.apply(object);
        rowList.add(row);
        //reach batch limit size, flush index data to HBase
        if ( rowList.size() >= batchSize ) {
            table.batch(rowList, results);
            throwIfBatchFailed(results);
            rowList.clear();
        }
    }
    //save remaining index data
    if ( !rowList.isEmpty() ) {
        final Object[] errors = new Object[rowList.size()];
        table.batch(rowList, errors);
        throwIfBatchFailed(errors);
    }
}
 
Example 2
Project: rlc-analyser   File: RLCDataExporter.java   View Source Code Vote up 6 votes
/**
 * Used to write definitions counts per route.
 *
 * @param writer
 * @throws IOException
 */
private void totalDefinitionsCountsPerRoute(final FileWriter writer) throws IOException {
	CSVUtils.writeLine(writer, Arrays.asList("")); // empty line
	writeHeader(writer, "Definitions per route");
	final int[] overallCounts = this.currentStore.getDefinitionCountsPerRoute();
	final List<String> stringWrite = new ArrayList<String>();
	for (int i = 0; i < overallCounts.length; i++) {
		stringWrite.clear();
		// final index needs to have different name: e.g. 10 or more
		if (i == overallCounts.length - 1) {
			stringWrite.add("Definitions per Route: " + i + " or more");
		} else {
			stringWrite.add("Definitions per Route: " + i);
		}

		stringWrite.add(overallCounts[i] + "");
		for (final RLCDataStore store : this.dataStoreMap.values()) {
			stringWrite.add(String.valueOf(store.getDefinitionCountsPerRoute()[i]));
		}
		CSVUtils.writeLine(writer, stringWrite);
	}
}
 
Example 3
Project: MOAAP   File: Converters.java   View Source Code Vote up 6 votes
public static void Mat_to_vector_KeyPoint(Mat m, List<KeyPoint> kps) {
    if (kps == null)
        throw new java.lang.IllegalArgumentException("Output List can't be null");
    int count = m.rows();
    if (CvType.CV_64FC(7) != m.type() || m.cols() != 1)
        throw new java.lang.IllegalArgumentException(
                "CvType.CV_64FC(7) != m.type() ||  m.cols()!=1\n" + m);

    kps.clear();
    double[] buff = new double[7 * count];
    m.get(0, 0, buff);
    for (int i = 0; i < count; i++) {
        kps.add(new KeyPoint((float) buff[7 * i], (float) buff[7 * i + 1], (float) buff[7 * i + 2], (float) buff[7 * i + 3],
                (float) buff[7 * i + 4], (int) buff[7 * i + 5], (int) buff[7 * i + 6]));
    }
}
 
Example 4
Project: react-native-scan-doc   File: Converters.java   View Source Code Vote up 6 votes
public static void Mat_to_vector_KeyPoint(Mat m, List<KeyPoint> kps) {
    if (kps == null)
        throw new java.lang.IllegalArgumentException("Output List can't be null");
    int count = m.rows();
    if (CvType.CV_64FC(7) != m.type() || m.cols() != 1)
        throw new java.lang.IllegalArgumentException(
                "CvType.CV_64FC(7) != m.type() ||  m.cols()!=1\n" + m);

    kps.clear();
    double[] buff = new double[7 * count];
    m.get(0, 0, buff);
    for (int i = 0; i < count; i++) {
        kps.add(new KeyPoint((float) buff[7 * i], (float) buff[7 * i + 1], (float) buff[7 * i + 2], (float) buff[7 * i + 3],
                (float) buff[7 * i + 4], (int) buff[7 * i + 5], (int) buff[7 * i + 6]));
    }
}
 
Example 5
Project: MOAAP   File: Converters.java   View Source Code Vote up 6 votes
public static void Mat_to_vector_vector_KeyPoint(Mat m, List<MatOfKeyPoint> kps) {
    if (kps == null)
        throw new java.lang.IllegalArgumentException("Output List can't be null");

    if (m == null)
        throw new java.lang.IllegalArgumentException("Input Mat can't be null");

    List<Mat> mats = new ArrayList<Mat>(m.rows());
    Mat_to_vector_Mat(m, mats);
    for (Mat mi : mats) {
        MatOfKeyPoint vkp = new MatOfKeyPoint(mi);
        kps.add(vkp);
        mi.release();
    }
    mats.clear();
}
 
Example 6
Project: android-age-estimator   File: Converters.java   View Source Code Vote up 6 votes
public static void Mat_to_vector_vector_Point3f(Mat m, List<MatOfPoint3f> pts) {
    if (pts == null)
        throw new java.lang.IllegalArgumentException("Output List can't be null");

    if (m == null)
        throw new java.lang.IllegalArgumentException("Input Mat can't be null");

    List<Mat> mats = new ArrayList<Mat>(m.rows());
    Mat_to_vector_Mat(m, mats);
    for (Mat mi : mats) {
        MatOfPoint3f pt = new MatOfPoint3f(mi);
        pts.add(pt);
        mi.release();
    }
    mats.clear();
}
 
Example 7
Project: OpenCV   File: Converters.java   View Source Code Vote up 6 votes
public static void Mat_to_vector_vector_DMatch(Mat m, List<MatOfDMatch> lvdm) {
    if (lvdm == null)
        throw new java.lang.IllegalArgumentException("Output List can't be null");

    if (m == null)
        throw new java.lang.IllegalArgumentException("Input Mat can't be null");

    List<Mat> mats = new ArrayList<Mat>(m.rows());
    Mat_to_vector_Mat(m, mats);
    lvdm.clear();
    for (Mat mi : mats) {
        MatOfDMatch vdm = new MatOfDMatch(mi);
        lvdm.add(vdm);
        mi.release();
    }
    mats.clear();
}
 
Example 8
Project: openjdk-jdk10   File: RepackTest.java   View Source Code Vote up 6 votes
static void testRepack() throws IOException {

        // make a copy of the test specimen to local directory
        File testFile = new File("src_tools.jar");
        Utils.copyFile(Utils.getGoldenJar(), testFile);
        List<String> cmdsList = new ArrayList<>();

        // case 1:
        cmdsList.add(Utils.getPack200Cmd());
        cmdsList.add("--repack");
        cmdsList.add(testFile.getName());
        Utils.runExec(cmdsList);

        // case 2:
        File dstFile = new File("dst_tools.jar");
        cmdsList.clear();
        cmdsList.add(Utils.getPack200Cmd());
        cmdsList.add("--repack");
        cmdsList.add(dstFile.getName());
        cmdsList.add(testFile.getName());
        Utils.runExec(cmdsList);

        // tidy up
        testFile.delete();
        dstFile.delete();
    }
 
Example 9
Project: cyberduck   File: TransferTableDataSource.java   View Source Code Vote up 5 votes
/**
 * Invoked by tableView when the mouse button is released over a table view that previously decided to allow a drop.
 *
 * @param draggingInfo contains details on this dragging operation.
 * @param row          The proposed location is row and action is operation.
 */
@Override
public boolean tableView_acceptDrop_row_dropOperation(final NSTableView view, final NSDraggingInfo draggingInfo,
                                                      final NSInteger row, final NSUInteger operation) {
    if(draggingInfo.draggingPasteboard().availableTypeFromArray(NSArray.arrayWithObject(NSPasteboard.StringPboardType)) != null) {
        String droppedText = draggingInfo.draggingPasteboard().stringForType(NSPasteboard.StringPboardType);// get the data from paste board
        if(StringUtils.isNotBlank(droppedText)) {
            log.info("NSPasteboard.StringPboardType:" + droppedText);
            final DownloadController c = new DownloadController(droppedText);
            c.beginSheet(TransferControllerFactory.get());
            return true;
        }
        return false;
    }
    final List<PathPasteboard> pasteboards = PathPasteboardFactory.allPasteboards();
    if(pasteboards.isEmpty()) {
        return false;
    }
    for(PathPasteboard pasteboard : pasteboards) {
        if(pasteboard.isEmpty()) {
            continue;
        }
        final Host host = pasteboard.getBookmark();
        final List<TransferItem> downloads = new ArrayList<TransferItem>();
        for(Path download : pasteboard) {
            downloads.add(new TransferItem(
                    download, LocalFactory.get(new DownloadDirectoryFinder().find(host), download.getName())));
        }
        collection.add(row.intValue(), new DownloadTransfer(host, downloads));
        view.reloadData();
        view.selectRowIndexes(NSIndexSet.indexSetWithIndex(row), false);
        view.scrollRowToVisible(row);
    }
    pasteboards.clear();
    return true;
}
 
Example 10
Project: FaceDetectDemo   File: Converters.java   View Source Code Vote up 5 votes
public static void Mat_to_vector_Rect2d(Mat m, List<Rect2d> rs) {
    if (rs == null)
        throw new java.lang.IllegalArgumentException("rs == null");
    int count = m.rows();
    if (CvType.CV_64FC4 != m.type() || m.cols() != 1)
        throw new java.lang.IllegalArgumentException(
                                                     "CvType.CV_64FC4 != m.type() ||  m.rows()!=1\n" + m);

    rs.clear();
    double[] buff = new double[4 * count];
    m.get(0, 0, buff);
    for (int i = 0; i < count; i++) {
        rs.add(new Rect2d(buff[4 * i], buff[4 * i + 1], buff[4 * i + 2], buff[4 * i + 3]));
    }
}
 
Example 11
Project: react-native-scan-doc   File: Converters.java   View Source Code Vote up 5 votes
public static void Mat_to_vector_char(Mat m, List<Byte> bs) {
    if (bs == null)
        throw new java.lang.IllegalArgumentException("Output List can't be null");
    int count = m.rows();
    if (CvType.CV_8SC1 != m.type() || m.cols() != 1)
        throw new java.lang.IllegalArgumentException(
                "CvType.CV_8SC1 != m.type() ||  m.cols()!=1\n" + m);

    bs.clear();
    byte[] buff = new byte[count];
    m.get(0, 0, buff);
    for (int i = 0; i < count; i++) {
        bs.add(buff[i]);
    }
}
 
Example 12
Project: matchmaker   File: MatcherTest.java   View Source Code Vote up 5 votes
private void assertMatchAttempts(
        Matcher<?> matcher,
        Object matchedObject,
        List<Class<?>> matchAttempts,
        Class<?>... expectedMatchAttempts
) {
    matcher.match(matchedObject);
    assertEquals(asList(expectedMatchAttempts), matchAttempts);
    matchAttempts.clear();
}
 
Example 13
Project: NGB-master   File: FeatureIndexManager.java   View Source Code Vote up 5 votes
private void putVariationsInIndex(List<VcfIndexEntry> allEntries, String currentKey, VcfFile vcfFile,
                                  List<GeneFile> geneFiles, Map<String, Chromosome> chromosomeMap,
                                  VcfFileReader vcfFileReader, VCFHeader vcfHeader)
    throws GeneReadingException, IOException {
    if (currentKey != null && Utils.chromosomeMapContains(chromosomeMap, currentKey)) {
        List<VcfIndexEntry> processedEntries = postProcessIndexEntries(allEntries, geneFiles,
                                   Utils.getFromChromosomeMap(chromosomeMap, currentKey), vcfHeader, vcfFileReader);
        featureIndexDao.writeLuceneIndexForFile(vcfFile, processedEntries);
        LOGGER.info(MessageHelper.getMessage(MessagesConstants
                                                 .INFO_FEATURE_INDEX_CHROMOSOME_WROTE, currentKey));
        allEntries.clear();
    }
}
 
Example 14
Project: dubbox-hystrix   File: FailoverClusterInvokerTest.java   View Source Code Vote up 5 votes
/**
   * 测试在调用重试过程中,directory列表变更,invoke重试时重新进行list选择 
   */
  @Test
  public void testInvokerDestoryAndReList(){
  	final URL url = URL.valueOf("test://localhost/"+ Demo.class.getName() + "?loadbalance=roundrobin&retries="+retries);
  	RpcException exception = new RpcException(RpcException.TIMEOUT_EXCEPTION);
  	MockInvoker<Demo> invoker1 = new MockInvoker<Demo>(Demo.class, url);
  	invoker1.setException(exception);
  	
  	MockInvoker<Demo> invoker2 = new MockInvoker<Demo>(Demo.class, url);
  	invoker2.setException(exception);
  	
      final List<Invoker<Demo>> invokers = new ArrayList<Invoker<Demo>>();
      invokers.add(invoker1);
      invokers.add(invoker2);
      
      Callable<Object> callable = new Callable<Object>() {
	public Object call() throws Exception {
		//模拟invoker全部被destroy掉
		for (Invoker<Demo> invoker:invokers){
			invoker.destroy();
		}
		invokers.clear();
		MockInvoker<Demo> invoker3  = new MockInvoker<Demo>(Demo.class, url);
		invokers.add(invoker3);
		return null;
	}
};
invoker1.setCallable(callable);
      invoker2.setCallable(callable);
      
      RpcInvocation inv = new RpcInvocation();
      inv.setMethodName("test");
      
      Directory<Demo> dic = new MockDirectory<Demo>(url, invokers);
      
      FailoverClusterInvoker<Demo> clusterinvoker = new FailoverClusterInvoker<Demo>(dic);
      clusterinvoker.invoke(inv);
  }
 
Example 15
Project: sjk   File: ApiImporterMarketServiceImpl.java   View Source Code Vote up 4 votes
private PaginationMarketApp savePaginationForFull() throws Exception {
    // saveOrUpdate to table MarketApp
    PaginationMarketApp marketPagination = null;
    Session session = sessions.openSession();
    session.setDefaultReadOnly(false);
    Transaction tx = null;
    try {
        Market market = getMarket(session);
        marketPagination = getMarketAppForFull(market);
        if (marketPagination != null && marketPagination.getTotalPages() >= marketPagination.getCurrentPage()) {
            List<MarketApp> marketApps = marketPagination.getData();
            List<MarketApp> offMarketApps = new ArrayList<MarketApp>();
            if (marketApps != null && !marketApps.isEmpty()) {
                Object[] infos = new Object[] { market.getMarketName(), marketPagination.getTotalPages(),
                        marketPagination.getCurrentPage(), marketApps.size() };
                accessMarketDao.getMarketlogger().info(
                        "Begin to import {} on one page. totalPages: {} currentPage : {} , size: {}", infos);
                tx = session.beginTransaction();
                savePaginationMarketApp(session, market, marketApps, offMarketApps);
                market.setFullLastReqCurrentPage(marketPagination.getCurrentPage());
                market.setFullTotalPages(marketPagination.getTotalPages());
                market.setFullLastTime(new Date());
                session.merge(market);
                tx.commit();
                tx = null;
                session.clear();
                session.close();
                deleteMarketAppsTransaction(offMarketApps);
                marketApps.clear();
                offMarketApps.clear();
            }
        }
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        logger.error("Exception", e);
        throw e;
    } finally {
        if (session.isOpen()) {
            session.close();
        }
    }
    return marketPagination;
}
 
Example 16
Project: alfresco-repository   File: UserUsageTrackingComponent.java   View Source Code Vote up 4 votes
/**
 * Clear content usage for all users that have a usage.
 */
private void clearAllUsages()
{
    if (logger.isInfoEnabled()) 
    {
        logger.info("Disabled - clear non-missing user usages ...");
    }
    
    final Map<String, NodeRef> users = new HashMap<String, NodeRef>();
    
    RetryingTransactionCallback<Object> getUsersWithUsage = new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Throwable
        {
            // get people (users) with calculated usage
            MapHandler userHandler = new MapHandler()
            {
                public void handle(Map<String, Object> result)
                {
                    String username = (String)result.get("username");
                    String uuid = (String)result.get("uuid");
                    
                    if (! username.equalsIgnoreCase(AuthenticationUtil.getSystemUserName()))
                    {
                        users.put(username, new NodeRef(personStoreRef, uuid));
                    }
                }
            };
            usageDAO.getUsersWithUsage(tenantService.getName(personStoreRef), userHandler);
            
            return null;
        }
    };
    
    // execute in READ-ONLY txn
    transactionService.getRetryingTransactionHelper().doInTransaction(getUsersWithUsage, true);
    
    if (logger.isInfoEnabled()) 
    {
        logger.info("Found " + users.size() + " users to clear");
    }
    
    int clearCount = 0;
    int batchCount = 0;
    int totalCount = 0;
    
    List<NodeRef> batchPersonRefs = new ArrayList<NodeRef>(clearBatchSize);
    for (NodeRef personNodeRef : users.values())
    {
        batchPersonRefs.add(personNodeRef);
        batchCount++;
        totalCount++;
        
        if ((batchCount == clearBatchSize) || (totalCount == users.size()))
        {
            int cleared = clearUsages(batchPersonRefs);
            clearCount = clearCount + cleared;
            
            batchPersonRefs.clear();
            batchCount = 0;
        }
    }
    
    if (logger.isInfoEnabled()) 
    {
        logger.info("... cleared non-missing usages for " + clearCount + " users");
    }
}
 
Example 17
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostServletMoveTest.java   View Source Code Vote up 4 votes
public void testMoveNodeMultipleSourceReplace() throws Exception {
    final String testPath = TEST_BASE_PATH + "/mvmult/"
        + System.currentTimeMillis();
    final String testRoot = testClient.createNode(HTTP_BASE_URL + testPath,
        null);

    // create multiple source nodes
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src1", props);
    testClient.createNode(HTTP_BASE_URL + testPath + "/src2", props);

    // move the src? nodes
    List<NameValuePair> nvPairs = new ArrayList<NameValuePair>();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION,
        SlingPostConstants.OPERATION_MOVE));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath
        + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath
        + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath
        + "/src2"));
    assertPostStatus(testRoot, HttpServletResponse.SC_PRECONDITION_FAILED,
        nvPairs, "Expecting Move Failure: dest parent does not exist");

    // create destination parent
    testClient.createNode(HTTP_BASE_URL + testPath + "/dest", null);

    // now dest exists, so we expect success
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs,
        "Expecting Move Success");

    // assert partial existence of the src?/text properties
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src1/text",
        HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src2/text",
        HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src3/text",
        HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src4/text",
        HttpServletResponse.SC_NOT_FOUND);

    // assert content test
    String content = getContent(HTTP_BASE_URL + testPath
        + "/dest/src1.json", CONTENT_TYPE_JSON);
    JsonObject json = JsonUtil.parseObject(content);
    assertEquals("Hello", json.getString("text"));

    // modify src1 content
    nvPairs.clear();
    nvPairs.add(new NameValuePair("text", "Modified Hello"));
    assertPostStatus(HTTP_BASE_URL + testPath + "/src1",
        HttpServletResponse.SC_CREATED, nvPairs,
        "Expect Content Create Success");

    // move the src? nodes
    nvPairs.clear();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION,
        SlingPostConstants.OPERATION_MOVE));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath
        + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath
        + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath
        + "/src2"));
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs,
        "Expecting Move Success");

    // assert content test
    String content2 = getContent(HTTP_BASE_URL + testPath
        + "/dest/src1.json", CONTENT_TYPE_JSON);
    JsonObject json2 = JsonUtil.parseObject(content2);
    assertEquals("Modified Hello", json2.getString("text"));

    // clean up
    testClient.delete(testRoot);
}
 
Example 18
Project: parabuild-ci   File: NumberAxis.java   View Source Code Vote up 4 votes
/**
 * Calculates the positions of the tick labels for the axis, storing the 
 * results in the tick label list (ready for drawing).
 *
 * @param g2  the graphics device.
 * @param dataArea  the area in which the plot should be drawn.
 * @param edge  the location of the axis.
 * 
 * @return A list of ticks.
 *
 */
protected List refreshTicksVertical(Graphics2D g2,
                                    Rectangle2D dataArea,
                                    RectangleEdge edge) {

    List result = new java.util.ArrayList();
    result.clear();

    Font tickLabelFont = getTickLabelFont();
    g2.setFont(tickLabelFont);
    if (isAutoTickUnitSelection()) {
        selectAutoTickUnit(g2, dataArea, edge);
    }

    double size = getTickUnit().getSize();
    int count = calculateVisibleTickCount();
    double lowestTickValue = calculateLowestVisibleTickValue();

    if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
        for (int i = 0; i < count; i++) {
            double currentTickValue = lowestTickValue + (i * size);
            String tickLabel;
            NumberFormat formatter = getNumberFormatOverride();
            if (formatter != null) {
                tickLabel = formatter.format(currentTickValue);
            }
            else {
                tickLabel = getTickUnit().valueToString(currentTickValue);
            }

            TextAnchor anchor = null;
            TextAnchor rotationAnchor = null;
            double angle = 0.0;
            if (isVerticalTickLabels()) {
                if (edge == RectangleEdge.LEFT) { 
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                    angle = -Math.PI / 2.0;
                }
                else {
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                    angle = Math.PI / 2.0;
                }
            }
            else {
                if (edge == RectangleEdge.LEFT) {
                    anchor = TextAnchor.CENTER_RIGHT;
                    rotationAnchor = TextAnchor.CENTER_RIGHT;
                }
                else {
                    anchor = TextAnchor.CENTER_LEFT;
                    rotationAnchor = TextAnchor.CENTER_LEFT;
                }
            }

            Tick tick = new NumberTick(
                new Double(currentTickValue), tickLabel, anchor, 
                rotationAnchor, angle
            );
            result.add(tick);
        }
    }
    return result;

}
 
Example 19
Project: personium-core   File: ODataBatchResource.java   View Source Code Vote up 4 votes
/**
 * bulkリクエストのチェックと実行処理.
 * @param uriInfo uriInfo
 * @param boundary boundary
 * @param navigationPropertyBulkContexts ナビゲーションプロパティ経由登録リクエスト情報のリスト
 */
private void checkAndExecBulk(
        StringBuilder responseBody,
        UriInfo uriInfo,
        String boundary,
        List<NavigationPropertyBulkContext> navigationPropertyBulkContexts) {
    if (!navigationPropertyBulkContexts.isEmpty()) {
        if (!isTimedOut(BatchElapsedTimer.Lock.YIELD)) {
            if (!shutter.isShuttered()) {
                execBulkRequestForNavigationProperty(navigationPropertyBulkContexts);

                createNavigationPropertyBulkResponse(
                        responseBody,
                        uriInfo,
                        boundary,
                        navigationPropertyBulkContexts);
            } else {
                // 前のブロックで503エラーが発生している場合
                createTooManyConcurrentResponse(navigationPropertyBulkContexts);
            }
        } else {
            for (NavigationPropertyBulkContext npBulkContext : navigationPropertyBulkContexts) {
                npBulkContext.setException(PersoniumCoreException.Misc.SERVER_REQUEST_TIMEOUT);
                npBulkContext.getBatchResponse().setErrorResponse(
                        PersoniumCoreException.Misc.SERVER_REQUEST_TIMEOUT);
                BatchBodyPart bodyPart = npBulkContext.getBodyPart();
                responseBody.append(getChangesetResponseBody(boundary, bodyPart,
                        npBulkContext.getBatchResponse()));
            }
        }
        navigationPropertyBulkContexts.clear();
    } else {
        if (bulkRequests.size() != 0) {
            if (!isTimedOut(BatchElapsedTimer.Lock.YIELD)) {
                if (!shutter.isShuttered()) {
                    execBulk(responseBody, uriInfo, boundary);
                } else {
                    // 前のブロックで503エラーが発生している場合
                    createTooManyConcurrentResponse(responseBody, boundary);
                    bulkRequests.clear();
                }
            } else {
                for (Entry<String, BulkRequest> request : bulkRequests.entrySet()) {
                    BatchResponse res = new BatchResponse();
                    Exception exception = PersoniumCoreException.Misc.SERVER_REQUEST_TIMEOUT;
                    res.setErrorResponse(exception);
                    // レスポンスボディ作成
                    responseBody.append(getChangesetResponseBody(boundary, request.getValue().getBodyPart(), res));
                }
                bulkRequests.clear();
            }
        }
    }
}
 
Example 20
Project: imagetozxspec   File: ColourHelper.java   View Source Code Vote up 4 votes
/**
 * Colours an entire image using the given colourstrategy based on the
 * original and output images. Colours the Spectrum attribute blocks by
 * selecting xMax by yMax parts of the output image (i.e. usually 8x8
 * pixels), chooses the most popular two colours. The colour choice strategy
 * then decides how to colour individual pixels based on these two colours.
 * 
 * Note it is expected that this method will be called AFTER the pixels have
 * been changed to Spectrum colours.
 * 
 * @param image the image to colour
 * @param colourChoiceStrategy the colour choice strategy
 * @return the modified image
 */
public static BufferedImage colourAttributes(BufferedImage image, ColourChoiceStrategy colourChoiceStrategy) {

	// Do not use bidimap because inverse map key values will be lost (i.e. many tallies will produce same key)	
	Map<Integer, Integer> map = new HashMap<>();
	List<TallyValue> tallyValues = new LinkedList<>();
	
	// Analyse block and choose the two most popular colours in attribute block
	for (int y = 0; y + ATTRIBUTE_BLOCK_SIZE <= image.getHeight(); y += ATTRIBUTE_BLOCK_SIZE) {
		for (int x = 0; x + ATTRIBUTE_BLOCK_SIZE <= image.getWidth() && y + ATTRIBUTE_BLOCK_SIZE <= image.getHeight(); x += ATTRIBUTE_BLOCK_SIZE) {
			map.clear();
			tallyValues.clear();
			int outRgb[] = image.getRGB(x, y, ATTRIBUTE_BLOCK_SIZE, ATTRIBUTE_BLOCK_SIZE, null, 0, ATTRIBUTE_BLOCK_SIZE);

			for (int rgb : outRgb) {
				final int[] comps = intToRgbComponents(rgb);
				int value = getClosestColour(comps[0], comps[1], comps[2], SpectrumDefaults.SPECTRUM_COLOURS_ALL);
				int count = 1;
				if (map.containsKey(value)) {
					count = map.get(value) + 1;
				}
				map.put(value, count);
			}
			map.keySet().stream().forEach(colour -> {
				Integer tally = map.get(colour);
				tallyValues.add(new TallyValue(colour, tally));
			});
			tallyValues.sort(TallyValue.TALLY_COMPARATOR);
			
			int mostPopularColour = tallyValues.get(0).getColour();
			int secondMostPopularColour = tallyValues.size()>1?tallyValues.get(1).getColour():mostPopularColour;
			
			// Enforce attribute favouritism rules on the two spectrum
			// attribute colours (fixes the problem that colours could be from both the bright
			// and half bright set).
			int[] correctedAlphaColours = OptionsObject.getInstance().getAttributeMode().enforceAttributeRule(mostPopularColour, secondMostPopularColour);
						
			// Replace all colours in attribute block (which can be any spectrum colours) with the just the popular two
			for (int i = 0; i < outRgb.length; ++i) {
				outRgb[i] = colourChoiceStrategy.getClosestColour(outRgb[i], correctedAlphaColours);
			}
			image.setRGB(x, y, ATTRIBUTE_BLOCK_SIZE, ATTRIBUTE_BLOCK_SIZE, outRgb, 0, ATTRIBUTE_BLOCK_SIZE);
		}
	}
	return image;
}