java.util.Map Java Examples

The following examples show how to use java.util.Map. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UtilHelpers.java    From hudi with Apache License 2.0 7 votes vote down vote up
/***
 * call spark function get the schema through jdbc.
 * The code logic implementation refers to spark 2.4.x and spark 3.x.
 * @param options
 * @return
 * @throws Exception
 */
public static Schema getJDBCSchema(Map<String, String> options) throws Exception {
  Connection conn = createConnectionFactory(options);
  String url = options.get(JDBCOptions.JDBC_URL());
  String table = options.get(JDBCOptions.JDBC_TABLE_NAME());
  boolean tableExists = tableExists(conn, options);

  if (tableExists) {
    JdbcDialect dialect = JdbcDialects.get(url);
    try (PreparedStatement statement = conn.prepareStatement(dialect.getSchemaQuery(table))) {
      statement.setQueryTimeout(Integer.parseInt(options.get("queryTimeout")));
      try (ResultSet rs = statement.executeQuery()) {
        StructType structType;
        if (Boolean.parseBoolean(options.get("nullable"))) {
          structType = JdbcUtils.getSchema(rs, dialect, true);
        } else {
          structType = JdbcUtils.getSchema(rs, dialect, false);
        }
        return AvroConversionUtils.convertStructTypeToAvroSchema(structType, table, "hoodie." + table);
      }
    }
  } else {
    throw new HoodieException(String.format("%s table does not exists!", table));
  }
}
 
Example #2
Source File: TaskCacheEventListener.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Override
public void onAssignment(TaskAssignmentResult taskAssignmentResult) {
    V3QueueableTask request = (V3QueueableTask) taskAssignmentResult.getRequest();
    Map<String, String> taskContext = request.getTask().getTaskContext();
    if (taskContext.containsKey(TASK_ATTRIBUTES_IP_ALLOCATION_ID)) {
        taskCache.addTaskIpAllocation(taskAssignmentResult.getTaskId(), taskContext.get(TASK_ATTRIBUTES_IP_ALLOCATION_ID));
    }

    int opportunisticCpus = request.getOpportunisticCpus();
    if (request.isCpuOpportunistic() && opportunisticCpus > 0) {
        String machineId = taskAssignmentResult.getHostname();
        Optional<String> allocationId = opportunisticCpuCache.findAvailableOpportunisticCpus(machineId)
                .map(OpportunisticCpuAvailability::getAllocationId);
        if (!allocationId.isPresent()) {
            codeInvariants().inconsistent("Task assigned to opportunistic CPUs on machine %s that can not be found", machineId);
        }
        taskCache.addOpportunisticCpuAllocation(new OpportunisticCpuAllocation(
                taskAssignmentResult.getTaskId(),
                machineId,
                allocationId.orElse(UNKNOWN_ALLOCATION_ID),
                opportunisticCpus
        ));
    }
}
 
Example #3
Source File: RebootActionCleanup.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void execute(JobExecutionContext arg0In)
    throws JobExecutionException {
    List<Map<String, Long>> failedRebootActions = lookupRebootActionCleanup();
    for (Map<String, Long> fa : failedRebootActions) {
        Long sid = fa.get("server_id");
        Long aid = fa.get("action_id");
        List<Long> fAids = invalidateActionRecursive(sid, aid);
        for (Long fAid : fAids) {
            invalidateKickstartSession(sid, fAid);
        }
    }
    if (failedRebootActions.size() > 0) {
        log.info("Set " + failedRebootActions.size() +
                " reboot action(s) to failed. Running longer than 6 hours.");
    }
}
 
Example #4
Source File: RealRunningTimeTracker.java    From ambiverse-nlu with Apache License 2.0 6 votes vote down vote up
private TimingInfo getTrackedInfoImpl(Map<String, Map<Integer, Long>> start, Map<String, Map<Integer, Long>> end) {
  TimingInfo timingInfo = new TimingInfo();
  for (Entry<String, Integer> e : moduleLevelStart.entrySet()) {
    String module = e.getKey();
    int level = e.getValue();

    double totalTime = 0.0;
    double maxTime = 0.0;
    for (Integer uniqueId : end.get(module).keySet()) {
      Long finish = end.get(module).get(uniqueId);
      assert start.containsKey(module) : "No start for end.";
      Long begin = start.get(module).get(uniqueId);
      Long dur = finish - begin;
      totalTime += dur;
      if (dur > maxTime) {
        maxTime = dur;
      }
    }
    double avgTime = totalTime / end.get(module).size();
    timingInfo.addModule(new Module(module, level, end.get(module).size(), avgTime, maxTime));
  }

  timingInfo.setTotalExecutionTime(overallEndTime - overallStartTime);
  return timingInfo;
}
 
Example #5
Source File: CustomerLoadVOGenerator.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
public static final Map<String, String> getValidAddressVOTemplate() {
    Map<String, String> fields = new HashMap<String, String>();
    
    fields.put("customerAddressName", "");
    fields.put("customerLine1StreetAddress", "");
    fields.put("customerLine2StreetAddress", "");
    fields.put("customerCityName", "");
    fields.put("customerStateCode", "");
    fields.put("customerZipCode", "");
    fields.put("customerCountryCode", "");
    fields.put("customerAddressInternationalProvinceName", "");
    fields.put("customerInternationalMailCode", "");
    fields.put("customerEmailAddress", "");
    fields.put("customerAddressTypeCode", "");
    fields.put("customerAddressEndDate", "");

    return fields;
}
 
Example #6
Source File: HttpURLConnection.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an unmodifiable Map of general request
 * properties for this connection. The Map keys
 * are Strings that represent the request-header
 * field names. Each Map value is a unmodifiable List
 * of Strings that represents the corresponding
 * field values.
 *
 * @return  a Map of the general request properties for this connection.
 * @throws IllegalStateException if already connected
 * @since 1.4
 */
@Override
public synchronized Map<String, List<String>> getRequestProperties() {
    if (connected)
        throw new IllegalStateException("Already connected");

    // exclude headers containing security-sensitive info
    if (setUserCookies) {
        return requests.getHeaders(EXCLUDE_HEADERS);
    }
    /*
     * The cookies in the requests message headers may have
     * been modified. Use the saved user cookies instead.
     */
    Map<String, List<String>> userCookiesMap = null;
    if (userCookies != null || userCookies2 != null) {
        userCookiesMap = new HashMap<>();
        if (userCookies != null) {
            userCookiesMap.put("Cookie", Arrays.asList(userCookies));
        }
        if (userCookies2 != null) {
            userCookiesMap.put("Cookie2", Arrays.asList(userCookies2));
        }
    }
    return requests.filterAndAddHeaders(EXCLUDE_HEADERS2, userCookiesMap);
}
 
Example #7
Source File: ReflectUtils.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public static  Object getPropertyValue(Object element, String propName, Closure2<String, Exception> errorHandler) {
		if (element instanceof Map) {
			return getValue((Map) element, propName);
		}
		try{
//			Intro<?> info = getIntro(getObjectClass(element));
//			PropertyDescriptor pd = info.getProperty(propName);
//			return info.getPropertyValue(element, pd);
			return getIntro(getObjectClass(element)).getPropertyValue(element, propName);
		}catch(Exception e){
			/*logger.error("get ["+element+"] property["+propName+"] error: " + e.getMessage());
			if(throwIfError)
				throw new BaseException("get ["+element+"] property["+propName+"] error", e);*/
			errorHandler.execute(propName, e);
		}
		return null;
	}
 
Example #8
Source File: ListCompletionView.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public @Override void paint(Graphics g) {
    Object value = (Map)(Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints")); //NOI18N
    Map renderingHints = (value instanceof Map) ? (java.util.Map)value : null;
    if (renderingHints != null && g instanceof Graphics2D) {
        Graphics2D g2d = (Graphics2D) g;
        RenderingHints oldHints = g2d.getRenderingHints();
        g2d.setRenderingHints(renderingHints);
        try {
            super.paint(g2d);
        } finally {
            g2d.setRenderingHints(oldHints);
        }
    } else {
        super.paint(g);
    }
}
 
Example #9
Source File: DtxStart.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String,Object> getFields()
{
    Map<String,Object> result = new LinkedHashMap<String,Object>();

    if ((packing_flags & 256) != 0)
    {
        result.put("xid", getXid());
    }
    if ((packing_flags & 512) != 0)
    {
        result.put("join", getJoin());
    }
    if ((packing_flags & 1024) != 0)
    {
        result.put("resume", getResume());
    }


    return result;
}
 
Example #10
Source File: PvList.java    From AndrOBD with GNU General Public License v3.0 6 votes vote down vote up
/**
 * handle a set/map of data attributes with specified notification action
 *
 * @param data             Map of new data attributes to handle
 * @param action           PvChangeEvent-Action code to be used for notifications
 * @param allowChildEvents are child events (for each attribute) allowed?
 * @return previous value of corresponding data item
 */
@SuppressWarnings("rawtypes")
private synchronized Object handleData(Map data, int action, boolean allowChildEvents)
{
	Object result = null;


	if (data.containsKey(getKeyAttribute()))
	{
		// remember flag for event creation
		boolean oldAllowEvents = allowEvents;
		// set flag for event creation
		allowEvents = allowChildEvents;
		ProcessVar dataset = (ProcessVar) get(data.get(getKeyAttribute()));
		if (dataset == null)
		{
			dataset = new ProcessVar();
			dataset.setKeyAttribute(getKeyAttribute());
		}
		dataset.putAll(data, action, allowChildEvents);
		// restore flag for event creation
		allowEvents = oldAllowEvents;
		result = put(dataset.getKeyValue(), dataset, action);
	}
	return (result);
}
 
Example #11
Source File: HueBridgeHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method is called whenever the connection to the {@link HueBridge} is resumed.
 *
 * @throws ApiException if the physical device does not support this API call
 * @throws IOException if the physical device could not be reached
 */
private void onConnectionResumed() throws IOException, ApiException {
    logger.debug("Bridge connection resumed. Updating thing status to ONLINE.");

    if (!propertiesInitializedSuccessfully) {
        FullConfig fullConfig = hueBridge.getFullConfig();
        Config config = fullConfig.getConfig();
        if (config != null) {
            Map<String, String> properties = editProperties();
            properties.put(PROPERTY_SERIAL_NUMBER, config.getMACAddress().replaceAll(":", "").toLowerCase());
            properties.put(PROPERTY_FIRMWARE_VERSION, config.getSoftwareVersion());
            updateProperties(properties);
            propertiesInitializedSuccessfully = true;
        }
    }

    updateStatus(ThingStatus.ONLINE);
}
 
Example #12
Source File: JVMMonitor.java    From fqueue with Apache License 2.0 6 votes vote down vote up
public static Map<String, MemoryUsage> getMemoryPoolCollectionUsage() {
    Map<String, MemoryUsage> gcMemory = new HashMap<String, MemoryUsage>();
    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        String name = memoryPoolMXBean.getName();
        if (edenSpace.contains(name)) {
            gcMemory.put("eden", memoryPoolMXBean.getCollectionUsage());
        } else if (survivorSpace.contains(name)) {
            gcMemory.put("survivor", memoryPoolMXBean.getCollectionUsage());
        } else if (oldSpace.contains(name)) {
            gcMemory.put("old", memoryPoolMXBean.getCollectionUsage());
        } else if (permSpace.contains(name)) {
            gcMemory.put("perm", memoryPoolMXBean.getCollectionUsage());
        } else if (codeCacheSpace.contains(name)) {
            gcMemory.put("codeCache", memoryPoolMXBean.getCollectionUsage());
        }

    }
    return gcMemory;
}
 
Example #13
Source File: SiteMsgUtil.java    From agile-service-old with Apache License 2.0 6 votes vote down vote up
public void issueSolve(List<Long> userIds, String userName, String summary, String url, Long assigneeId, Long projectId) {
    NoticeSendDTO noticeSendDTO = new NoticeSendDTO();
    noticeSendDTO.setCode("issueSolve");
    Map<String, Object> params = new HashMap<>();
    params.put(ASSIGNEENAME, userName);
    params.put(SUMMARY, summary);
    params.put(URL, url);
    noticeSendDTO.setParams(params);
    List<NoticeSendDTO.User> userList = new ArrayList<>();
    for (Long id : userIds) {
        NoticeSendDTO.User user = new NoticeSendDTO.User();
        user.setId(id);
        userList.add(user);
    }
    noticeSendDTO.setTargetUsers(userList);
    NoticeSendDTO.User fromUser = new NoticeSendDTO.User();
    fromUser.setId(assigneeId);
    noticeSendDTO.setFromUser(fromUser);
    noticeSendDTO.setSourceId(projectId);
    try {
        notifyFeignClient.postNotice(noticeSendDTO);
    } catch (Exception e) {
        LOGGER.error("完成issue消息发送失败", e);
    }
}
 
Example #14
Source File: ConsumerTest.java    From kbear with Apache License 2.0 6 votes vote down vote up
protected void commitSync(
        java.util.function.BiConsumer<Consumer<String, String>, Map<TopicPartition, OffsetAndMetadata>> committer)
        throws InterruptedException {
    produceMessages();

    try (Consumer<String, String> consumer = createConsumerWithoutAutoCommit()) {
        consumer.subscribe(_topics);
        pollDurationTimeout(consumer);

        OffsetAndMetadata committed = consumer.committed(_topicPartition);
        System.out.println("committed: " + committed);
        OffsetAndMetadata committed2 = new OffsetAndMetadata(committed.offset() + _messageCount,
                committed.metadata());
        System.out.println("committed2: " + committed2);
        Map<TopicPartition, OffsetAndMetadata> offsetMap = new HashMap<>();
        offsetMap.put(_topicPartition, committed2);
        committer.accept(consumer, offsetMap);
        OffsetAndMetadata committed3 = consumer.committed(_topicPartition);
        System.out.println("committed3: " + committed3);
        Assert.assertEquals(committed2.offset(), committed3.offset());
    }
}
 
Example #15
Source File: ResetPasswordFactory.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find a given ResetPassword entry by token.
 * @param token token of interest
 * @return ResetPassword, or null if none found
 */
public static ResetPassword lookupByToken(String token) {
    SelectMode sm = ModeFactory.getMode("ResetPassword_queries",
                                        "find_by_token");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("token", token);
    DataResult<ResetPassword> dr = sm.execute(params);
    if (dr == null || dr.size() == 0) {
        return null;
    }
    else {
        return dr.get(0);
    }
}
 
Example #16
Source File: BindingSetTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void requireThatTreeSplitCanBeBoundForPorts() {
    Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
    RequestHandler foo8080 = new NonWorkingRequestHandler();
    RequestHandler foo80 = new NonWorkingRequestHandler();
    RequestHandler foobar = new NonWorkingRequestHandler();
    RequestHandler foopqrbar = new NonWorkingRequestHandler();

    handlers.put(new UriPattern("http://host:8080/foo"), foo8080);
    handlers.put(new UriPattern("http://host:70/foo"), foo80);
    handlers.put(new UriPattern("http://hostpqr:70/foo"), foopqrbar);
    handlers.put(new UriPattern("http://host:80/foobar"), foobar);
    BindingSet<RequestHandler> bindings = new BindingSet<>(handlers.entrySet());
    assertNotNull(bindings);
}
 
Example #17
Source File: Req4000DAO.java    From oslits with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public void selectReq4000ExcelList(Map paramMap,
		ExcelDataListResultHandler resultHandler) throws Exception {
	// TODO Auto-generated method stub
	listExcelDownSql("req4000DAO.selectReq4000ReqClsList", paramMap, resultHandler);
	
}
 
Example #18
Source File: ClientSessionMemoryLocalPersistence.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Override
@ExecuteInSingleWriter
public void removeWithTimestamp(final @NotNull String clientId, final int bucketIndex) {

    final Map<String, PersistenceEntry<ClientSession>> bucket = getBucket(bucketIndex);
    final PersistenceEntry<ClientSession> remove = bucket.remove(clientId);
    if (remove != null) {
        final ClientSession clientSession = remove.getObject();
        if (isPersistent(clientSession) || clientSession.isConnected()) {
            sessionsCount.decrementAndGet();
        }
        removeWillReference(clientSession);
        currentMemorySize.addAndGet(-(remove.getEstimatedSize() + ObjectMemoryEstimation.stringSize(clientId)));
    }
}
 
Example #19
Source File: AbstractAsynchronousOperationHandlers.java    From flink with Apache License 2.0 5 votes vote down vote up
protected TriggerHandler(
		GatewayRetriever<? extends T> leaderRetriever,
		Time timeout,
		Map<String, String> responseHeaders,
		MessageHeaders<B, TriggerResponse, M> messageHeaders) {
	super(leaderRetriever, timeout, responseHeaders, messageHeaders);
}
 
Example #20
Source File: RestoreCommitLogsActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private void assertCommitLogBuckets(Map<Integer, DateTime> bucketIdsAndTimestamps) {
  Map<Long, CommitLogBucket> buckets = ofy().load()
      .type(CommitLogBucket.class)
      .ids(Longs.asList(Longs.toArray(CommitLogBucket.getBucketIds())));
  assertThat(buckets).hasSize(bucketIdsAndTimestamps.size());
  for (Entry<Integer, DateTime> bucketIdAndTimestamp : bucketIdsAndTimestamps.entrySet()) {
    assertThat(buckets.get((long) bucketIdAndTimestamp.getKey()).getLastWrittenTime())
        .isEqualTo(bucketIdAndTimestamp.getValue());
  }
}
 
Example #21
Source File: AntMerchantExpandIndirectActivityCreateRequest.java    From alipay-sdk-java-all with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getTextParams() {		
	AlipayHashMap txtParams = new AlipayHashMap();
	txtParams.put("biz_content", this.bizContent);
	if(udfParams != null) {
		txtParams.putAll(this.udfParams);
	}
	return txtParams;
}
 
Example #22
Source File: CommentsDiffTool.java    From review-board-idea-plugin with Apache License 2.0 5 votes vote down vote up
private void updateHighLights(Editor editor) {
    MarkupModel markup = editor.getMarkupModel();

    for (RangeHighlighter customRangeHighlighter : newCommentHighlighters) {
        markup.removeHighlighter(customRangeHighlighter);
    }
    newCommentHighlighters.clear();

    int lineCount = markup.getDocument().getLineCount();

    Map<Integer, List<Comment>> lineComments = lineComments(comments);
    for (Map.Entry<Integer, List<Comment>> entry : lineComments.entrySet()) {
        if (entry.getKey() > lineCount) continue;

        boolean hasNewComments = false;
        for (Comment comment : entry.getValue()) {
            if (comment.id == null) {
                hasNewComments = true;
                break;
            }
        }

        TextAttributes attributes = new TextAttributes();
        if (hasNewComments) attributes.setBackgroundColor(JBColor.PINK);
        else attributes.setBackgroundColor(JBColor.YELLOW);

        RangeHighlighter rangeHighlighter = markup
                .addLineHighlighter(entry.getKey() - 1, HighlighterLayer.SELECTION + (hasNewComments ? 2 : 1), attributes);
        rangeHighlighter.setGutterIconRenderer(new CommentGutterIconRenderer());
        newCommentHighlighters.add(rangeHighlighter);
    }
}
 
Example #23
Source File: CompoundWriteTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void overwritesExistingChild() {
  CompoundWrite compoundWrite = CompoundWrite.emptyWrite();
  Map<String, Object> base =
      new MapBuilder().put("child-1", "value-1").put("child-2", "value-2").build();
  Node baseNode = NodeUtilities.NodeFromJSON(base);
  Path path = new Path("child-1");
  compoundWrite = compoundWrite.addWrite(path, LEAF_NODE);
  Assert.assertEquals(
      baseNode.updateImmediateChild(path.getFront(), LEAF_NODE), compoundWrite.apply(baseNode));
}
 
Example #24
Source File: TestCountBasedStreamChooser.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testHostsHaveDifferentNumberStreams() {
    Map<SocketAddress, Set<String>> streamDistribution = new HashMap<SocketAddress, Set<String>>();
    Set<String> allStreams = new HashSet<String>();

    int numHosts = 6;
    int maxStreamsPerHost = 4;

    int port = 1000;
    for (int i = 0; i < numHosts; i++) {
        int group = i / 2;
        int numStreamsThisGroup = maxStreamsPerHost - group;

        SocketAddress address = new InetSocketAddress("127.0.0.1", port + i);
        Set<String> streams = new HashSet<String>();

        for (int j = 1; j <= numStreamsThisGroup; j++) {
            String streamName = "HostsHaveDifferentNumberStreams-" + i + "-" + j;
            streams.add(streamName);
            allStreams.add(streamName);
        }

        streamDistribution.put(address, streams);
    }

    Set<String> streamsChoosen = new HashSet<String>();
    CountBasedStreamChooser chooser = new CountBasedStreamChooser(streamDistribution);

    for (int i = 0; i < allStreams.size(); i++) {
        String s = chooser.choose();
        assertNotNull(s);
        streamsChoosen.add(s);
    }
    assertNull(chooser.choose());
    assertEquals(allStreams.size(), streamsChoosen.size());
    assertTrue(Sets.difference(allStreams, streamsChoosen).isEmpty());
}
 
Example #25
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadAttributesMapNoTypeBasicSize() throws IOException {
    Path foo = addFile("/foo");
    setContents(foo, new byte[1024]);

    Map<String, Object> attributes = fileSystem.readAttributes(createPath("/foo"), "size");
    Map<String, ?> expected = Collections.singletonMap("basic:size", Files.size(foo));
    assertEquals(expected, attributes);
}
 
Example #26
Source File: NamingGenerator.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void generate(ProtocGeneratorOptions options, RootNode ast) throws Exception {
   this.ast = ast;

   outputDir = new File(options.getOutputPath());
   mainPkgDir = new File(outputDir, options.getPackageName().replaceAll("\\.", "/"));
   mainPkgDir.mkdirs();

   if (options.getTestOutputPath() != null) {
      testDir = new File(options.getTestOutputPath());
      testPkgDir = new File(testDir, options.getPackageName().replaceAll("\\.", "/"));
      testPkgDir.mkdirs();
   }

   Set<String> bindings = new HashSet<>();
   List<Map<String, Object>> dataBindings = new ArrayList<>();

   generateConstantBindings(options.getPackageName(), ast.getConstants(), bindings);

   String pkg = null;
   for (List<QualifiedName> group : ast.getQualifiedGroups().values()) {
       if (pkg == null && group != null && !group.isEmpty()) {
          pkg = group.get(0).getPkg();
       }
       generateMessageBindings(options, group, ast.getQualified(), ast.getConstants(), bindings, dataBindings);
   }

   generateBindingsList(options.getPackageName(), pkg, bindings);
}
 
Example #27
Source File: ThreadAnalyser.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private ThreadObject parseThread(Map<String, Object> map) {

        ThreadObject to = new ThreadObject();

        String info = (String) map.get("info");
        String[] thread = info.split("\n");
        extractFromTitle(thread[0], to);
        extractStackTrace(thread, to);
        to.setInfo(info);

        String percpu = map.get("percpu").toString();
        to.setCpu(DataConvertHelper.toDouble(percpu, 0));
        to.setTime(DataConvertHelper.toLong(map.get("time").toString(), 0));
        return to;
    }
 
Example #28
Source File: VFSBlobVault.java    From xodus with Apache License 2.0 5 votes vote down vote up
@Override
public void flushBlobs(@Nullable final LongHashMap<InputStream> blobStreams,
                       @Nullable final LongHashMap<File> blobFiles,
                       @Nullable final LongSet deferredBlobsToDelete,
                       @NotNull final Transaction txn) throws Exception {
    if (blobStreams != null) {
        blobStreams.forEachEntry((ObjectProcedureThrows<Map.Entry<Long, InputStream>, Exception>) object -> {
            final InputStream stream = object.getValue();
            stream.reset();
            setContent(object.getKey(), stream, txn);
            return true;
        });
    }
    // if there were blob files then move them
    if (blobFiles != null) {
        blobFiles.forEachEntry((ObjectProcedureThrows<Map.Entry<Long, File>, Exception>) object -> {
            setContent(object.getKey(), object.getValue(), txn);
            return true;
        });
    }
    // if there are deferred blobs to delete then defer their deletion
    if (deferredBlobsToDelete != null) {
        try {
            final LongIterator it = deferredBlobsToDelete.iterator();
            while (it.hasNext()) {
                delete(it.nextLong(), txn);
            }
        } finally {
            txn.abort();
        }
    }
}
 
Example #29
Source File: ArchivaCli.java    From archiva with Apache License 2.0 5 votes vote down vote up
private void dumpAvailableConsumers()
{
    Map<String, KnownRepositoryContentConsumer> availableConsumers = getConsumers();

    LOGGER.info( ".\\ Available Consumer List \\.______________________________" );

    for ( Map.Entry<String, KnownRepositoryContentConsumer> entry : availableConsumers.entrySet() )
    {
        String consumerHint = entry.getKey();
        RepositoryContentConsumer consumer = entry.getValue();
        LOGGER.info( "  {} : {} ({})", //
                     consumerHint, consumer.getDescription(), consumer.getClass().getName() );
    }
}
 
Example #30
Source File: TumorContaminationModelTest.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testHighContamination() throws IOException {
    final Map<Integer, Long> contaminationMap = fromFile(CONTAMINATION_HIGH);
    final TumorContaminationModel model = new TumorContaminationModel();
    assertEquals(249329, TumorContaminationModel.reads(2, contaminationMap));
    assertEquals(248936, TumorContaminationModel.reads(3, contaminationMap));

    final double contamination = model.contamination(107, contaminationMap);
    assertEquals(1, contamination, EPSILON);
}