public static String encodeUrl(Parameters parameters) { if (parameters == null) { return ""; } StringBuilder sb = new StringBuilder(); boolean first = true; int size = parameters.size(); for (int loc = 0; loc < size; loc++) { if (first) { first = false; } else { sb.append("&"); } String _key = parameters.getKey(loc); String _value = parameters.getValue(_key); if (_value == null) { // Log.i("encodeUrl", "key:" + _key + " 's value is null"); } else { // Log.i("encodeUrl", URLEncoder.encode(parameters.getKey(loc)) // + "=" + URLEncoder.encode(parameters.getValue(loc))); sb.append( URLEncoder.encode(parameters.getKey(loc)) + "=" + URLEncoder.encode(encodeBase64(parameters.getValue(loc).getBytes()))); } } return sb.toString(); }
/** {@inheritDoc} */ @Override public void init(FilterConfig config) throws ServletException { // rewrap datasources in GlobalNamingResources with ResourceLink in // context.xml System.setProperty( Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.REWRAP_DATASOURCES.getCode(), Boolean.TRUE.toString()); if (Parameters.getParameter(Parameter.SQL_TRANSFORM_PATTERN) == null) { // regexp pour agréger les paramètres bindés dans les critères // de requêtes SQL tels que "in (?, ?, ?, ?)" et ainsi pour éviter // que ces requêtes ayant un nombre variable de paramètres soient // considérées comme différentes ; // de fait cela agrège aussi les values des inserts System.setProperty( Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.SQL_TRANSFORM_PATTERN.getCode(), "\\([\\?, ]+\\)"); } if (Parameters.getParameter(Parameter.DISPLAYED_COUNTERS) == null) { // disable jsp counter to fix // https://github.com/javamelody/liferay-javamelody/issues/5, // the jsp counter does not display anything anyway. // In consequence, jsf, job, ejb, jpa, spring, guice are also // disabled. System.setProperty( Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.DISPLAYED_COUNTERS.getCode(), "http,sql,error,log"); } super.init(config); LOG.debug("JavaMelody is monitoring Liferay"); }
/** Only called reflectively. Do not use programmatically. */ public Parameterized(Class<?> klass) throws Throwable { super(klass, NO_RUNNERS); Parameters parameters = getParametersMethod().getAnnotation(Parameters.class); fRunners = Collections.unmodifiableList( createRunnersForParameters(allParameters(), parameters.name())); }
public RtspClient() { mCSeq = 0; mTmpParameters = new Parameters(); mTmpParameters.port = 1935; mTmpParameters.path = "/"; mTmpParameters.transport = TRANSPORT_UDP; mAuthorization = null; mCallback = null; mMainHandler = new Handler(Looper.getMainLooper()); mState = STATE_STOPPED; final Semaphore signal = new Semaphore(0); new HandlerThread("RtspClient") { @Override protected void onLooperPrepared() { mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == RtpThread.WHAT_THREAD_END_UNEXCEPTION) { if (mCallback != null) { mCallback.onRtspUpdate(RtpThread.WHAT_THREAD_END_UNEXCEPTION, null); } else { stopStream(); } } } }; signal.release(); } }.start(); signal.acquireUninterruptibly(); }
public void init() throws Exception { Parameters params = getParameters(); if (params.getRaw().isEmpty()) { throw new IllegalArgumentException("no FastA file was given as input!"); } fastaReader = new FastaReader(params.getRaw().toArray()[0].toString()); }
public RemapInfo doRemap(int index) { int remappedIndex; if (index < params.getArgsSizeOnStack()) { ParameterInfo info = params.getParameterByDeclarationSlot(index); StackValue remapped = remapValues[index]; if (info.isSkipped || remapped == null) { return new RemapInfo(info); } if (info.isRemapped()) { return new RemapInfo(remapped, info, REMAPPED); } else { remappedIndex = ((StackValue.Local) remapped).index; } } else { remappedIndex = actualParamsSize - params.getArgsSizeOnStack() + index; // captured params not used directly in this inlined method, they used in // closure } return new RemapInfo( StackValue.local(remappedIndex + additionalShift, AsmTypes.OBJECT_TYPE), null, SHIFT); }
/** * Initializes this class with all {@link Parameters} as generated by the given {@link * ISimulationParametersInitializer}s.<br> * This method will adopt parameters if there are any already.<br> * If you don't want that, call {@link * SimulationParameters#init(ISimulationParametersInitializer...)} or destroy existing Parameters * first.<br> * Be aware that if this method is called several times (after first calling the destroy method), * the old {@link Parameters} are gone. All registered {@link IParameterChangeListener}s are then * informed that the {@link Parameters} are new ones. * * @param parameterInitializers the concrete {@link ISimulationParametersInitializer}s that * initialize the {@link SimulationParametersProvider} */ public static void initOrAdopt(ISimulationParametersInitializer... parameterInitializers) { // either create a new parameters object or use the old one instead Parameters parameters = null; if (SimulationParameters.myParamProvider != null) { parameters = SimulationParameters.myParamProvider.getParameters(); SimulationParameters.LOG.info("Adopted existing simulation parameters."); } else { parameters = new Parameters(); } // merge all parameters as returned by the given simulation parameter initializers into one // object for (ISimulationParametersInitializer parameterInitializer : parameterInitializers) { parameters.addAllParameters(parameterInitializer.initializeSimulationParameters()); } // initialize the simulation parameters provider SimulationParameters.myParamProvider = new SimulationParametersProvider(parameters); SimulationParameters.myParamProvider.getParameters(); // refresh parameters of all available parameter listeners synchronized (SimulationParameters.parameterChangeListeners) { for (IParameterChangeListener parameterChangeListener : SimulationParameters.parameterChangeListeners) { SimulationParameters.LOG.debug( "Refreshing parameter listener '" + parameterChangeListener.getClass().getSimpleName() + "'."); parameterChangeListener.refreshParameters(); } } }
@Override public void run( Parameters params, TopNResultBuilder resultBuilder, DimValSelector dimValSelector) { boolean hasDimValSelector = (dimValSelector != null); final int cardinality = params.getCardinality(); int numProcessed = 0; while (numProcessed < cardinality) { final int numToProcess; int maxNumToProcess = Math.min(params.getNumValuesPerPass(), cardinality - numProcessed); DimValSelector theDimValSelector; if (!hasDimValSelector) { numToProcess = maxNumToProcess; theDimValSelector = makeDimValSelector(params, numProcessed, numToProcess); } else { // skip invalid, calculate length to have enough valid value to process or hit the end. numToProcess = computeNewLength(dimValSelector, numProcessed, maxNumToProcess); theDimValSelector = updateDimValSelector(dimValSelector, numProcessed, numToProcess); } DimValAggregateStore aggregatesStore = makeDimValAggregateStore(params); scanAndAggregate(params, theDimValSelector, aggregatesStore, numProcessed); updateResults(params, theDimValSelector, aggregatesStore, resultBuilder); closeAggregators(aggregatesStore); numProcessed += numToProcess; params.getCursor().reset(); } }
protected Map<String, Object> toUrlParams() { Parameters additional = null; if (includeRowCount) { additional = new Parameters(); additional.setParam(Constants.INCLUDE_COUNT, true); } return queryParams.toUrlParams(additional); }
private JdbcWrapper(Counter sqlCounter) { super(); assert sqlCounter != null; this.sqlCounter = sqlCounter; // servletContext reste null pour l'instant this.servletContext = null; connectionInformationsEnabled = Parameters.isSystemActionsEnabled() && !Parameters.isNoDatabase(); }
private void requestToken() { final Parameters params = new Parameters(); params.put("oauth_callback", callback); final String method = "GET"; OAuth.signOAuth( host, pathRequest, method, https, params, null, null, consumerKey, consumerSecret); final HttpResponse response = Network.getRequest(getUrlPrefix() + host + pathRequest, params); if (Network.isSuccess(response)) { final String line = Network.getResponseData(response); int status = STATUS_ERROR; if (StringUtils.isNotBlank(line)) { assert line != null; final MatcherWrapper paramsMatcher1 = new MatcherWrapper(paramsPattern1, line); if (paramsMatcher1.find()) { OAtoken = paramsMatcher1.group(1); } final MatcherWrapper paramsMatcher2 = new MatcherWrapper(paramsPattern2, line); if (paramsMatcher2.find()) { OAtokenSecret = paramsMatcher2.group(1); } if (StringUtils.isNotBlank(OAtoken) && StringUtils.isNotBlank(OAtokenSecret)) { setTempTokens(OAtoken, OAtokenSecret); try { final Parameters paramsBrowser = new Parameters(); paramsBrowser.put("oauth_token", OAtoken); final String encodedParams = EntityUtils.toString(new UrlEncodedFormEntity(paramsBrowser)); startActivity( new Intent( Intent.ACTION_VIEW, Uri.parse(getUrlPrefix() + host + pathAuthorize + "?" + encodedParams))); status = STATUS_SUCCESS; } catch (ParseException e) { Log.e("OAuthAuthorizationActivity.requestToken", e); } catch (IOException e) { Log.e("OAuthAuthorizationActivity.requestToken", e); } } } requestTokenHandler.sendEmptyMessage(status); } else { final String extErrMsg = getExtendedErrorMsg(response); if (StringUtils.isNotBlank(extErrMsg)) { final Message msg = requestTokenHandler.obtainMessage(STATUS_ERROR_EXT_MSG, extErrMsg); requestTokenHandler.sendMessage(msg); } else { requestTokenHandler.sendEmptyMessage(STATUS_ERROR); } } }
static JRobin createInstance(String application, String name, String requestName) throws IOException { final File dir = Parameters.getStorageDirectory(application); final File rrdFile = new File(dir, name + ".rrd"); final int step = Parameters.getResolutionSeconds(); try { return new JRobin(application, name, rrdFile, step, requestName); } catch (final RrdException e) { throw createIOException(e); } }
/** * General main for all the prototoype generators Arguments: 0: Filename with the training data * set to be condensed. 1: Filename wich will contain the test data set * * @param args Arguments of the main function. */ public static void main(String[] args) { Parameters.setUse("AVG", ""); Parameters.assertBasicArgs(args); PrototypeSet training = PrototypeGenerationAlgorithm.readPrototypeSet(args[0]); PrototypeSet test = PrototypeGenerationAlgorithm.readPrototypeSet(args[1]); AVG generator = new AVG(training); PrototypeSet resultingSet = generator.execute(); int accuracy1NN = KNN.classficationAccuracy(resultingSet, test); generator.showResultsOfAccuracy(Parameters.getFileName(), accuracy1NN, test); }
@Override public void initialize(Parameters params) throws ResourceInitializationException { super.initialize(params); try { model = Model.load(((ResourceReader) params.get(Constants.MODEL)).getReader()); } catch (IOException e) { throw new ResourceInitializationException("Failed to load SVM model.", e); } labelIndeces = new int[labels.size()]; labelIndeces = model.getLabels(); representer = (TextRepresenter) params.get(Constants.REPRESENTER); }
public String getRenderParametersUrlTemplate() { final RenderWebServiceUrls urls = new RenderWebServiceUrls( parameters.baseDataUrl, parameters.getBaseOwner(), parameters.getBaseProject()); final String currentStackUrlString = urls.getStackUrlString(parameters.getBaseStack()); final String relativeStackUrlString = currentStackUrlString.substring(parameters.baseDataUrl.length()); return RenderableCanvasIdPairs.TEMPLATE_BASE_DATA_URL_TOKEN + relativeStackUrlString + "/tile/" + RenderableCanvasIdPairs.TEMPLATE_ID_TOKEN + "/render-parameters"; }
void initServletContext(ServletContext context) { assert context != null; this.servletContext = context; final String serverInfo = servletContext.getServerInfo(); jboss = serverInfo.contains("JBoss") || serverInfo.contains("WildFly"); glassfish = serverInfo.contains("GlassFish") || serverInfo.contains("Sun Java System Application Server"); weblogic = serverInfo.contains("WebLogic"); jonas = System.getProperty("jonas.name") != null; connectionInformationsEnabled = Parameters.isSystemActionsEnabled() && !Parameters.isNoDatabase(); }
/** Itt inicializáljuk a beviteli eszközt. */ @Override public void onCreate() { super.onCreate(); mContext = getApplicationContext(); float drawingAreaHeight = ShorthandUtils.dpToPx(mContext, 250.0f); mRecognizer = new Recognizer(mContext, drawingAreaHeight / 3); mRecognizer.loadDefaultCharMapping(); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); Parameters.initInstance(sharedPrefs); mParameters = Parameters.getInstance(); sharedPrefs.registerOnSharedPreferenceChangeListener(mParameters); }
protected MMObjectNode getGroupOrUserNode(Parameters a) { MMObjectNode groupOrUser = getNode(a.getString(PARAMETER_GROUPORUSER)); if (groupOrUser == null) throw new IllegalArgumentException( "There is no node with id '" + a.get(PARAMETER_GROUPORUSER) + "'"); MMObjectBuilder parent = groupOrUser.getBuilder(); MMObjectBuilder userBuilder = Authenticate.getInstance().getUserProvider().getUserBuilder(); if (!(parent instanceof Groups || userBuilder.getClass().isInstance(parent))) { throw new IllegalArgumentException( "Node '" + a.get(PARAMETER_GROUPORUSER) + "' does not represent a group or a user"); } return groupOrUser; }
/** Test default package versions. */ public static void testDefaultPackageVersion() throws Exception { Builder a = new Builder(); a.addClasspath(new File("bin")); a.setProperty("Bundle-Version", "1.2.3"); a.setProperty("Export-Package", "test.refer"); Jar jar = a.build(); Manifest m = jar.getManifest(); Parameters exports = Processor.parseHeader(m.getMainAttributes().getValue(Constants.EXPORT_PACKAGE), null); Map<String, String> attrs = exports.get("test.refer"); assertNotNull(attrs); assertEquals("1.2.3", attrs.get("version")); }
public void run(String[] args) { Parameters params = validateAndParseParams(args, Parameters.class); File testData = new File(params.getCensusData()); File dictOutFile = new File(params.getDict()); CmdLineUtil.checkInputFile("Name data", testData); CmdLineUtil.checkOutputFile("Dictionary file", dictOutFile); FileInputStream sampleDataIn = CmdLineUtil.openInFile(testData); ObjectStream<StringList> sampleStream = new NameFinderCensus90NameStream(sampleDataIn, Charset.forName(params.getEncoding())); Dictionary mDictionary; try { System.out.println("Creating Dictionary..."); mDictionary = createDictionary(sampleStream); } catch (IOException e) { throw new TerminateToolException( -1, "IO error while reading training data or indexing data: " + e.getMessage(), e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry this can fail.. } } System.out.println("Saving Dictionary..."); OutputStream out = null; try { out = new FileOutputStream(dictOutFile); mDictionary.serialize(out); } catch (IOException e) { throw new TerminateToolException( -1, "IO error while writing dictionary file: " + e.getMessage(), e); } finally { if (out != null) try { out.close(); } catch (IOException e) { // file might be damaged throw new TerminateToolException( -1, "Attention: Failed to correctly write dictionary:" + e.getMessage(), e); } } }
public LambdaInfo getLambdaIfExists(AbstractInsnNode insnNode) { if (insnNode.getOpcode() == Opcodes.ALOAD) { int varIndex = ((VarInsnNode) insnNode).var; if (varIndex < parameters.totalSize()) { return parameters.get(varIndex).getLambda(); } } else if (insnNode instanceof FieldInsnNode) { FieldInsnNode fieldInsnNode = (FieldInsnNode) insnNode; if (fieldInsnNode.name.startsWith("$$$")) { return findCapturedField(fieldInsnNode, nodeRemapper).getLambda(); } } return null; }
private Object[] paramsFromSource() { if (sourceClassUndefined()) return new Object[] {}; Class<?> sourceClass = parametersAnnotation.source(); return fillResultWithAllParamProviderMethods(sourceClass); }
/** * Retrieve the input attributes from the Active Directory for the given search query * * <p>Method getAttributes. * * @param searchBase String * @return List<User> * @throws NamingException */ private final List<User> getAttributes(String searchBase) throws NamingException { LOGGER.info(">> getAttributes()"); NamingEnumeration<SearchResult> results = localInitialLdapContext.search(searchBase, searchFilter, searchctls); List<User> users = new ArrayList<User>(); User user = null; while (results.hasMoreElements()) { user = new User(); SearchResult searchResult = results.next(); Attributes attrs = searchResult.getAttributes(); if (attrs != null && attrs.size() != 0) { Attribute attribute = null; String[] retrieveAttributes = parameters.getRetrieveAttributes(); String[] attributesValues = new String[retrieveAttributes.length]; for (int i = 0; i < retrieveAttributes.length; i++) { attribute = attrs.get(retrieveAttributes[i]); if (attribute != null && attribute.get() != null) { if (!isNullOrEmpty(attribute.get().toString())) { attributesValues[i] = attribute.get().toString(); } } } user.setAttributeValues(attributesValues); } users.add(user); } LOGGER.info("<< getAttributes()"); return users; }
/** Method setSearchParameters. */ private void setSearchParameters() { LOGGER.info(">> setSearchParameters()"); // Search controls and setting up the returning attributes searchctls = new SearchControls(); searchctls.setReturningAttributes(parameters.getRetrieveAttributes()); // Set the search scope. You can change this as according your // structure. // Remember this value has effect on performance. // Example: setting the scope to Subtree. searchctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Set the search filter. Change as according by changing the values in // properties class. searchFilter = new StringBuilder("(&(objectClass=") .append(Properties.FILTER_OBJECT_CLASS) .append(")(objectCategory=") .append(Properties.FILTER_OBJECT_CATEGORY) .append("))") .toString(); LOGGER.info("<< setSearchParameters"); }
public void actionPerformed(ActionEvent e) { String defaultHost = Parameters.getParameter("telnet.defaultHost", "localhost"); String hostname = JOptionPane.showInputDialog(Edit.getFrame(), "Hostname:", defaultHost); if (hostname != null) { Edit.openFile("telnet://" + hostname); } }
@Test public void testWhiteSpacesInSingleSegment() throws URISyntaxException { ITextUnit tu1 = new TextUnit("tu1"); TextContainer source = tu1.getSource(); source.append(new Segment("seg1", new TextFragment(" Text "))); assertEquals(1, source.getSegments().count()); assertEquals(1, source.count()); assertEquals(" Text ", source.get(0).toString()); assertTrue(source.get(0).isSegment()); params.setSegmentationStrategy(SegmStrategy.DEEPEN_EXISTING); segStep.handleTextUnit(new Event(EventType.TEXT_UNIT, tu1)); assertEquals(1, source.getSegments().count()); assertEquals(3, source.count()); assertEquals(" ", source.get(0).toString()); assertFalse(source.get(0).isSegment()); assertEquals("Text", source.get(1).toString()); assertTrue(source.get(1).isSegment()); assertEquals(" ", source.get(2).toString()); assertFalse(source.get(2).isSegment()); }
@Override public void render(Parameters blockParameters, Writer w, RenderHints hints) throws FrameworkException { log.debug("Error rendering " + blockParameters); switch (getType()) { case BODY: try { decorateIntro(hints, w, "error"); w.write("<h1>" + error.status); w.write(": "); CharTransformer escape = new Xml(Xml.ESCAPE); w.write(escape.transform(error.exception.getMessage())); w.write(" "); w.write(escape.transform(url)); w.write("</h1>"); w.write("<pre>"); HttpServletRequest request = blockParameters.get(Parameter.REQUEST); error.getErrorReport(w, request, escape); w.write("</pre>"); decorateOutro(hints, w); } catch (IOException eio) { throw new FrameworkException(eio.getMessage(), eio); } break; default: } }
/** * Do not calculate the current Parameters' performance again, use remembered scores instead. * * @param current * @return Parameters */ public Parameters getAlreadyTestedParameters(Parameters current) { Parameters alreadyTested = null; for (Parameters iterParams : getTestedParameters().toArray(new Parameters[] {})) { if (current.equals(iterParams)) alreadyTested = iterParams; } return alreadyTested; }
static Map<String, DataSource> getJndiDataSources() throws NamingException { final Map<String, DataSource> dataSources = new LinkedHashMap<String, DataSource>(2); final String datasourcesParameter = Parameters.getParameter(Parameter.DATASOURCES); if (datasourcesParameter == null) { dataSources.putAll(getJndiDataSourcesAt("java:comp/env/jdbc")); // pour jboss sans jboss-env.xml ou sans resource-ref dans web.xml : dataSources.putAll(getJndiDataSourcesAt("java:/jdbc")); // pour JavaEE 6 : // (voir par exemple // http://smokeandice.blogspot.com/2009/12/datasourcedefinition-hidden-gem-from.html) dataSources.putAll(getJndiDataSourcesAt("java:global/jdbc")); // pour WebLogic 10 et WebSphere 7, cf issue 68 dataSources.putAll(getJndiDataSourcesAt("jdbc")); } else if (datasourcesParameter.trim().length() != 0) { // NOPMD final InitialContext initialContext = new InitialContext(); for (final String datasource : datasourcesParameter.split(",")) { final String jndiName = datasource.trim(); // ici, on n'ajoute pas java:/comp/env // et on suppose qu'il n'en faut pas ou que cela a été ajouté dans le paramétrage final DataSource dataSource = (DataSource) initialContext.lookup(jndiName); dataSources.put(jndiName, dataSource); } initialContext.close(); } return Collections.unmodifiableMap(dataSources); }
/** Prints the classifier. */ public void print() { System.out.print(" Act: " + action + " Conf: "); for (int i = 0; i < rep.length; i++) { rep[i].print(); } if (parameters != null) parameters.print(); } // end print