/** * checks if a particular chained task is ready for processing * * @param chain_id the id this process is part off order * @param process_id the process_id * @return * @throws java.sql.SQLException */ public boolean canExecute(int chain_id, int process_id) throws SQLException { boolean isReady = false; try (AutoCloseableDBConnection c = new AutoCloseableDBConnection(); PreparedStatement getChain = c.prepareStatement( "SELECT process_id,busy FROM chain_activities WHERE (chain_id=?) ORDER BY process_id")) { getChain.setInt(1, chain_id); LinkedHashMap<Integer, Boolean> clearedToRunMap = new LinkedHashMap<>(); try (ResultSet executeQuery = getChain.executeQuery()) { while (executeQuery.next()) { clearedToRunMap.put(executeQuery.getInt("process_id"), executeQuery.getBoolean("busy")); } } int predecessingProcess = -1; for (Entry<Integer, Boolean> aProcess : clearedToRunMap.entrySet()) { if (aProcess.getKey() == process_id) { break; } else { predecessingProcess = aProcess.getKey(); // check if this process is already busy } } if (predecessingProcess == -1) { // then there's no predecessing process, meaning it can be run for sure isReady = true; } else if (clearedToRunMap.get(predecessingProcess)) { try ( // then it's busy, but it can be that it's not yet done ! ProcessDAO pdao = ProcessDAO.getInstance()) { isReady = pdao.isCompletedProcess(process_id); } } } return isReady; }
private void getContactList() { contactList.clear(); Map<String, EaseUser> users = DemoHelper.getInstance().getContactList(); Iterator<Entry<String, EaseUser>> iterator = users.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, EaseUser> entry = iterator.next(); if (!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME) && !entry.getKey().equals(Constant.GROUP_USERNAME) && !entry.getKey().equals(Constant.CHAT_ROOM) && !entry.getKey().equals(Constant.CHAT_ROBOT)) contactList.add(entry.getValue()); } // 排序 Collections.sort( contactList, new Comparator<EaseUser>() { @Override public int compare(EaseUser lhs, EaseUser rhs) { if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) { return lhs.getNick().compareTo(rhs.getNick()); } else { if ("#".equals(lhs.getInitialLetter())) { return 1; } else if ("#".equals(rhs.getInitialLetter())) { return -1; } return lhs.getInitialLetter().compareTo(rhs.getInitialLetter()); } } }); }
/** * Generate http request entity from Spring Integration message. * * @param requestMessage * @param method * @return */ private HttpEntity<?> generateRequest(Message<?> requestMessage, HttpMethod method) { HttpHeaders httpHeaders = new HttpHeaders(); headerMapper.fromHeaders(requestMessage.getHeaders(), httpHeaders); Map<String, ?> messageHeaders = requestMessage.getHeaders(); for (Entry<String, ?> header : messageHeaders.entrySet()) { if (!header.getKey().startsWith(CitrusMessageHeaders.PREFIX) && !MessageUtils.isSpringInternalHeader(header.getKey()) && !httpHeaders.containsKey(header.getKey())) { httpHeaders.add(header.getKey(), header.getValue().toString()); } } Object payload = requestMessage.getPayload(); if (httpHeaders.getContentType() == null) { httpHeaders.setContentType( MediaType.parseMediaType( contentType.contains("charset") ? contentType : contentType + ";charset=" + charset)); } if (HttpMethod.POST.equals(method) || HttpMethod.PUT.equals(method)) { return new HttpEntity<Object>(payload, httpHeaders); } return new HttpEntity<Object>(httpHeaders); }
@Override public LocalDateDoubleTimeSeries evaluate(final LocalDateDoubleTimeSeries... x) { testInputData(x); if (x.length > 2) { s_logger.info("Have more than two time series in array; only using first two"); } final FastIntDoubleTimeSeries ts1 = (FastIntDoubleTimeSeries) x[0].getFastSeries(); final FastIntDoubleTimeSeries ts2 = (FastIntDoubleTimeSeries) x[1].getFastSeries(); final int n = ts1.size(); final int[] times = new int[n]; final double[] returns = new double[n]; final Iterator<Entry<Integer, Double>> iter1 = ts1.iterator(); Entry<Integer, Double> entry1; Double value2; Integer t; int i = 0; while (iter1.hasNext()) { entry1 = iter1.next(); t = entry1.getKey(); value2 = ts2.getValue(t); if (value2 == null || Math.abs(value2) < ZERO) { if (getMode().equals(CalculationMode.STRICT)) { throw new TimeSeriesException("No data in second series for time " + t); } } else { times[i] = entry1.getKey(); returns[i++] = Math.log(entry1.getValue() / value2); } } return getSeries(x[0], times, returns, i); }
private Instance getConnectorConfiguration(Model model, StringToExpressionConverter converter) { final Instance configuration = model.newInstance("connectorconfiguration.ConnectorConfiguration"); configuration.set("definitionId", getDefinitionId()); configuration.set("version", getDefinitionVersion()); final Map<String, Object> additionalInputs = definitionMapper.getAdditionalInputs(inputs); final Map<String, Object> allInput = new HashMap<String, Object>(inputs); allInput.putAll(additionalInputs); for (Entry<String, Object> input : allInput.entrySet()) { final String parameterKeyFor = getParameterKeyFor(input.getKey()); if (parameterKeyFor != null) { final Instance parameter = model.newInstance("connectorconfiguration.ConnectorParameter"); parameter.set("key", parameterKeyFor); parameter.set( "expression", getParameterExpressionFor( model, parameterKeyFor, converter, definitionMapper.transformParameterValue(parameterKeyFor, input.getValue(), inputs), getReturnType(parameterKeyFor))); configuration.add("parameters", parameter); } else { if (BonitaStudioLog.isLoggable(IStatus.OK)) { BonitaStudioLog.debug( input.getKey() + " not mapped for " + getDefinitionId(), BarImporterPlugin.PLUGIN_ID); } } } return configuration; }
/** * Get all the acceptable values for a option for a board The outcome of this method can be used * to fill a combobox * * @param menu the name of a menu not the ide * @param boardName the name of a board not the ide * @return */ public String[] getMenuItemNames(String menuLabel, String boardName) { String menuID = null; String boardID = getBoardIDFromName(boardName); HashSet<String> ret = new HashSet<String>(); Map<String, String> menuInfo = mArduinoSupportedBoards.get("menu"); for (Entry<String, String> e2 : menuInfo.entrySet()) { if (e2.getValue().equals(menuLabel)) menuID = e2.getKey(); } String SearchKey = menuID + "." + boardID + "."; for (Entry<String, String> e2 : menuInfo.entrySet()) { int numsubkeys = e2.getKey().split("\\.").length; boolean startOk = e2.getKey().startsWith(SearchKey); if ((numsubkeys == 3) && (startOk)) ret.add(e2.getValue()); } // from Arduino IDE 1.5.4 menu is subset of the board. The previous code will not return a // result Map<String, String> boardInfo = mArduinoSupportedBoards.get(boardID); if (boardInfo != null) { SearchKey = "menu." + menuID + "."; for (Entry<String, String> e2 : boardInfo.entrySet()) { int numsubkeys = e2.getKey().split("\\.").length; boolean startOk = e2.getKey().startsWith(SearchKey); if ((numsubkeys == 3) && (startOk)) ret.add(e2.getValue()); } } return ret.toArray(new String[ret.size()]); }
public synchronized CDOChangeSetData merge(CDOChangeSet target, CDOChangeSet source) throws ConflictException { result = new CDOChangeSetDataImpl(); conflicts = CDOIDUtil.createMap(); targetMap = createMap(target); sourceMap = createMap(source); Set<CDOID> taken = new HashSet<CDOID>(); for (Entry<CDOID, Object> entry : targetMap.entrySet()) { CDOID id = entry.getKey(); Object targetData = entry.getValue(); Object sourceData = sourceMap.get(id); if (merge(targetData, sourceData)) { taken.add(id); } } for (Entry<CDOID, Object> entry : sourceMap.entrySet()) { CDOID id = entry.getKey(); if (taken.add(id)) { Object sourceData = entry.getValue(); Object targetData = targetMap.get(id); merge(targetData, sourceData); } } if (!conflicts.isEmpty()) { throw new ConflictException( "Merger could not resolve all conflicts: " + conflicts, this, result); } return result; }
/** * Non-Leaf command help. * * <p>This method is called if the given command line <code>args</code> calls for help on a * non-leaf (i.e. no commons-cli switches) node. * * @param exitCode the <code>System.exit</code> value to use. * @param msg Optional error message. Null if only help is to be displayed, Message is sent to * standard err before the help if not null. */ protected void commandHelp(int exitCode, String msg) { if (exitCode != 0 && msg != null) System.err.println(msg); String cmdStr = getLeadingCommandString(this); if (commandName != null) cmdStr += " " + commandName; StringBuilder sb = new StringBuilder("\nValid commands: " + cmdStr + " [-h|--help]|<"); boolean first = true; for (Entry<String, CliCommand> entry : commands.entrySet()) { if (!first) sb.append("|"); sb.append(entry.getKey()); first = false; } sb.append(">\n"); sb.append(" -h,--help Display " + commandName + " help.\n"); sb.append("\n Help for any given " + commandName + " sub-command can be obtained by:\n"); for (Entry<String, CliCommand> entry : commands.entrySet()) sb.append( " " + entry.getKey() + " [-" + CliBase.HelpShortCl + " | --" + CliBase.HelpLongCl + "]\n"); System.out.println(sb.toString()); // System.exit(exitCode); throw new RuntimeException(getClass().getSimpleName() + " Help displayed, see logs"); }
public static <Type> JSONValue toJSON( Map<String, Type> value, AbstractJsonEncoderDecoder<Type> encoder, Style style) { if (value == null) { return JSONNull.getInstance(); } switch (style) { case DEFAULT: case SIMPLE: { JSONObject rc = new JSONObject(); for (Entry<String, Type> t : value.entrySet()) { rc.put(t.getKey(), encoder.encode(t.getValue())); } return rc; } case JETTISON_NATURAL: { JSONObject rc = new JSONObject(); JSONArray entries = new JSONArray(); int i = 0; for (Entry<String, Type> t : value.entrySet()) { JSONObject entry = new JSONObject(); entry.put("key", new JSONString(t.getKey())); entry.put("value", encoder.encode(t.getValue())); entries.set(i++, entry); } rc.put("entry", entries); return rc; } default: throw new UnsupportedOperationException( "The encoding style is not yet suppored: " + style.name()); } }
private List<GenericClass> getAssignableClasses( TypeVariable<?> typeVariable, boolean allowRecursion, Map<TypeVariable<?>, Type> ownerVariableMap) { Map<GenericClass, Integer> assignableClasses = new LinkedHashMap<GenericClass, Integer>(); logger.debug("Getting assignable classes for type variable " + typeVariable); for (Entry<GenericClass, Integer> entry : classMap.entrySet()) { GenericClass key = entry.getKey(); logger.debug("Current class for type variable " + typeVariable + ": " + key); if (!key.satisfiesBoundaries(typeVariable, ownerVariableMap)) { logger.debug("Bounds not satisfied"); continue; } if (!allowRecursion && key.hasWildcardOrTypeVariables()) { logger.debug("Recursion not allowed but type has wilcard or type variables"); continue; } assignableClasses.put(entry.getKey(), entry.getValue()); } logger.debug("Found assignable classes: " + assignableClasses.size()); return sortByValue(assignableClasses); }
@Test public void testFromSystem_containsListValues() throws Exception { AbstractConfiguration.setDefaultListDelimiter('|'); Map<String, String> properties = Maps.newHashMap(); properties.put("testProperty", "b,bee"); for (Entry<String, String> entry : properties.entrySet()) { System.setProperty(entry.getKey(), entry.getValue()); } Splitter splitter = Splitter.on(','); Configuration systemConfiguration = configurationHelper.fromSystem(); for (Entry<String, String> entry : properties.entrySet()) { String[] actualValues = systemConfiguration.getStringArray(entry.getKey()); String[] expectedValues; if ("line.separator".equals(entry.getKey())) { expectedValues = new String[] {SystemUtils.LINE_SEPARATOR}; } else { expectedValues = splitter.splitToList(entry.getValue()).toArray(new String[0]); } assertArrayEquals( String.format("Values for key %s do not match", entry.getKey()), expectedValues, actualValues); } }
private List<GenericClass> getAssignableClasses( WildcardType wildcardType, boolean allowRecursion, Map<TypeVariable<?>, Type> ownerVariableMap) { Map<GenericClass, Integer> assignableClasses = new LinkedHashMap<GenericClass, Integer>(); logger.debug("Getting assignable classes for wildcard type " + wildcardType); for (Entry<GenericClass, Integer> entry : classMap.entrySet()) { GenericClass key = entry.getKey(); logger.debug("Current class for wildcard " + wildcardType + ": " + key); if (!key.satisfiesBoundaries(wildcardType, ownerVariableMap)) { logger.debug("Does not satisfy boundaries"); continue; } if (!allowRecursion && key.hasWildcardOrTypeVariables()) { logger.debug("Stopping because of type recursion"); continue; } logger.debug("Is assignable"); assignableClasses.put(entry.getKey(), entry.getValue()); } return sortByValue(assignableClasses); }
@Override public boolean loadLibrary(String libname, boolean ignoreError, ClassLoader cl) { try { for (Entry<String, String> nativeEntry : platformNativeIndex.entrySet()) { if (nativeEntry.getKey().contains(libname)) { if (log.isDebugEnabled()) { log.debug( "Loading mapped entry: [{}] [{}] [{}]", libname, nativeEntry.getKey(), nativeEntry.getValue()); } File nativeLibCopy = extractJarEntry( nativeEntry.getValue(), nativeEntry.getKey(), System.getProperty(JAVA_TMP_DIR), String.format("%s.jni", libname)); System.load(nativeLibCopy.getAbsolutePath()); return true; } } } catch (Exception e) { log.error("Unable to load native library [{}] - {}", libname, e); } if (log.isDebugEnabled()) { log.debug("No mapped library match for [{}]", libname); } return false; }
public static JsonObject mergeJsonFiles(JsonObject target, String... filenames) throws IOException { if (target == null) { target = new JsonObject(); } for (String filename : filenames) { String url = Config.CLOUD_STORAGE_BASE_URL + filename; JsonObject obj = fetchJsonFromPublicURL(url); if (obj == null) { throw new FileNotFoundException(url); } else { for (Entry<String, JsonElement> entry : obj.entrySet()) { if (entry.getValue().isJsonArray()) { // tries to merge an array with the existing one, if it's the case: JsonArray existing = target.getAsJsonArray(entry.getKey()); if (existing == null) { existing = new JsonArray(); target.add(entry.getKey(), existing); } existing.addAll(entry.getValue().getAsJsonArray()); } else { target.add(entry.getKey(), entry.getValue()); } } } } return target; }
private void updateMarkers(Map<String, Marker> markers) { markerLayout.removeAllComponents(); HashMap<String, Marker> newMarkers = new HashMap<String, Marker>(); TreeMap<Marker, String> ordered = new TreeMap<Marker, String>(); for (Entry<String, Marker> e : markers.entrySet()) { if (isTabWorthyMarker(e.getValue())) { newMarkers.put(e.getKey(), e.getValue()); ordered.put(e.getValue(), e.getKey()); } } for (Entry<Marker, String> e : ordered.entrySet()) { final String markerId = e.getValue(); MarkerButton b = new MarkerButton(e.getKey()); b.addListener( new ClickListener() { public void buttonClick(ClickEvent event) { activeMarker = markerId; showMarkerPopup(100); editor.scrollToMarkerId(markerId); } }); markerLayout.addComponent(b); } latestMarkers = newMarkers; }
@Test public void testFetchPartitionKeys() { HashMap<ByteArray, byte[]> entrySet = ServerTestUtils.createRandomKeyValuePairs(TEST_STREAM_KEYS_SIZE); List<Integer> fetchPartitionsList = Arrays.asList(0, 2); // insert it into server-0 store int fetchPartitionKeyCount = 0; Store<ByteArray, byte[]> store = getStore(0, testStoreName); for (Entry<ByteArray, byte[]> entry : entrySet.entrySet()) { store.put(entry.getKey(), new Versioned<byte[]>(entry.getValue())); if (isKeyPartition(entry.getKey(), 0, testStoreName, fetchPartitionsList)) { fetchPartitionKeyCount++; } } Iterator<ByteArray> fetchIt = getAdminClient().fetchKeys(0, testStoreName, fetchPartitionsList, null, false); // check values int count = 0; while (fetchIt.hasNext()) { assertEquals( "Fetched key should belong to asked partitions", true, isKeyPartition(fetchIt.next(), 0, testStoreName, fetchPartitionsList)); count++; } // assert all keys for asked partitions are returned. assertEquals("All keys for asked partitions should be received", fetchPartitionKeyCount, count); }
/* * (non-Javadoc) * * @see org.eclipse.papyrus.layout.LayouttoolInterface#execute(java.util.Map) */ public void execute(Map<EditPart, Rectangle> map) { TransactionalEditingDomain ted = getTransactionalEditingDomain(); if (ted != null) { CommandStack cs = null; // Add a command to apply new bounds of all nodes for (Entry<EditPart, Rectangle> s : map.entrySet()) { SetBoundsCommand boundsCommand = new SetBoundsCommand( ted, "apply layout", new EObjectAdapter((View) s.getKey().getModel()), s.getValue()); command.add(boundsCommand); GraphicalEditPart gep = (GraphicalEditPart) s.getKey(); if (cs == null) { cs = gep.getViewer().getEditDomain().getCommandStack(); } } try { // Execute layout commands with animation Animation.markBegin(); cs.execute(new ICommandProxy(command)); Animation.run(1000); } catch (Exception e) { Activator.getDefault().log(e.getMessage() + " : Cannot apply new bounds of all nodes", e); } } }
@Test public void testUpdate() { final HashMap<ByteArray, byte[]> entrySet = ServerTestUtils.createRandomKeyValuePairs(TEST_STREAM_KEYS_SIZE); Iterator<Pair<ByteArray, Versioned<byte[]>>> iterator = new AbstractIterator<Pair<ByteArray, Versioned<byte[]>>>() { final Iterator<Entry<ByteArray, byte[]>> entrySetItr = entrySet.entrySet().iterator(); @Override protected Pair<ByteArray, Versioned<byte[]>> computeNext() { while (entrySetItr.hasNext()) { Entry<ByteArray, byte[]> entry = entrySetItr.next(); return new Pair<ByteArray, Versioned<byte[]>>( entry.getKey(), new Versioned<byte[]>(entry.getValue())); } return endOfData(); } }; getAdminClient().updateEntries(0, testStoreName, iterator, null); // check updated values Store<ByteArray, byte[]> store = getStore(0, testStoreName); for (Entry<ByteArray, byte[]> entry : entrySet.entrySet()) { assertNotSame("entry should be present at store", 0, store.get(entry.getKey()).size()); assertEquals( "entry value should match", new String(entry.getValue()), new String(store.get(entry.getKey()).get(0).getValue())); } }
/** * This will update lists {@link #deletedAnnotations}, {@link #addedAnnotations} and {@link * #modifiedAnnotations} according to the given values. * * @param newOffset Offset of the text we want the annotation updated of. * @param newLength Length of the text we want the annotation updated of. * @param initiallyCollapsed Indicates that the created annotation should be folded from start. * @throws BadLocationException Thrown if we try and get an out of range character. Should not * happen. */ private void createOrUpdateAnnotation( final int newOffset, final int newLength, boolean initiallyCollapsed) throws BadLocationException { boolean createAnnotation = true; final Map<Annotation, Position> copy = new HashMap<Annotation, Position>(currentAnnotations); final String text = document.get(newOffset, newLength); for (Iterator<Entry<Annotation, Position>> iterator = copy.entrySet().iterator(); iterator.hasNext(); ) { Entry<Annotation, Position> entry = iterator.next(); if (entry.getKey().getText().equals(text)) { createAnnotation = false; final Position oldPosition = entry.getValue(); if (oldPosition.getOffset() != newOffset || oldPosition.getLength() != newLength) { final Position newPosition = new Position(newOffset, newLength); modifiedAnnotations.put(entry.getKey(), newPosition); currentAnnotations.put(entry.getKey(), newPosition); } deletedAnnotations.remove(entry.getKey()); break; } } if (createAnnotation) { Annotation annotation = null; annotation = new ProjectionAnnotation(initiallyCollapsed); annotation.setText(text); final Position position = new Position(newOffset, newLength); currentAnnotations.put(annotation, position); addedAnnotations.put(annotation, position); } }
@Test public void testRecoverData() { // use store with replication 2, required write 2 for this test. String testStoreName = "test-recovery-data"; HashMap<ByteArray, byte[]> entrySet = ServerTestUtils.createRandomKeyValuePairs(TEST_STREAM_KEYS_SIZE); // insert it into server-0 store Store<ByteArray, byte[]> store = getStore(0, testStoreName); for (Entry<ByteArray, byte[]> entry : entrySet.entrySet()) { store.put(entry.getKey(), new Versioned<byte[]>(entry.getValue())); } // assert server 1 is empty store = getStore(1, testStoreName); for (Entry<ByteArray, byte[]> entry : entrySet.entrySet()) { assertSame("entry should NOT be present at store", 0, store.get(entry.getKey()).size()); } // recover all data adminClient.restoreDataFromReplications(1, 2); // assert server 1 has all entries for its partitions store = getStore(1, testStoreName); for (Entry<ByteArray, byte[]> entry : entrySet.entrySet()) { ByteArray key = entry.getKey(); assertSame("entry should be present for key " + key, 1, store.get(entry.getKey()).size()); assertEquals( "entry value should match", new String(entry.getValue()), new String(store.get(entry.getKey()).get(0).getValue())); } }
/** * Computes the m matrix with one setup (you should execute it with the other setup too). * * @param root The ancestor of {@code w}, {@code x} nodes. ({@code v}). * @param d Distance matrix. * @param w The left node of {@code root}. * @param x The right node of {@code root}. * @param rightM The subtable for the right m. * @param ret The result table. * @param leftKeys The leaves of {@code w} tree. * @param rightKeys The leaves of {@code x} tree. */ private void computeM( final DendrogramNode root, final Map<RowKey, DistanceVectorDataValue> d, final DendrogramNode w, final DendrogramNode x, final Map<Triple<DendrogramNode, RowKey, RowKey>, Number> rightM, final Map<Triple<DendrogramNode, RowKey, RowKey>, Number> ret, final Set<RowKey> leftKeys, final Set<RowKey> rightKeys) { final Map<RowKey, Map<RowKey, Number>> t = computeT(w, ret, d, leftKeys, rightKeys); for (final Entry<RowKey, Map<RowKey, Number>> entry : t.entrySet()) { for (final Entry<RowKey, Number> innerEntry : entry.getValue().entrySet()) { double max = Double.NEGATIVE_INFINITY; for (final RowKey l : rightKeys) { final Triple<DendrogramNode, RowKey, RowKey> key = Triple.apply(x, l, innerEntry.getKey()); if (!rightM.containsKey(key)) { continue; } final double alternative = entry.getValue().get(l).doubleValue() + rightM.get(key).doubleValue(); if (alternative > max) { max = alternative; } } ret.put(Triple.apply(root, entry.getKey(), innerEntry.getKey()), Double.valueOf(max)); } } }
public ICredential getCredentialObject(String userId) throws MissingCredentialException, InvalidCredentialException { ICredential credential = null; if (getAccounts(configurationMap).size() == 0) { throw new MissingCredentialException( "No API accounts have been configured in application properties"); } String prefix = Constants.ACCOUNT_PREFIX; Map<String, String> credMap = getValuesByCategory(configurationMap, prefix); if (userId != null && userId.trim().length() != 0) { for (Entry<String, String> entry : credMap.entrySet()) { if (entry.getKey().endsWith(Constants.CREDENTIAL_USERNAME_SUFFIX) && entry.getValue().equalsIgnoreCase(userId)) { String acctKey = entry.getKey().substring(0, entry.getKey().indexOf('.')); credential = returnCredential(credMap, acctKey); } } if (credential == null) { throw new MissingCredentialException( "Account for the username does not exists in the properties file"); } } else { int index = 1; String userName = (String) credMap.get(prefix + index + Constants.CREDENTIAL_USERNAME_SUFFIX); if (userName != null && userName.trim().length() != 0) { credential = returnCredential(credMap, prefix + index); } else { throw new MissingCredentialException("Associate valid account for index 1"); } } return credential; }
public void assertAll(Iterable<Diagnostic> asserted, DiagnosticPredicate predicates[]) { HashMap<DiagnosticPredicate, Boolean> consumed = new HashMap<DiagnosticPredicate, Boolean>(); for (DiagnosticPredicate p : predicates) consumed.put(p, Boolean.FALSE); for (Diagnostic d : asserted) { boolean found = false; for (Entry<DiagnosticPredicate, Boolean> e : consumed.entrySet()) if ((!e.getValue() || e.getKey().isGreedy()) && e.getKey().apply(d)) { consumed.put(e.getKey(), Boolean.TRUE); found = true; break; } if (!found) { if (predicates.length == 1) throw new ComparisonFailure( "Predicate does not match", predicates[0].toString(), diagnosticsToString(d)); throw new ComparisonFailure( "No predicate in expected matches", Arrays.toString(predicates), diagnosticsToString(d)); } } ArrayList<DiagnosticPredicate> unconsumed = new ArrayList<DiagnosticPredicate>(); for (Entry<DiagnosticPredicate, Boolean> e : consumed.entrySet()) if (!e.getValue() && e.getKey().isRequired()) unconsumed.add(e.getKey()); if (unconsumed.size() != 0) throw new ComparisonFailure( "Missing diagnostics for required predicates", Arrays.toString(unconsumed.toArray()), diagnosticsToString(asserted)); }
public void init() throws BabuDBException { // load persisted snapshots from disk for (Entry<String, DatabaseInternal> entry : dbs.getDatabaseManager().getDatabasesInternal().entrySet()) { final File snapDir = new File(dbs.getConfig().getBaseDir(), entry.getKey() + "/snapshots"); if (snapDir.exists()) { Map<String, Snapshot> snapMap = new HashMap<String, Snapshot>(); snapshotDBs.put(entry.getKey(), snapMap); boolean compressed = entry.getValue().getLSMDB().getIndex(0).isCompressed(); boolean mmaped = entry.getValue().getLSMDB().getIndex(0).isMMapEnabled(); String[] snapshots = snapDir.list(); for (String snapName : snapshots) { BabuDBView view = new DiskIndexView( snapDir + "/" + snapName, entry.getValue().getComparators(), compressed, mmaped); snapMap.put(snapName, new Snapshot(view, dbs)); } } } }
/** {@inheritDoc} */ @Override public void setup(OAuth2Settings settings) throws OAuth2SettingsException { /* validate supplied settings */ if (settings == null) { throw new OAuth2SettingsException("Missing settings."); } if (Utils.isNullOrEmpty(settings.getTokenUri())) { throw new OAuth2SettingsException("Token server URI missing."); } else { tokenServer = settings.getTokenUri(); } if (Utils.isNullOrEmpty(settings.getRefreshToken())) { throw new OAuth2SettingsException("Refresh token cannot be null or empty."); } if (Utils.isNullOrEmpty(settings.getClientId())) { throw new OAuth2SettingsException("Client ID cannot be null or empty."); } if (settings.getClientSecret() != null) { tokenParams.put("client_secret", settings.getClientSecret()); } if (!Utils.isNullOrEmpty(settings.getScope())) { tokenParams.put("scope", settings.getScope()); } /* populate token request params */ tokenParams.put("client_id", settings.getClientId()); tokenParams.put("grant_type", "refresh_token"); tokenParams.put("refresh_token", settings.getRefreshToken()); for (Entry<String, String> entry : settings.getExtraTokenParams().entrySet()) { if (!tokenParams.containsKey(entry.getKey())) { tokenParams.put(entry.getKey(), entry.getValue()); } } }
/** * Use local LRU to evict data, and get <code> requestBytes </code> available space. * * @param requestBytes The data requested. * @return <code> true </code> if the space is granted, <code> false </code> if not. */ private boolean memoryEvictionLRU(long requestBytes) { Set<Integer> pinList; try { pinList = mMasterClient.worker_getPinIdList(); } catch (TException e) { LOG.error(e.getMessage()); pinList = new HashSet<Integer>(); } synchronized (mLatestBlockAccessTimeMs) { synchronized (mUsersPerLockedBlock) { while (mWorkerSpaceCounter.getAvailableBytes() < requestBytes) { long blockId = -1; long latestTimeMs = Long.MAX_VALUE; for (Entry<Long, Long> entry : mLatestBlockAccessTimeMs.entrySet()) { if (entry.getValue() < latestTimeMs && !pinList.contains(BlockInfo.computeInodeId(entry.getKey()))) { if (!mUsersPerLockedBlock.containsKey(entry.getKey())) { blockId = entry.getKey(); latestTimeMs = entry.getValue(); } } } if (blockId != -1) { freeBlock(blockId); } else { return false; } } } } return true; }
/** * Method to determine a comple argument based on the dependency declared by an argument. The * method calls a recursive method that searches in each line of the processed sentence for the * dependency declared and dependencies of each depency * * @param arg - The original argument * @param sentenceLines - all lines of the SRL file that compse the processed sentence */ private static void preDetermineFullArg(SemanticRelationArgument arg, String[] sentenceLines) { TreeMap<Integer, ArgumentTerm> parts = new TreeMap<Integer, ArgumentTerm>(); parts.put( arg.getArgLine(), new ArgumentTerm(arg.getShortArg(), arg.getShortArgLemma(), arg.getShortArgPosTag())); // call to recursive method parts.putAll(retrieveDependentArgs(parts, sentenceLines)); // build a string based on all dependencies found and populate the array of ArgumentTerms // The TreeMap guarantees that the words are read in order, since // the nodes are ordered by the line ID String fullArg = ""; int firstWordLine = arg.getArgLine(); for (Entry<Integer, ArgumentTerm> part : parts.entrySet()) { // Add ArgumentTerm to array of ArgumentTerm objects arg.getArgumentTerms().add(part.getValue()); fullArg += part.getValue().getWord() + " "; // check if the argument actually begins prior the argument lead if (part.getKey() < firstWordLine) { firstWordLine = part.getKey(); } } arg.setArgLine(firstWordLine); arg.setFullArg(fullArg); }
/** Saves the defaults and missing values. */ public void save() { if (!this.folder.exists()) { this.folder.mkdirs(); } if (!this.file.exists()) { try { this.file.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } this.config = YamlConfiguration.loadConfiguration(this.file); for (Entry<String, Object> en : this.defaults.entrySet()) { if (!this.config.contains(en.getKey())) { ConfigUtils.setObject(this.config, en.getKey(), en.getValue()); } } try { this.config.save(this.file); } catch (Exception e) { e.printStackTrace(); } }
/** * Sets the rendering settings associated to the image. * * @param viewedBy The value to set. */ void setViewedBy(Map viewedBy) { Map m = new LinkedHashMap(); if (viewedBy != null) { long id = MetadataViewerAgent.getUserDetails().getId(); Entry entry; Iterator i = viewedBy.entrySet().iterator(); ExperimenterData exp; while (i.hasNext()) { entry = (Entry) i.next(); exp = (ExperimenterData) entry.getKey(); if (exp.getId() == id) { m.put(exp, entry.getValue()); } } i = viewedBy.entrySet().iterator(); while (i.hasNext()) { entry = (Entry) i.next(); exp = (ExperimenterData) entry.getKey(); if (exp.getId() != id) { m.put(exp, entry.getValue()); } } } this.viewedBy = m; }
private ServletRequest prepareServletRequest( Object target, NativeWebRequest request, MethodParameter parameter) { String modelPrefixName = parameter.getParameterAnnotation(FormModel.class).value(); HttpServletRequest nativeRequest = (HttpServletRequest) request.getNativeRequest(); MultipartRequest multipartRequest = WebUtils.getNativeRequest(nativeRequest, MultipartRequest.class); MockHttpServletRequest mockRequest = null; if (multipartRequest != null) { MockMultipartHttpServletRequest mockMultipartRequest = new MockMultipartHttpServletRequest(); for (MultipartFile file : multipartRequest.getFileMap().values()) { mockMultipartRequest.addFile( new MultipartFileWrapper(getNewParameterName(file.getName(), modelPrefixName), file)); } mockRequest = mockMultipartRequest; } else { mockRequest = new MockHttpServletRequest(); } for (Entry<String, String> entry : getUriTemplateVariables(request).entrySet()) { String parameterName = entry.getKey(); String value = entry.getValue(); if (isFormModelAttribute(parameterName, modelPrefixName)) { mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value); } } for (Object parameterEntry : nativeRequest.getParameterMap().entrySet()) { Entry<String, String[]> entry = (Entry<String, String[]>) parameterEntry; String parameterName = entry.getKey(); String[] value = entry.getValue(); if (isFormModelAttribute(parameterName, modelPrefixName)) { mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value); } } return mockRequest; }