List of usage examples for java.util TreeMap put
public V put(K key, V value)
From source file:no.met.jtimeseries.netcdf.NetcdfChartProvider.java
public void getCsv(PrintStream out, Iterable<String> variables) throws ParseException, IOException { Vector<NumberPhenomenon> data = getWantedPhenomena(variables); // header/*from w w w . j a v a2 s. c o m*/ out.print("# Time"); for (NumberPhenomenon p : data) out.print(",\t" + p.getPhenomenonName() + " (" + p.getPhenomenonUnit() + ")"); out.println(); TreeMap<Date, Double[]> displayData = new TreeMap<Date, Double[]>(); for (int i = 0; i < data.size(); i++) { for (NumberValueItem atom : data.get(i)) { Double[] d = displayData.get(atom.getTimeFrom()); if (d == null) { d = new Double[data.size()]; displayData.put(atom.getTimeFrom(), d); } d[i] = atom.getValue(); } } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); for (Entry<Date, Double[]> element : displayData.entrySet()) { out.print(format.format(element.getKey())); Double[] d = element.getValue(); for (int i = 0; i < d.length; i++) out.print(",\t" + d[i]); out.println(); } }
From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java
private UserRedirectRequiredException getRedirectForAuthorization(GoogleAuthCodeResourceDetails resource, AccessTokenRequest request) {/*from w w w. j av a 2 s . co m*/ // we don't have an authorization code yet. So first get that. TreeMap<String, String> requestParameters = new TreeMap<>(); requestParameters.put("response_type", "code"); // oauth2 spec, section 3 requestParameters.put("client_id", resource.getClientId()); // Client secret is not required in the initial authorization request String redirectUri = resource.getRedirectUri(request); if (redirectUri != null) { requestParameters.put("redirect_uri", redirectUri); } if (resource.isScoped()) { StringBuilder builder = new StringBuilder(); List<String> scope = resource.getScope(); if (scope != null) { Iterator<String> scopeIt = scope.iterator(); while (scopeIt.hasNext()) { builder.append(scopeIt.next()); if (scopeIt.hasNext()) { builder.append(' '); } } } requestParameters.put("scope", builder.toString()); } requestParameters.put("approval_prompt", resource.getApprovalPrompt()); if (StringUtils.isEmpty(resource.getLoginHint())) { requestParameters.put("login_hint", resource.getLoginHint()); } requestParameters.put("access_type", "online"); UserRedirectRequiredException redirectException = new UserRedirectRequiredException( resource.getUserAuthorizationUri(), requestParameters); String stateKey = stateKeyGenerator.generateKey(resource); redirectException.setStateKey(stateKey); request.setStateKey(stateKey); redirectException.setStateToPreserve(redirectUri); request.setPreservedState(redirectUri); return redirectException; }
From source file:org.loklak.data.DAO.java
private static ArrayList<String> getBestPeers(Collection<String> peers) { ArrayList<String> best = new ArrayList<>(); if (peers == null || peers.size() == 0) return best; // first check if any of the given peers has unknown latency TreeMap<Long, String> o = new TreeMap<>(); for (String peer : peers) { if (peerLatency.containsKey(peer)) { o.put(peerLatency.get(peer) * 1000 + best.size(), peer); } else {// ww w .j av a 2s . co m best.add(peer); } } best.addAll(o.values()); return best; }
From source file:hydrograph.ui.engine.ui.converter.impl.OutputFileExcelUiConverter.java
@Override protected Map<String, String> getRuntimeProperties() { LOGGER.debug("Fetching runtime properties for -", componentName); TreeMap<String, String> runtimeMap = null; TypeProperties typeProperties = ((ExcelFile) typeBaseComponent).getRuntimeProperties(); if (typeProperties != null) { runtimeMap = new TreeMap<>(); for (Property runtimeProperty : typeProperties.getProperty()) { runtimeMap.put(runtimeProperty.getName(), runtimeProperty.getValue()); }/* w w w .j a v a 2 s.c o m*/ } return runtimeMap; }
From source file:com.terremark.impl.TerremarkClientImpl.java
/** * Internal method to retrieve the server supported API versions and time. If client specified a specific API * version, it is checked to see if the server supports it. {@link java.lang.IllegalArgumentException} is thrown if * the client API version is not supported by the server. If client did not specify a version, the latest version in * the server provided list is chosen for the client. The time difference between the server and the client is * computed and cached.//from ww w . j a va 2 s. com * * @param clientVersion Client specified API version. Can be null. * @throws TerremarkException If error occurs while retrieving the server time and/or API versions. */ private void initialize(final Version clientVersion) throws TerremarkException { final SupportedVersions versions = getSupportedVersions(); final TreeMap<Date, String> versionDates = new TreeMap<Date, String>(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); for (final VersionInfo vi : versions.getVersionInfos()) { try { versionDates.put(sdf.parse(vi.getVersion()), vi.getVersion()); } catch (final ParseException ex) { throw new InternalServerException( "While validating the API version, got invalid version from server: " + vi.getVersion(), ex); } } String clientVersionStr = clientVersion == null ? null : clientVersion.toString(); if (clientVersionStr == null) { clientVersionStr = versionDates.lastEntry().getValue(); } else { if (!versionDates.values().contains(clientVersionStr)) { throw new IllegalArgumentException("Invalid API version: " + clientVersionStr); } } final Date serverDateTime = getTime().getCurrentServerTime().toGregorianCalendar().getTime(); versionAndDateProvider.setVersion(clientVersionStr); versionAndDateProvider.calculateClockSkew(serverDateTime); }
From source file:com.ngdata.hbaseindexer.mr.HBaseIndexerMapper.java
@Override protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); Utils.getLogConfigFile(context.getConfiguration()); if (LOG.isTraceEnabled()) { LOG.trace("CWD is {}", new File(".").getCanonicalPath()); TreeMap map = new TreeMap(); for (Map.Entry<String, String> entry : context.getConfiguration()) { map.put(entry.getKey(), entry.getValue()); }// w w w. j a v a 2 s . c om LOG.trace("Mapper configuration:\n{}", Joiner.on("\n").join(map.entrySet())); } String indexName = context.getConfiguration().get(INDEX_NAME_CONF_KEY); String indexerComponentFactory = context.getConfiguration().get(INDEX_COMPONENT_FACTORY_KEY); String indexConfiguration = context.getConfiguration().get(INDEX_CONFIGURATION_CONF_KEY); String tableName = context.getConfiguration().get(TABLE_NAME_CONF_KEY); if (indexName == null) { throw new IllegalStateException("No configuration value supplied for " + INDEX_NAME_CONF_KEY); } if (indexConfiguration == null) { throw new IllegalStateException("No configuration value supplied for " + INDEX_CONFIGURATION_CONF_KEY); } if (tableName == null) { throw new IllegalStateException("No configuration value supplied for " + TABLE_NAME_CONF_KEY); } Map<String, String> indexConnectionParams = getIndexConnectionParams(context.getConfiguration()); IndexerComponentFactory factory = IndexerComponentFactoryUtil.getComponentFactory(indexerComponentFactory, new ByteArrayInputStream(indexConfiguration.getBytes(Charsets.UTF_8)), indexConnectionParams); IndexerConf indexerConf = factory.createIndexerConf(); String morphlineFile = context.getConfiguration().get(MorphlineResultToSolrMapper.MORPHLINE_FILE_PARAM); Map<String, String> params = indexerConf.getGlobalParams(); if (morphlineFile != null) { params.put(MorphlineResultToSolrMapper.MORPHLINE_FILE_PARAM, morphlineFile); } String morphlineId = context.getConfiguration().get(MorphlineResultToSolrMapper.MORPHLINE_ID_PARAM); if (morphlineId != null) { params.put(MorphlineResultToSolrMapper.MORPHLINE_ID_PARAM, morphlineId); } for (Map.Entry<String, String> entry : context.getConfiguration()) { if (entry.getKey().startsWith(MorphlineResultToSolrMapper.MORPHLINE_VARIABLE_PARAM + ".")) { params.put(entry.getKey(), entry.getValue()); } if (entry.getKey().startsWith(MorphlineResultToSolrMapper.MORPHLINE_FIELD_PARAM + ".")) { params.put(entry.getKey(), entry.getValue()); } } ResultToSolrMapper mapper = factory.createMapper(indexName); // TODO This would be better-placed in the top-level job setup -- however, there isn't currently any // infrastructure to handle converting an in-memory model into XML (we can only interpret an // XML doc into the internal model), so we need to do this here for now if (indexerConf.getRowReadMode() != RowReadMode.NEVER) { LOG.warn("Changing row read mode from " + indexerConf.getRowReadMode() + " to " + RowReadMode.NEVER); indexerConf = new IndexerConfBuilder(indexerConf).rowReadMode(RowReadMode.NEVER).build(); } indexerConf.setGlobalParams(params); try { indexer = createIndexer(indexName, context, indexerConf, tableName, mapper, indexConnectionParams); } catch (SharderException e) { throw new RuntimeException(e); } }
From source file:io.mapzone.arena.analytics.graph.SingleSourceNodeGraphFunction.java
@Override public void createContents(final MdToolkit tk, final Composite parent, final Graph graph) { try {/*from w ww . ja v a 2 s . co m*/ super.createContents(tk, parent, graph); final FeaturePropertySelectorUI sourcePropertiesUI = new FeaturePropertySelectorUI(tk, parent, prop -> { this.selectedSourcePropertyDescriptor = prop; EventManager.instance().publish(new GraphFunctionConfigurationChangedEvent( SingleSourceNodeGraphFunction.this, "sourcePropertyDescriptor", prop)); }); final FeatureSourceSelectorUI sourceFeaturesUI = new FeatureSourceSelectorUI(tk, parent, fs -> { this.selectedSourceFeatureSource = fs; EventManager.instance().publish(new GraphFunctionConfigurationChangedEvent( SingleSourceNodeGraphFunction.this, "sourceFeatureSource", fs)); sourcePropertiesUI.setFeatureSource(fs); }); final TreeMap<String, EdgeFunction> edgeFunctions = Maps.newTreeMap(); for (Class<EdgeFunction> cl : availableFunctions) { try { EdgeFunction function = cl.newInstance(); function.init(this); edgeFunctions.put(function.title(), function); } catch (Exception e) { throw new RuntimeException(e); } } final Composite edgeFunctionContainer = tk.createComposite(parent, SWT.NONE); edgeFunctionContainer.setLayout(FormLayoutFactory.defaults().create()); final ComboViewer edgeFunctionsUI = new ComboViewer(parent, SWT.SINGLE | SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY); edgeFunctionsUI.setContentProvider(new ArrayContentProvider()); edgeFunctionsUI.setInput(edgeFunctions.keySet()); edgeFunctionsUI.addSelectionChangedListener(ev -> { String selected = SelectionAdapter.on(ev.getSelection()).first(String.class).get(); EdgeFunction function = edgeFunctions.get(selected); // FormDataFactory.on( edgeFunctionContainer ).top( // edgeFunctionsUI.getCombo(), 4 ) // .height( function.preferredHeight() ).left( COLUMN_2 ).right( 100 // ); FormDataFactory.on(edgeFunctionContainer).height(function.preferredHeight()); UIUtils.disposeChildren(edgeFunctionContainer); // create panel function.createContents(tk, edgeFunctionContainer, selectedSourceFeatureSource); // FormDataFactory.on( edgeFunctionContainer ).fill(); // resize also the top container // XXX depends on the parent structure ((FormData) parent.getParent().getParent().getLayoutData()).height = preferredHeight() + function.preferredHeight(); parent.getParent().getParent().getParent().layout(); this.selectedEdgeFunction = function; }); final Label selectSourceTableLabel = tk.createLabel(parent, i18n.get("selectSourceTable"), SWT.NONE); FormDataFactory.on(selectSourceTableLabel).top(15).left(1); FormDataFactory.on(sourceFeaturesUI.control()).top(selectSourceTableLabel, 2).left(1); final Label selectSourcePropertiesLabel = tk.createLabel(parent, i18n.get("selectSourceProperties"), SWT.NONE); FormDataFactory.on(selectSourcePropertiesLabel).top(sourceFeaturesUI.control(), 4).left(COLUMN_2); FormDataFactory.on(sourcePropertiesUI.control()).top(selectSourcePropertiesLabel, 2).left(COLUMN_2); final Label selectEdgeFunctionLabel = tk.createLabel(parent, i18n.get("selectEdgeFunction"), SWT.NONE); FormDataFactory.on(selectEdgeFunctionLabel).top(sourcePropertiesUI.control(), 6).left(1); FormDataFactory.on(edgeFunctionsUI.getCombo()).top(selectEdgeFunctionLabel, 2).left(1); FormDataFactory.on(edgeFunctionContainer).fill().top(edgeFunctionsUI.getCombo(), 4).left(COLUMN_2); // event listener EventManager.instance().subscribe(this, ifType(EdgeFunctionConfigurationDoneEvent.class, ev -> ev.status.get() == Boolean.TRUE && ev.getSource().equals(selectedEdgeFunction))); EventManager.instance().subscribe(this, ifType(GraphFunctionConfigurationChangedEvent.class, ev -> ev.getSource().equals(SingleSourceNodeGraphFunction.this))); } catch (Exception e) { StatusDispatcher.handleError("", e); } }
From source file:com.github.cmisbox.remote.CMISRepository.java
public TreeMap<String, String> getChildrenFolders(String id) { TreeMap<String, String> res = new TreeMap<String, String>(); Iterator<QueryResult> i = this.session .query("select * from cmis:folder where in_folder('" + id + "')", true).iterator(); while (i.hasNext()) { QueryResult qr = i.next();//w ww. ja v a2 s .c o m res.put(qr.getPropertyById(PropertyIds.NAME).getFirstValue().toString(), qr.getPropertyById(PropertyIds.OBJECT_ID).getFirstValue().toString()); } return res; }
From source file:com.pindroid.client.PinboardApi.java
/** * Performs an api call to Pinboard's http based api methods. * /*from w w w . j a v a 2 s . c om*/ * @param url URL of the api method to call. * @param params Extra parameters included in the api call, as specified by different methods. * @param account The account being synced. * @param context The current application context. * @return A String containing the response from the server. * @throws IOException If a server error was encountered. * @throws AuthenticationException If an authentication error was encountered. * @throws TooManyRequestsException * @throws PinboardException */ private static InputStream PinboardApiCall(String url, TreeMap<String, String> params, Account account, Context context) throws IOException, AuthenticationException, TooManyRequestsException, PinboardException { final AccountManager am = AccountManager.get(context); if (account == null) throw new AuthenticationException(); final String username = account.name; String authtoken = "00000000000000000000"; // need to provide a sane default value, since a token that is too short causes a 500 error instead of 401 try { String tempAuthtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true); if (tempAuthtoken != null) authtoken = tempAuthtoken; } catch (Exception e) { e.printStackTrace(); throw new AuthenticationException("Error getting auth token"); } params.put("auth_token", username + ":" + authtoken); final Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME); builder.authority(PINBOARD_AUTHORITY); builder.appendEncodedPath(url); for (String key : params.keySet()) { builder.appendQueryParameter(key, params.get(key)); } String apiCallUrl = builder.build().toString(); Log.d("apiCallUrl", apiCallUrl); final HttpGet post = new HttpGet(apiCallUrl); post.setHeader("User-Agent", "PinDroid"); post.setHeader("Accept-Encoding", "gzip"); final DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient(); final HttpResponse resp = client.execute(post); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { final HttpEntity entity = resp.getEntity(); InputStream instream = entity.getContent(); final Header encoding = entity.getContentEncoding(); if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } return instream; } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { am.invalidateAuthToken(Constants.AUTHTOKEN_TYPE, authtoken); try { authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true); } catch (Exception e) { e.printStackTrace(); throw new AuthenticationException("Invalid auth token"); } throw new AuthenticationException(); } else if (statusCode == Constants.HTTP_STATUS_TOO_MANY_REQUESTS) { throw new TooManyRequestsException(300); } else if (statusCode == HttpStatus.SC_REQUEST_URI_TOO_LONG) { throw new PinboardException(); } else { throw new IOException(); } }
From source file:org.powertac.producer.ProducerTest.java
@Before public void setUp() { customerRepo.recycle();/*from w ww.j av a 2s . c om*/ brokerRepo.recycle(); tariffRepo.recycle(); tariffSubscriptionRepo.recycle(); randomSeedRepo.recycle(); timeslotRepo.recycle(); weatherReportRepo.recycle(); weatherReportRepo.runOnce(); reset(mockAccounting); reset(mockServerProperties); // create a Competition, needed for initialization comp = Competition.newInstance("producer-test"); broker1 = new Broker("Joe"); // now = new DateTime(2009, 10, 10, 0, 0, 0, 0, // DateTimeZone.UTC).toInstant(); now = comp.getSimulationBaseTime(); timeService.setCurrentTime(now); timeService.setClockParameters(now.toInstant().getMillis(), 720l, 60 * 60 * 1000); exp = now.plus(TimeService.WEEK * 10); defaultTariffSpec = new TariffSpecification(broker1, PowerType.PRODUCTION).withExpiration(exp) .addRate(new Rate().withValue(0.5)); defaultTariff = new Tariff(defaultTariffSpec); defaultTariff.init(); defaultTariff.setState(Tariff.State.OFFERED); tariffRepo.setDefaultTariff(defaultTariffSpec); when(mockTariffMarket.getDefaultTariff(PowerType.FOSSIL_PRODUCTION)).thenReturn(defaultTariff); when(mockTariffMarket.getDefaultTariff(PowerType.RUN_OF_RIVER_PRODUCTION)).thenReturn(defaultTariff); when(mockTariffMarket.getDefaultTariff(PowerType.SOLAR_PRODUCTION)).thenReturn(defaultTariff); when(mockTariffMarket.getDefaultTariff(PowerType.WIND_PRODUCTION)).thenReturn(defaultTariff); accountingArgs = new ArrayList<Object[]>(); // mock the AccountingService, capture args doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); accountingArgs.add(args); return null; } }).when(mockAccounting).addTariffTransaction(isA(TariffTransaction.Type.class), isA(Tariff.class), isA(CustomerInfo.class), anyInt(), anyDouble(), anyDouble()); // Set up serverProperties mock config = new Configurator(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); config.configureSingleton(args[0]); return null; } }).when(mockServerProperties).configureMe(anyObject()); TreeMap<String, String> map = new TreeMap<String, String>(); map.put("common.competition.expectedTimeslotCount", "1440"); Configuration mapConfig = new MapConfiguration(map); config.setConfiguration(mapConfig); config.configureSingleton(comp); }