/** * Reads the file specified by filename and returns the file content as a string. * End of lines are replaced by a space. * * @param fileName the command line filename * @return the file content as a string. */ private List<String> readFile(String fileName) { List<String> result = Lists.newArrayList(); try (BufferedReader bufRead = Files.newBufferedReader(Paths.get(fileName), options.atFileCharset)) { String line; // Read through file one line at time. Print line # and line while ((line = bufRead.readLine()) != null) { // Allow empty lines and # comments in these at files if (line.length() > 0 && !line.trim().startsWith("#")) { result.add(line); } } } catch (IOException e) { throw new ParameterException("Could not read file " + fileName + ": " + e); } return result; }
/** * @return the field that's meant to receive all the parameters that are not options. * * @param arg the arg that we're about to add (only passed here to output a meaningful * error message). */ private List<?> getMainParameter(String arg) { if (mainParameter == null) { throw new ParameterException( "Was passed main parameter '" + arg + "' but no main parameter was defined in your arg class"); } List<?> result = (List<?>) mainParameter.get(mainParameterObject); if (result == null) { result = Lists.newArrayList(); if (!List.class.isAssignableFrom(mainParameter.getType())) { throw new ParameterException("Main parameter field " + mainParameter + " needs to be of type List, not " + mainParameter.getType()); } mainParameter.set(mainParameterObject, result); } if (firstTimeMainParameter) { result.clear(); firstTimeMainParameter = false; } return result; }
@Test public void dexPerClassFileWithDesugaring() throws Throwable { String testName = "dexPerClassFileWithDesugaring"; String testPackage = "lambdadesugaringnplus"; String mainClass = "LambdasWithStaticAndDefaultMethods"; Path inputJarFile = Paths.get(EXAMPLE_DIR, testPackage + JAR_EXTENSION); D8IncrementalTestRunner test = test(testName, testPackage, mainClass); test.withInterfaceMethodDesugaring(OffOrAuto.Auto); Resource mergedFromCompiledSeparately = test.mergeClassFiles(Lists.newArrayList( test.compileClassesSeparately(inputJarFile).values()), null); Resource mergedFromCompiledTogether = test.mergeClassFiles(Lists.newArrayList( test.compileClassesTogether(inputJarFile, null).values()), null); Assert.assertArrayEquals( readFromResource(mergedFromCompiledSeparately), readFromResource(mergedFromCompiledTogether)); }
/** * 签名算法 * * @param o 要参与签名的数据对象 * @return 签名 * @throws IllegalAccessException */ public static String getSign(Object o, String key) throws IllegalAccessException { List<String> list = Lists.newArrayList(); Class cls = o.getClass(); Field[] fields = cls.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); if (f.get(o) != null && f.get(o) != "") { list.add(f.getName() + "=" + f.get(o) + "&"); } } int size = list.size(); String[] arrayToSort = list.toArray(new String[size]); Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER); StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { sb.append(arrayToSort[i]); } String result = sb.toString(); result += "key=" + key; //log.log("Sign Before MD5:" + result); result = md5(result).toUpperCase(); //Util.log("Sign Result:" + result); return result; }
public static String getSign(Map<String, Object> map, String key) { List<String> list = Lists.newArrayList(); for (Map.Entry<String, Object> entry : map.entrySet()) { if (entry.getValue() != "") { list.add(entry.getKey() + "=" + entry.getValue() + "&"); } } int size = list.size(); String[] arrayToSort = list.toArray(new String[size]); Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER); StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { sb.append(arrayToSort[i]); } String result = sb.toString(); result += "key=" + key; //Util.log("Sign Before MD5:" + result); result = md5(result).toUpperCase(); //Util.log("Sign Result:" + result); return result; }
/** * 把数组所有元素按照字母顺序排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串 * <p> * 第一步: 在通知返回参数列表中,除去sign、sign_type两个参数外,凡是通知返回回来的参数皆是待验签的参数。 * 第二步:将剩下参数进行url_decode, 然后进行字典排序,组成字符串,得到待签名字符串 * * @param params 需要排序并参与字符拼接的参数组 * @return 拼接后字符串 * @Link 异步返回结果的验签:https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.OSyDs4&treeId=194&articleId=103296&docType=1#s1 */ public static String createStringUrl(Map<String, String> params) { List<String> keys = Lists.newArrayList(params.keySet()); Collections.sort(keys); StringBuffer prestr = new StringBuffer(); int keySize = keys.size(); int lastKeyLength = keySize - 1; for (int i = 0; i < keySize; i++) { String key = keys.get(i); /* if (*//*key.equals("sign") ||*//* key.equals("sign_type")) {//除去sign、sign_type两个参数 continue; }*/ String value = params.get(key); if (i == lastKeyLength) {//拼接时,不包括最后一个&字符 prestr.append(key).append("=").append(value); } else { prestr.append(key).append("=").append(value).append("&"); } } return prestr.toString(); }
@Test public void testLeftPush() throws IOException { OperatorNode<SequenceOperator> query = OperatorNode.create(SequenceOperator.FILTER, OperatorNode.create(SequenceOperator.JOIN, OperatorNode.create(SequenceOperator.SCAN, ImmutableList.of("left"), Lists.newArrayList()).putAnnotation("alias", "left"), OperatorNode.create(SequenceOperator.SCAN, ImmutableList.of("right"), Lists.newArrayList()).putAnnotation("alias", "right"), OperatorNode.create(ExpressionOperator.EQ, OperatorNode.create(ExpressionOperator.PROPREF, OperatorNode.create(ExpressionOperator.READ_RECORD, "left"), "id"), OperatorNode.create(ExpressionOperator.PROPREF, OperatorNode.create(ExpressionOperator.READ_RECORD, "right"), "id")) ), OperatorNode.create(ExpressionOperator.EQ, OperatorNode.create(ExpressionOperator.PROPREF, OperatorNode.create(ExpressionOperator.READ_RECORD, "left"), "id"), OperatorNode.create(ExpressionOperator.LITERAL, "1")) ); OperatorNode<SequenceOperator> transformed = new JoinFilterPushDown().visitSequenceOperator(query); Assert.assertEquals(transformed.getOperator(), SequenceOperator.JOIN); Assert.assertEquals(((OperatorNode) transformed.getArgument(0)).getOperator(), SequenceOperator.FILTER); Assert.assertEquals(((OperatorNode) transformed.getArgument(1)).getOperator(), SequenceOperator.SCAN); // TODO: validate the rest of the tree }
@Test public void testRightPush() throws IOException { OperatorNode<SequenceOperator> query = OperatorNode.create(SequenceOperator.FILTER, OperatorNode.create(SequenceOperator.JOIN, OperatorNode.create(SequenceOperator.SCAN, ImmutableList.of("left"), Lists.newArrayList()).putAnnotation("alias", "left"), OperatorNode.create(SequenceOperator.SCAN, ImmutableList.of("right"), Lists.newArrayList()).putAnnotation("alias", "right"), OperatorNode.create(ExpressionOperator.EQ, OperatorNode.create(ExpressionOperator.PROPREF, OperatorNode.create(ExpressionOperator.READ_RECORD, "left"), "id"), OperatorNode.create(ExpressionOperator.PROPREF, OperatorNode.create(ExpressionOperator.READ_RECORD, "right"), "id")) ), OperatorNode.create(ExpressionOperator.EQ, OperatorNode.create(ExpressionOperator.PROPREF, OperatorNode.create(ExpressionOperator.READ_RECORD, "right"), "id"), OperatorNode.create(ExpressionOperator.LITERAL, "1")) ); OperatorNode<SequenceOperator> transformed = new JoinFilterPushDown().visitSequenceOperator(query); Assert.assertEquals(transformed.getOperator(), SequenceOperator.JOIN); Assert.assertEquals(((OperatorNode) transformed.getArgument(0)).getOperator(), SequenceOperator.SCAN); Assert.assertEquals(((OperatorNode) transformed.getArgument(1)).getOperator(), SequenceOperator.FILTER); // TODO: validate the rest of the tree }
/** * For a given AutoScaling group logical id, get the public dns names associated with each instance. * * @param logicalId AutoScaling group logical id * @return List of public dns names */ public List<String> getPublicDnsForAutoScalingGroup(final String logicalId) { final List<String> instanceIds = Lists.newLinkedList(); final Optional<AutoScalingGroup> autoScalingGroup = describeAutoScalingGroup(logicalId); final List<String> publicDnsNames = Lists.newLinkedList(); if (autoScalingGroup.isPresent()) { autoScalingGroup.get() .getInstances().stream().forEach(instance -> instanceIds.add(instance.getInstanceId())); final DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest() .withInstanceIds(instanceIds); final DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(describeInstancesRequest); describeInstancesResult.getReservations().forEach(reservation -> reservation.getInstances().stream().forEach(instance -> publicDnsNames.add(instance.getPublicDnsName())) ); } return publicDnsNames; }
static SimpleFeatureType createSimpleFeatureType(String simpleFeatureTypeName) throws SchemaException { // list the attributes that constitute the feature type List<String> attributes = Lists.newArrayList( "Who:String:index=full", "What:java.lang.Long", // some types require full qualification (see DataUtilities docs) "When:Date", // a date-time field is optional, but can be indexed "*Where:Point:srid=4326", // the "*" denotes the default geometry (used for indexing) "Why:String", // you may have as many other attributes as you like... "Visibility:String" ); // create the bare simple-feature type String simpleFeatureTypeSchema = Joiner.on(",").join(attributes); SimpleFeatureType simpleFeatureType = SimpleFeatureTypes.createType(simpleFeatureTypeName, simpleFeatureTypeSchema); // use the user-data (hints) to specify which date-time field is meant to be indexed; // if you skip this step, your data will still be stored, it simply won't be indexed simpleFeatureType.getUserData().put(SimpleFeatureTypes.DEFAULT_DATE_KEY, "When"); return simpleFeatureType; }
static SimpleFeatureType createSimpleFeatureType(String simpleFeatureTypeName) throws SchemaException { // list the attributes that constitute the feature type List<String> attributes = Lists.newArrayList( "Who:String:index=full", "What:java.lang.Long", // some types require full qualification (see DataUtilities docs) "When:Date", // a date-time field is optional, but can be indexed "*Where:Point:srid=4326", // the "*" denotes the default geometry (used for indexing) "Why:String" // you may have as many other attributes as you like... ); // create the bare simple-feature type String simpleFeatureTypeSchema = Joiner.on(",").join(attributes); SimpleFeatureType simpleFeatureType = SimpleFeatureTypes.createType(simpleFeatureTypeName, simpleFeatureTypeSchema); // use the user-data (hints) to specify which date-time field is meant to be indexed; // if you skip this step, your data will still be stored, it simply won't be indexed simpleFeatureType.getUserData().put(SimpleFeatureTypes.DEFAULT_DATE_KEY, "When"); return simpleFeatureType; }
static SimpleFeatureType createSimpleFeatureType(String simpleFeatureTypeName) throws SchemaException { // list the attributes that constitute the feature type List<String> attributes = Lists.newArrayList( "Who:String", "What:java.lang.Long", // some types require full qualification (see DataUtilities docs) "When:Date", // a date-time field is optional, but can be indexed "*Where:Point:srid=4326", // the "*" denotes the default geometry (used for indexing) "Why:String" // you may have as many other attributes as you like... ); // create the bare simple-feature type String simpleFeatureTypeSchema = Joiner.on(",").join(attributes); SimpleFeatureType simpleFeatureType = DataUtilities.createType(simpleFeatureTypeName, simpleFeatureTypeSchema); return simpleFeatureType; }
@Nullable public List<GraylogAddress> getGraylogAddresses() { if(graylogAddresses == null) { return null; } String[] addresses; if (graylogAddresses.contains(",")) { addresses = graylogAddresses.split(","); } else { addresses = new String[]{graylogAddresses}; } List<GraylogAddress> result = Lists.newArrayList(); for (String address : addresses) { String[] parts = address.split(":"); result.add(new GraylogAddress(parts[0], Integer.parseInt(parts[1]))); } return result; }
/** * Reads the file specified by filename and returns the file content as a string. * End of lines are replaced by a space. * * @param fileName the command line filename * @return the file content as a string. */ private static List<String> readFile(String fileName) { List<String> result = Lists.newArrayList(); try { BufferedReader bufRead = new BufferedReader(new FileReader(fileName)); String line; // Read through file one line at time. Print line # and line while ((line = bufRead.readLine()) != null) { // Allow empty lines in these at files if (line.length() > 0) result.add(line); } bufRead.close(); } catch (IOException e) { throw new ParameterException("Could not read file " + fileName + ": " + e); } return result; }
/** * @return the number of options that were processed. */ private int processVariableArity(String[] args, int index, ParameterDescription pd) { Object arg = pd.getObject(); IVariableArity va; if (! (arg instanceof IVariableArity)) { va = DEFAULT_VARIABLE_ARITY; } else { va = (IVariableArity) arg; } List<String> currentArgs = Lists.newArrayList(); for (int j = index + 1; j < args.length; j++) { currentArgs.add(args[j]); } int arity = va.processVariableArity(pd.getParameter().names()[0], currentArgs.toArray(new String[0])); int result = processFixedArity(args, index, pd, List.class, arity); return result; }
/** * @return the field that's meant to receive all the parameters that are not options. * * @param arg the arg that we're about to add (only passed here to output a meaningful * error message). */ private List<?> getMainParameter(String arg) { if (m_mainParameter == null) { throw new ParameterException( "Was passed main parameter '" + arg + "' but no main parameter was defined"); } List<?> result = (List<?>) m_mainParameter.get(m_mainParameterObject); if (result == null) { result = Lists.newArrayList(); if (! List.class.isAssignableFrom(m_mainParameter.getType())) { throw new ParameterException("Main parameter field " + m_mainParameter + " needs to be of type List, not " + m_mainParameter.getType()); } m_mainParameter.set(m_mainParameterObject, result); } if (m_firstTimeMainParameter) { result.clear(); m_firstTimeMainParameter = false; } return result; }
private List<Authorization> findExpiredConsumers(final String repoOwner, final String repoPassword) throws IOException { OAuthService oAuthServiceRest = createOAuthServiceRest(repoOwner, repoPassword); List<Authorization> expiredConsumers = Lists.newArrayList(); // Ideally we should retrieve the Github Applications but no available REST service for that purpose at the moment. // There is a small risk of having Applications without Authorizations which are going to be missed in the current // logic but acceptable to keep code simple. When Github makes the Applications available via REST then we can update // our code. List<Authorization> authorizations = oAuthServiceRest.getAuthorizations(); for (Authorization authorization : authorizations) { if (super.isConsumerExpired(authorization.getApp().getName())) { expiredConsumers.add(authorization); } } return expiredConsumers; }
/** * @return list of expired consumers to be deleted from Bitbucket */ private List<BitbucketConsumer> findExpiredConsumers(final String repoOwner, final String repoPassword) { ConsumerRemoteRestpoint consumerRemoteRestpoint = createConsumerRemoteRestpoint(repoOwner, repoPassword); List<BitbucketConsumer> expiredConsumers = Lists.newArrayList(); List<BitbucketConsumer> consumers = consumerRemoteRestpoint.getConsumers(repoOwner); for (BitbucketConsumer consumer : consumers) { if (super.isConsumerExpired(consumer.getName())) { expiredConsumers.add(consumer); } } return expiredConsumers; }
/** * Filter resources, get all valid resources from all resources */ public static <T extends MPersistableEntity> List<T> filterResource(final MResource.TYPE type, List<T> resources) throws SqoopException { Collection<T> collection = Collections2.filter(resources, new Predicate<T>() { @Override public boolean apply(T input) { try { String name = String.valueOf(input.getPersistenceId()); checkPrivilege(getPrivilege(type, name, MPrivilege.ACTION.READ)); // add valid resource return true; } catch (Exception e) { //do not add into result if invalid resource return false; } } }); return Lists.newArrayList(collection); }
/** * Filter resources, get all valid resources from all resources */ public static List<MSubmission> filterSubmission(List<MSubmission> submissions) throws SqoopException { Collection<MSubmission> collection = Collections2.filter(submissions, new Predicate<MSubmission>() { @Override public boolean apply(MSubmission input) { try { String jobId = String.valueOf(input.getJobId()); checkPrivilege(getPrivilege(MResource.TYPE.JOB, jobId, MPrivilege.ACTION.READ)); // add valid submission return true; } catch (Exception e) { //do not add into result if invalid submission return false; } } }); return Lists.newArrayList(collection); }
@Test public void test() throws IOException { FileSystem fs = mock(FileSystem.class); String datasetPathStr = "/path/to/dataset"; String dataset1 = "datasetVersion1"; String dataset2 = "datasetVersion2"; Path datasetPath = new Path(datasetPathStr); Path globbedPath = new Path(datasetPathStr + "/*"); Path datasetVersion1 = new Path(datasetPathStr + "/" + dataset1); Path datasetVersion2 = new Path(datasetPathStr + "/" + dataset2); when(fs.globStatus(globbedPath)). thenReturn(new FileStatus[]{new FileStatus(0, true, 0, 0, 0, datasetVersion1), new FileStatus(0, true, 0, 0, 0, datasetVersion2)}); DatasetVersionFinder<StringDatasetVersion> versionFinder = new MockDatasetVersionFinder(fs, new Properties()); List<StringDatasetVersion> datasetVersions = Lists.newArrayList(versionFinder.findDatasetVersions(new MockDataset(datasetPath))); Assert.assertEquals(datasetVersions.size(), 2); Assert.assertEquals(datasetVersions.get(0).getVersion(), dataset1); Assert.assertEquals(datasetVersions.get(0).getPathsToDelete().iterator().next(), datasetVersion1); Assert.assertEquals(datasetVersions.get(1).getVersion(), dataset2); Assert.assertEquals(datasetVersions.get(1).getPathsToDelete().iterator().next(), datasetVersion2); }
/** * Based on the previously parsed files and the provided log files, this method determines which new files are to be * parsed. Generally, "Launch.log" will always be scanned. * * @param scannedFiles the {@link ScannedFiles} instance. * @param logFiles the Rocket League log files available. * @return a list of files to parse. */ protected List<File> getFilesToParse(final ScannedFiles scannedFiles, final File[] logFiles) { retainLogFiles(scannedFiles, logFiles); final List<File> filesToParse = Lists.newArrayList(); for (File file : logFiles) { if (file.getName().equals(DEFAULT_LOGFILE)) { filesToParse.add(file); } else if (!scannedFiles.getLogFiles().contains(file.getName())) { filesToParse.add(file); scannedFiles.getLogFiles().add(file.getName()); } } return filesToParse; }
@Test public void verifyIndexedFailedCount() throws Exception { //given ElasticDataPointer dataPointer = ElasticDataPointerBuilder.builder() .setAddress("http://localhost:9300/" + INDEX + "/" + TYPE) .build(); ProcessSynchronizer processSynchronizer = buildProcessSynchronizerMock(); IndexingComponent indexingComponent = mock(IndexingComponent.class); when(indexingComponent.indexData(eq(dataPointer), any(SearchHit[].class))) .thenReturn(Optional.of(new BulkResult(0, Lists.newArrayList("1", "2")))); //when IndexingProcess updatesProcess = IndexingProcessBuilder.builder() .setProcessSynchronizer(processSynchronizer) .setIndexingComponent(indexingComponent) .setDataPointer(dataPointer) .build(); updatesProcess.run(); //then verify(processSynchronizer, times(1)).incrementFailures(2); }
/** * Given a set of suites and the starting root package, it will print all the tests that are quarantined. * * @param args command line arguments * @throws Exception if something went wrong. */ public static void main(String[] args) throws Exception { QuarantineCommandLineArguments arguments = QuarantineCommandLineArguments.initialize(args); checkArguments(arguments); List<Class> classes = TestsFinder.getTestClassesOfPackage(arguments.suites(), arguments.suitesPackage()); System.out.println(String.format("Quarantined tests for suites %s in package %s", arguments.suites(), arguments.suitesPackage())); classes.stream() .forEach(test -> Lists.newArrayList(test.getMethods()) .stream() .filter(method -> method.isAnnotationPresent(Test.class) && !method.isAnnotationPresent(Ignore.class) && method.isAnnotationPresent(Quarantine.class) == true) .forEach(quarantinedTest-> { System.out.println(String.format("%s:%s", quarantinedTest.getDeclaringClass().getCanonicalName(), quarantinedTest.getName())); })); }
@Inject public TestSuiteRunner( @Named(PropertiesModule.TIMEOUT_IN_MINUTES) String timeOutInMinutes, TestRunnerConfig arguments, TestRunnerFactory testRunnerFactory, IntegrationFactory integrationFactory) { this.testRunnerFactory = Preconditions.checkNotNull(testRunnerFactory); this.suites = arguments.suites(); this.suitesPackage = arguments.suitesPackage(); this.timeoutInMinutes = Integer.valueOf(timeOutInMinutes); this.parallel = arguments.parallel(); this.executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(parallel)); this.totalTests = 0; this.quarantine = arguments.quarantine(); this.results = Collections.synchronizedList(Lists.newArrayList()); this.integrationFactory = Preconditions.checkNotNull(integrationFactory); }
/** * Create and add ports to map, return them as a list. * Supposedly this is called during the early scenario setup. The map is built, the biology is built * and the marketmap can be built. * * @param map the map to place ports in * @param mapmakerRandom the randomizer * @param marketFactory a function that returns the market associated with a location. We might refactor this at some point* * @param model * @param gasPriceMaker * @return the list of ports that have been built and added to the map. It can be ignored. */ @Override public List<Port> buildPorts( NauticalMap map, MersenneTwisterFast mapmakerRandom, Function<SeaTile, MarketMap> marketFactory, FishState model, GasPriceMaker gasPriceMaker) { try { portMap = reader.readFile( filePath,map,marketFactory, gasPriceMaker, model ); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("failed to read port file!"); } for(Port port : portMap.keySet()) map.addPort(port); return Lists.newArrayList(portMap.keySet()); }
@Override public void run() { Date timeNow = new Date(); List<Contest> runningContests = Lists.newArrayList(); try { jpaApi.withTransaction("default", true, () -> { runningContests.addAll(contestService.getRunningContestsWithScoreboardModule(timeNow)); return null; }); } catch (Throwable t) { throw new RuntimeException(t); } for (Contest contest : runningContests) { if (!ScoreboardUpdaterDispatcher.updaterExists(contest.getJid())) { ScoreboardUpdaterDispatcher.updateScoreboard(scheduler, executor, contest, contestService, contestScoreboardService, contestContestantService, programmingSubmissionService); } } }
@Override public ImmutableMap<SimulationInputs, Simulation> runExperiments( Set<SimulationInputs> simulationInputsSet, List<RandomTrial> randomTrials) { Map<SimulationInputs, List<SimulationDrmaaJobInfo>> jobsByInput = Maps .newHashMap(); List<String> allJobIds = Lists.newArrayList(); for (SimulationInputs experiment : simulationInputsSet) { List<SimulationDrmaaJobInfo> jobs = makeJobs(experiment, randomTrials); jobsByInput.put(experiment, jobs); allJobIds.addAll(submitJobs(jobs)); } try { session.synchronize(allJobIds, Session.TIMEOUT_WAIT_FOREVER, true); } catch (DrmaaException e) { throw new RuntimeException(e); } System.out.println("All jobs finished"); ImmutableMap.Builder<SimulationInputs, Simulation> ans = ImmutableMap .builder(); for (Map.Entry<SimulationInputs, List<SimulationDrmaaJobInfo>> entry : jobsByInput .entrySet()) { ans.put(entry.getKey(), mergeResults(entry.getValue(), 0)); } return ans.build(); }
private List<SimulationDrmaaJobInfo> splitInputJob(SimulationJob simulationJob) { List<SimulationDrmaaJobInfo> ans = Lists.newArrayList(); if (simulationJob.getRunHistoric()) { new SimulationDrmaaJobInfo(getSimJobName(), SimulationJob.newBuilder() .setSimulationInputs(simulationJob.getSimulationInputs()) .setRunHistoric(true).build()); } for (int i = 0; i < simulationJob.getRandomTrialCount(); i++) { ans.add(new SimulationDrmaaJobInfo(getSimJobName(), SimulationJob .newBuilder() .setSimulationInputs(simulationJob.getSimulationInputs()) .setRunHistoric(false) .addRandomTrial(simulationJob.getRandomTrial(i)) .setIndexWithinAllTrials(i + simulationJob.getIndexWithinAllTrials()) .build())); } return ans; }
private List<String> makeDefaultInstances() { List<String> ans = Lists.newArrayList(); String path = "kepLibInstances"; File dir = new File(path); if (!dir.isDirectory()) { System.out .println("Directory kepLibInstances not found, looking for files in working directory instead."); path = "."; } String fileName = ".*.csv"; System.out.println("path:" + path); System.out.println("fileName:" + fileName); // fileName = fileName.replaceAll("\\*", "\\.\\*"); // System.out.println("fileNameJavaregex:" + fileName); Collection<File> files = FileUtils.listFiles(new File(path), new RegexFileFilter(fileName), null); for (File file : files) { ans.add(file.getPath()); } System.out.println("Found " + files.size() + " files."); return ans; }
static SimpleFeatureType createSimpleFeatureType(String simpleFeatureTypeName) throws SchemaException { // list the attributes that constitute the feature type List<String> attributes = Lists.newArrayList( "Who:String:index=full", "What:java.lang.Long", // some types require full qualification (see DataUtilities docs) "When:Date", // a date-time field is optional, but can be indexed "*Where:Point:srid=4326", // the "*" denotes the default geometry (used for indexing) "Why:String" // you may have as many other attributes as you like... ); // create the bare simple-feature type String simpleFeatureTypeSchema = Joiner.on(",").join(attributes); SimpleFeatureType simpleFeatureType = SimpleFeatureTypes$.MODULE$.createType(simpleFeatureTypeName, simpleFeatureTypeSchema); // use the user-data (hints) to specify which date-time field is meant to be indexed; // if you skip this step, your data will still be stored, it simply won't be indexed simpleFeatureType.getUserData().put(Constants.SF_PROPERTY_START_TIME, "When"); return simpleFeatureType; }
/** * @return the number of options that were processed. */ private int processVariableArity(String[] args, int index, ParameterDescription pd) { Object arg = pd.getObject(); if (! (arg instanceof IVariableArity)) { throw new ParameterException("Arg class " + arg.getClass() + " should implement IVariableArity"); } IVariableArity va = (IVariableArity) arg; List<String> currentArgs = Lists.newArrayList(); for (int j = index + 1; j < args.length; j++) { currentArgs.add(args[j]); } int result = va.processVariableArity(pd.getParameter().names()[0], currentArgs.toArray(new String[0])); return result; }
/** * @return the field that's meant to receive all the parameters that are not options. * * @param arg the arg that we're about to add (only passed here to output a meaningful * error message). */ private List<?> getMainParameter(String arg) { if (m_mainParameterField == null) { throw new ParameterException( "Was passed main parameter '" + arg + "' but no main parameter was defined"); } try { List result = (List) m_mainParameterField.get(m_mainParameterObject); if (result == null) { result = Lists.newArrayList(); if (! List.class.isAssignableFrom(m_mainParameterField.getType())) { throw new ParameterException("Main parameter field " + m_mainParameterField + " needs to be of type List, not " + m_mainParameterField.getType()); } m_mainParameterField.set(m_mainParameterObject, result); } return result; } catch(IllegalAccessException ex) { throw new ParameterException("Couldn't access main parameter: " + ex.getMessage()); } }