edu.emory.mathcs.backport.java.util.Arrays Java Examples

The following examples show how to use edu.emory.mathcs.backport.java.util.Arrays. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DependencyDumper.java    From depends with MIT License 6 votes vote down vote up
private final void outputDeps(String projectName, String outputDir, String[] outputFormat) {
@SuppressWarnings("unchecked")
List<String> formatList = Arrays.asList(outputFormat);
AbstractFormatDependencyDumper[] builders = new AbstractFormatDependencyDumper[] {
 	new DetailTextFormatDependencyDumper(dependencyMatrix,projectName,outputDir),
 	new XmlFormatDependencyDumper(dependencyMatrix,projectName,outputDir),
 	new JsonFormatDependencyDumper(dependencyMatrix,projectName,outputDir),
 	new ExcelXlsFormatDependencyDumper(dependencyMatrix,projectName,outputDir),
 	new ExcelXlsxFormatDependencyDumper(dependencyMatrix,projectName,outputDir),
 	new DotFormatDependencyDumper(dependencyMatrix,projectName,outputDir),
 	new DotFullnameDependencyDumper(dependencyMatrix,projectName,outputDir),
 	new PlantUmlFormatDependencyDumper(dependencyMatrix,projectName,outputDir),
 	new BriefPlantUmlFormatDependencyDumper(dependencyMatrix,projectName,outputDir)
};
for (AbstractFormatDependencyDumper builder:builders) {
	if (formatList.contains(builder.getFormatName())){
		builder.output();
	}
}
  }
 
Example #2
Source File: TemplateTypeCache.java    From Cynthia with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void remove(UUID[] uuids) {
	for (UUID uuid : uuids) {
		EhcacheHandler.getInstance().delete(EhcacheHandler.FOREVER_CACHE,uuid.getValue());
	}
	
	List<UUID> deleteTempalteList = Arrays.asList(uuids);
	
	List<TemplateType> allTemplateTypes = getAll();
	Iterator<TemplateType> it = allTemplateTypes.iterator();
	while (it.hasNext()) {
		if (deleteTempalteList.contains(it.next().getId())) {
			it.remove();
		}
	}
	
	setAll(allTemplateTypes);
}
 
Example #3
Source File: TemplateCache.java    From Cynthia with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void remove(UUID[] uuids) {
	for (UUID uuid : uuids) {
		EhcacheHandler.getInstance().delete(EhcacheHandler.FOREVER_CACHE,uuid.getValue());
	}

	List<UUID> deleteTempalteList = Arrays.asList(uuids);

	List<Template> allTempaltes = getAll();
	Iterator<Template> it = allTempaltes.iterator();
	while (it.hasNext()) {
		if (deleteTempalteList.contains(it.next().getId())) {
			it.remove();
		}
	}

	setAll(allTempaltes);
}
 
Example #4
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void DoesNotAddRulesDirParameter_IfEmptyString() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();
    final ArrayList<Long> capturedTimeouts = new ArrayList<Long>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            capturedTimeouts.add((long) invocation.getArguments()[3]);
            return 0;
        }
    };

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);

    this.config.setRulesDir("");
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file" }));

    Command theCommand = capturedCommands.get(0);
    assertFalse(theCommand.toCommandLine().contains("--rules-dir"));
}
 
Example #5
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void DoesNotAddRulesDirParameter_IfNull() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();
    final ArrayList<Long> capturedTimeouts = new ArrayList<Long>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            capturedTimeouts.add((long) invocation.getArguments()[3]);
            return 0;
        }
    };

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);

    this.config.setRulesDir(null);
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file" }));

    Command theCommand = capturedCommands.get(0);
    assertFalse(theCommand.toCommandLine().contains("--rules-dir"));
}
 
Example #6
Source File: InfoSubscription.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @return
 */
private List<String> getProperty(String key) {
    List<String> infoSubscriptions = new ArrayList<String>();
    List<PropertyImpl> properties = propertyManager.findProperties(ident, null, null, null, key);

    if (properties.size() > 1) {
        Log.error("more than one property found, something went wrong, deleting them and starting over.");
        for (PropertyImpl prop : properties) {
            propertyManager.deleteProperty(prop);
        }

    } else if (properties.size() == 0l) {
        PropertyImpl p = propertyManager.createPropertyInstance(ident, null, null, null, key, null, null, null, null);
        propertyManager.saveProperty(p);
        properties = propertyManager.findProperties(ident, null, null, null, key);
    }
    String value = properties.get(0).getTextValue();

    if (value != null && !value.equals("")) {
        String[] subscriptions = properties.get(0).getTextValue().split(SEPARATOR);
        infoSubscriptions.addAll(Arrays.asList(subscriptions));
    }

    return infoSubscriptions;
}
 
Example #7
Source File: PropertyManagerEBL.java    From olat with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<String> getCourseCalendarSubscriptionProperty(final PropertyParameterObject propertyParameterObject) {
    List<String> infoSubscriptions = new ArrayList<String>();
    List<PropertyImpl> properties = findProperties(propertyParameterObject);

    if (properties.size() > 1) {
        Log.error("more than one property found, something went wrong, deleting them and starting over.");
        for (PropertyImpl prop : properties) {
            propertyManager.deleteProperty(prop);
        }

    } else if (properties.size() == 0l) {
        createAndSaveProperty(propertyParameterObject);
        properties = findProperties(propertyParameterObject);
    }
    String value = properties.get(0).getTextValue();

    if (value != null && !value.equals("")) {
        String[] subscriptions = properties.get(0).getTextValue().split(SEPARATOR);
        infoSubscriptions.addAll(Arrays.asList(subscriptions));
    }

    return infoSubscriptions;
}
 
Example #8
Source File: PropertyManagerEBL.java    From olat with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<String> getCourseCalendarSubscriptionProperty(final PropertyParameterObject propertyParameterObject) {
    List<String> infoSubscriptions = new ArrayList<String>();
    List<PropertyImpl> properties = findProperties(propertyParameterObject);

    if (properties.size() > 1) {
        Log.error("more than one property found, something went wrong, deleting them and starting over.");
        for (PropertyImpl prop : properties) {
            propertyManager.deleteProperty(prop);
        }

    } else if (properties.size() == 0l) {
        createAndSaveProperty(propertyParameterObject);
        properties = findProperties(propertyParameterObject);
    }
    String value = properties.get(0).getTextValue();

    if (value != null && !value.equals("")) {
        String[] subscriptions = properties.get(0).getTextValue().split(SEPARATOR);
        infoSubscriptions.addAll(Arrays.asList(subscriptions));
    }

    return infoSubscriptions;
}
 
Example #9
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void executesCommandWithCorrectArgumentsAndTimeouts() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();
    final ArrayList<Long> capturedTimeouts = new ArrayList<Long>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            capturedTimeouts.add((long) invocation.getArguments()[3]);
            return 0;
        }
    };

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file", "path/to/another" }));

    assertEquals(1, capturedCommands.size());

    Command theCommand = capturedCommands.get(0);
    long theTimeout = capturedTimeouts.get(0);

    assertEquals("node path/to/tslint --format json --rules-dir path/to/rules --out path/to/temp --config path/to/config path/to/file path/to/another", theCommand.toCommandLine());
    // Expect one timeout period per file processed
    assertEquals(2 * 40000, theTimeout);
}
 
Example #10
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void usesTypeCheckParameter_ifConfigSaysToUseTypeCheck() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            return 0;
        }
    };

    this.config.setPathToTsConfig("path/to/tsconfig.json");
    this.config.setShouldPerformTypeCheck(true);

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file", "path/to/another" }));

    assertEquals(1, capturedCommands.size());

    Command theCommand = capturedCommands.get(0);

    assertEquals("node path/to/tslint --format json --rules-dir path/to/rules --out path/to/temp --config path/to/config --project path/to/tsconfig.json --type-check", theCommand.toCommandLine());
}
 
Example #11
Source File: PgpPipeTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters(name = "{index} - {0} - {1}")
public static Collection<Object[]> data() {
	// List of the parameters for pipes is as follows:
	// action, secretkey, password, publickey, senders, recipients
	return Arrays.asList(new Object[][]{
			{"Sign then Verify", "success",
					new String[]{"sign", sender[2], sender[1], sender[4], sender[0], recipient[0]},
					new String[]{"verify", recipient[2], recipient[1], recipient[4], sender[0], recipient[0]}},
			{"Encrypt then Decrypt", "success",
					new String[]{"encrypt", null, null, recipient[3], null, recipient[0]},
					new String[]{"dEcryPt", recipient[2], recipient[1], null, null, null}},
			{"Sign then Decrypt", "success",
					new String[]{"sign", sender[2], sender[1], sender[4], sender[0], recipient[0]},
					new String[]{"decrypt", recipient[2], recipient[1], null, null, null}},
			{"Verify Someone Signed", "success",
					new String[]{"sign", sender[2], sender[1], sender[4], sender[0], recipient[0]},
					new String[]{"verify", recipient[2], recipient[1], recipient[4], null, recipient[0]}},
			{"Encrypt then Verify", "org.bouncycastle.openpgp.PGPException",
					new String[]{"encrypt", null, null, recipient[3], null, recipient[0]},
					new String[]{"verify", recipient[2], recipient[1], recipient[4], sender[0], recipient[0]}},
			{"Sign wrong params", "nl.nn.adapterframework.configuration.ConfigurationException",
					new String[]{"sign", null, null, recipient[3], null, recipient[0]},
					new String[]{"decrypt", recipient[2], recipient[1], null, null, null}},
			{"Null action", "nl.nn.adapterframework.configuration.ConfigurationException",
					new String[]{null, null, null, recipient[3], null, recipient[0]},
					new String[]{"decrypt", recipient[2], recipient[1], null, null, null}},
			{"Non-existing action", "nl.nn.adapterframework.configuration.ConfigurationException",
					new String[]{"non-existing action", null, null, recipient[3], null, recipient[0]},
					new String[]{"decrypt", recipient[2], recipient[1], null, null, null}},
			{"Wrong password", "org.bouncycastle.openpgp.PGPException",
					new String[]{"encrypt", null, null, recipient[3], null, recipient[0]},
					new String[]{"decrypt", recipient[2], "wrong password :/", null, null, null}},
			{"Decrypt Plaintext", "org.bouncycastle.openpgp.PGPException",
					new String[]{"decrypt", recipient[2], recipient[1], null, null, null},
					new String[]{"decrypt", recipient[2], recipient[1], null, null, null}},
	});
}
 
Example #12
Source File: CommandStart.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() {
	if (values.size() > 0) {
		projectDir = values.get(0);
	}
	execute(Arrays.asList(new String[]{"mvn", "-X", "-f", projectDir + "/pom.xml", "compile", "exec:exec", "-DmainClass=org.minnal.Bootstrap"}));
}
 
Example #13
Source File: MediaWikiAPIPageExtractor.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
private boolean extractTopicsFromString(String str, TopicMap t){
    
    String[] titles = str.split(",");
    List<String> titleList = Arrays.asList(titles);
    
    for(String title : titleList){
        try {
            parsePage(title,t);
        } catch (Exception e) {
            log(e);
        }
    }
    
    return true;
}
 
Example #14
Source File: GalleryListParserTest.java    From EhViewer with Apache License 2.0 5 votes vote down vote up
@ParameterizedRobolectricTestRunner.Parameters(name = "{index}-{0}")
public static List data() {
  return Arrays.asList(new Object[][] {
      { E_MINIMAL },
      { E_MINIMAL_PLUS },
      { E_COMPAT },
      { E_EXTENDED },
      { E_THUMBNAIL },
      { EX_MINIMAL },
      { EX_MINIMAL_PLUS },
      { EX_COMPAT },
      { EX_EXTENDED },
      { EX_THUMBNAIL },
  });
}
 
Example #15
Source File: SubscriptionValidationDAO.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private void populateApiPolicyList(List<APIPolicy> apiPolicies, ResultSet resultSet)
        throws SQLException {

    Map<Integer, APIPolicy> temp = new ConcurrentHashMap<>();
    if (apiPolicies != null && resultSet != null) {
        while (resultSet.next()) {
            int policyId = resultSet.getInt("POLICY_ID");
            APIPolicy apiPolicy = temp.get(policyId);
            if (apiPolicy == null) {
                apiPolicy = new APIPolicy();
                apiPolicy.setId(policyId);
                apiPolicy.setName(resultSet.getString("NAME"));
                apiPolicy.setQuotaType(resultSet.getString("DEFAULT_QUOTA_TYPE"));
                apiPolicy.setTenantId(resultSet.getInt("TENANT_ID"));
                apiPolicy.setApplicableLevel(resultSet.getString("APPLICABLE_LEVEL"));
                apiPolicies.add(apiPolicy);
            }
            APIPolicyConditionGroup apiPolicyConditionGroup = new APIPolicyConditionGroup();
            int conditionGroup = resultSet.getInt("CONDITION_GROUP_ID");
            apiPolicyConditionGroup.setConditionGroupId(conditionGroup);
            apiPolicyConditionGroup.setQuotaType(resultSet.getString("QUOTA_TYPE"));
            apiPolicyConditionGroup.setPolicyId(policyId);
            ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
            ConditionGroupDTO conditionGroupDTO = null;
            try {
                conditionGroupDTO = apiMgtDAO.createConditionGroupDTO(conditionGroup);
            } catch (APIManagementException e) {
                log.error("Error while processing api policies for policyId : " + policyId, e);
            }
            ConditionDTO[] conditionDTOS = conditionGroupDTO.getConditions();
            apiPolicyConditionGroup.setConditionDTOS(Arrays.asList(conditionDTOS));
            apiPolicy.addConditionGroup(apiPolicyConditionGroup);
            temp.put(policyId, apiPolicy);
        }
    }
}
 
Example #16
Source File: AttachmentResultTest.java    From jxapi with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAttachment() {
	AttachmentResult a = new AttachmentResult(RESPONSE_MESSAGE, statements, attachments);
	assertNotNull(a);
	assertEquals(Arrays.toString(attachment), Arrays.toString(a.getAttachment().get(HASH).getAttachment()));
	assertEquals(type, a.getAttachment().get(HASH).getType());
}
 
Example #17
Source File: Types.java    From systemds with Apache License 2.0 5 votes vote down vote up
public static FileFormat safeValueOf(String fmt) {
	try {
		return valueOf(fmt.toUpperCase());
	}
	catch(Exception ex) {
		throw new DMLRuntimeException("Unknown file format: "+fmt
			+ " (valid values: "+Arrays.toString(FileFormat.values())+")");
	}
}
 
Example #18
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 5 votes vote down vote up
@Test
public void doesNotSendFileListToTsLint_ifConfigSaysToUseProjectFile() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();
    final ArrayList<Long> capturedTimeouts = new ArrayList<Long>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            capturedTimeouts.add((long) invocation.getArguments()[3]);
            return 0;
        }
    };

    this.config.setPathToTsConfig("path/to/tsconfig.json");

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file", "path/to/another" }));

    assertEquals(1, capturedCommands.size());

    Command theCommand = capturedCommands.get(0);
    long theTimeout = capturedTimeouts.get(0);

    assertEquals("node path/to/tslint --format json --rules-dir path/to/rules --out path/to/temp --config path/to/config --project path/to/tsconfig.json", theCommand.toCommandLine());
    // Timeout should be just what we specified since we're not batching

    assertEquals(40000, theTimeout);
}
 
Example #19
Source File: GameManagingUtilsTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testEagerSmellDoesNotTriggerIfProductionsMethodsAreLessThanThreshold() throws IOException {
    // This has 2 production calls instead of 4 {@link
    // TestSmellDetectorProducer.EAGER_TEST_THRESHOLD}
    String testCode = "" + "import org.junit.*;" + "\n" + "import static org.junit.Assert.*;" + "\n"
            + "import static org.hamcrest.MatcherAssert.assertThat;" + "\n"
            + "import static org.hamcrest.Matchers.*;" + "\n" + "public class TestLift {" + "\n"
            + "    @Test(timeout = 4000)" + "\n" + "    public void test() throws Throwable {" + "\n"
            + "        Lift l = new Lift(50);" + "\n"
            // 1 Production Method call
            + "        l.goUp();" + "\n" //
            // 2 Production Method call
            + "        l.goUp();" + "\n" //
            // Calls inside the assertions (or inside other calls?) are not counted
            + "        assertEquals(50, l.getTopFloor());" + "\n" + "    }" + "\n" + "}";

    org.codedefenders.game.Test newTest = createMockedTest(testCode);
    GameClass cut = createMockedCUT();

    // configure the mock
    gameManagingUtils.detectTestSmells(newTest, cut);

    // Verify that the store method was called
    ArgumentCaptor<TestFile> argument = ArgumentCaptor.forClass(TestFile.class);
    Mockito.verify(mockedTestSmellDAO).storeSmell(Mockito.any(), argument.capture());
    // We expect no smells
    Set<String> noSmellsExpected = new HashSet<>(Arrays.asList(new String[] {}));
    // Collect smells
    Set<String> actualSmells = new HashSet<>();
    for (AbstractSmell smell : argument.getValue().getTestSmells()) {
        if (smell.getHasSmell()) {
            actualSmells.add(smell.getSmellName());
        }
    }

    Assert.assertEquals(noSmellsExpected, actualSmells);
}
 
Example #20
Source File: GameManagingUtilsTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testSmellGood() throws IOException {
    String testCode = "" + "import org.junit.*;" + "\n" + "import static org.junit.Assert.*;" + "\n"
            + "import static org.hamcrest.MatcherAssert.assertThat;" + "\n"
            + "import static org.hamcrest.Matchers.*;" + "\n" + "public class TestLift {" + "\n"
            + "    @Test(timeout = 4000)" + "\n" + "    public void test() throws Throwable {" + "\n"
            + "        Lift l = new Lift(50);" + "\n" + "        assertEquals(50, l.getTopFloor());" + "\n"
            + "    }" + "\n" + "}";

    org.codedefenders.game.Test newTest = createMockedTest(testCode);
    GameClass cut = createMockedCUT();

    // configure the mock
    gameManagingUtils.detectTestSmells(newTest, cut);

    // Verify that the store method was called once and capture the
    // parameter passed to the invocation
    ArgumentCaptor<TestFile> argument = ArgumentCaptor.forClass(TestFile.class);
    Mockito.verify(mockedTestSmellDAO).storeSmell(Mockito.any(), argument.capture());

    // TODO Probably some smart argument matcher might be needed
    // TODO Matching by string is britlle, maybe match by "class/type"?
    Set<String> expectedSmells = new HashSet<>(Arrays.asList(new String[] {}));
    // Collect smells
    Set<String> actualSmells = new HashSet<>();
    for (AbstractSmell smell : argument.getValue().getTestSmells()) {
        if (smell.getHasSmell()) {
            actualSmells.add(smell.getSmellName());
        }
    }

    Assert.assertEquals(expectedSmells, actualSmells);
}
 
Example #21
Source File: FuzzyPhoneNumberHelperTest.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private static <E> Set<E> setOf(E... values) {
  //noinspection unchecked
  return new HashSet<>(Arrays.asList(values));
}
 
Example #22
Source File: CellerySignedJWTGenerator.java    From cellery-security with Apache License 2.0 4 votes vote down vote up
private List<String> getScopes(TokenValidationContext validationContext) {

        String[] scopes = validationContext.getTokenInfo().getScopes();
        return scopes != null ? Arrays.asList(scopes) : Collections.emptyList();
    }
 
Example #23
Source File: CommandGenerateTests.java    From minnal with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() {
    execute(Arrays.asList(new String[]{"mvn", "-X", "-f", projectDir + "/pom.xml", "compile", "exec:exec", "-Dexec.executable=java",
            "-DmainClass=org.minnal.generator.test.TestsGenerator", "-Dexec.args=-cp %classpath org.minnal.generator.test.TestsGenerator "
            + projectDir + " " + baseTestClass + " " + Joiner.on(",").join(packages)}));
}
 
Example #24
Source File: MinnalGenerator.java    From minnal with Apache License 2.0 4 votes vote down vote up
protected void process(String[] args) {
    try {
        logger.trace("Parsing the args {}", (Object) args);
        jc.parse(args);
    } catch (ParameterException e) {
        logger.debug("Failed while parsing the args " + Arrays.toString(args), e);
        showHelp(jc.getParsedCommand());
        return;
    }

    if (this.args.isTrace()) {
        LogManager.getRootLogger().setLevel(Level.TRACE);
    } else if (this.args.isDebug()) {
        LogManager.getRootLogger().setLevel(Level.DEBUG);
    }

    String command = jc.getParsedCommand();
    if (Strings.isNullOrEmpty(command)) {
        logger.debug("Command is missing. Please specify a command");
        showHelp(command);
        return;
    }

    if (this.args.isHelp()) {
        showHelp(command);
        return;
    }

    if (command.equalsIgnoreCase("new")) {
        logger.debug("Running command new");
        run(commandNew);
    } else if (command.equalsIgnoreCase("add")) {
        logger.debug("Running command add");
        run(commandAdd);
    } else if (command.equalsIgnoreCase("start")) {
        logger.debug("Running command start");
        run(commandStart);
    } else if (command.equalsIgnoreCase("generate-model")) {
        logger.debug("Running command generate-model");
        run(commandGenerateModel);
    } else if (command.equalsIgnoreCase("generate-tests")) {
        logger.debug("Running command generate-tests");
        run(commandGenerateTests);
    }
}
 
Example #25
Source File: AbstractWordExtractor.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean _extractTopicsFrom(String str, TopicMap t) throws Exception {
    String[] strArray = str.split("\\r?\\n");
    return handleWordList(Arrays.asList(strArray), t);
}
 
Example #26
Source File: Main.java    From depends with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static void executeCommand(DependsCommand app) throws ParameterException {
	String lang = app.getLang();
	String inputDir = app.getSrc();
	String[] includeDir = app.getIncludes();
	String outputName = app.getOutputName();
	String outputDir = app.getOutputDir();
	String[] outputFormat = app.getFormat();

	inputDir = FileUtil.uniqFilePath(inputDir);
	boolean supportImplLink = false;
	if (app.getLang().equals("cpp") || app.getLang().equals("python")) supportImplLink = true;
	
	if (app.isAutoInclude()) {
		FolderCollector includePathCollector = new FolderCollector();
		List<String> additionalIncludePaths = includePathCollector.getFolders(inputDir);
		additionalIncludePaths.addAll(Arrays.asList(includeDir));
		includeDir = additionalIncludePaths.toArray(new String[] {});
	}
		
	AbstractLangProcessor langProcessor = LangProcessorRegistration.getRegistry().getProcessorOf(lang);
	if (langProcessor == null) {
		System.err.println("Not support this language: " + lang);
		return;
	}

	if ( app.isDv8map()) {
		DV8MappingFileBuilder dv8MapfileBuilder = new DV8MappingFileBuilder(langProcessor.supportedRelations());
		dv8MapfileBuilder.create(outputDir+File.separator+"depends-dv8map.mapping");
	}
	
	long startTime = System.currentTimeMillis();
	
	FilenameWritter filenameWritter = new EmptyFilenameWritter();
	if (!StringUtils.isEmpty(app.getNamePathPattern())) {
		if (app.getNamePathPattern().equals("dot")||
				app.getNamePathPattern().equals(".")) {
			filenameWritter = new DotPathFilenameWritter();
		}else if (app.getNamePathPattern().equals("unix")||
				app.getNamePathPattern().equals("/")) {
			filenameWritter = new UnixPathFilenameWritter();
		}else if (app.getNamePathPattern().equals("windows")||
				app.getNamePathPattern().equals("\\")) {
			filenameWritter = new WindowsPathFilenameWritter();
		}else{
			throw new ParameterException("Unknown name pattern paremater:" + app.getNamePathPattern());
		}
	}

	
	/* by default use file dependency generator */
	DependencyGenerator dependencyGenerator = new FileDependencyGenerator();
	if (!StringUtils.isEmpty(app.getGranularity())) {
		/* method parameter means use method generator */
		if (app.getGranularity().equals("method"))
				dependencyGenerator = new FunctionDependencyGenerator();
		else if (app.getGranularity().equals("file"))
			/*no action*/;
		else if (app.getGranularity().startsWith("L"))
			/*no action*/;
		else
			throw new ParameterException("Unknown granularity parameter:" + app.getGranularity());
	}
	
	if (app.isStripLeadingPath() ||
			app.getStrippedPaths().length>0) {
		dependencyGenerator.setLeadingStripper(new LeadingNameStripper(app.isStripLeadingPath(),inputDir,app.getStrippedPaths()));
	}
	
	if (app.isDetail()) {
		dependencyGenerator.setGenerateDetail(true);
	}
	
	dependencyGenerator.setFilenameRewritter(filenameWritter);
	langProcessor.setDependencyGenerator(dependencyGenerator);
	
	langProcessor.buildDependencies(inputDir, includeDir,app.getTypeFilter(),supportImplLink,app.isOutputExternalDependencies(),app.isDuckTypingDeduce());
	
	
	DependencyMatrix matrix = langProcessor.getDependencies();

	if (app.getGranularity().startsWith("L")) {
		matrix = new MatrixLevelReducer(matrix,app.getGranularity().substring(1)).shrinkToLevel();
	}
	DependencyDumper output = new DependencyDumper(matrix);
	output.outputResult(outputName,outputDir,outputFormat);
	if (app.isOutputExternalDependencies()) {
		Set<UnsolvedBindings> unsolved = langProcessor.getExternalDependencies();
    	UnsolvedSymbolDumper unsolvedSymbolDumper = new UnsolvedSymbolDumper(unsolved,app.getOutputName(),app.getOutputDir(),
    			new LeadingNameStripper(app.isStripLeadingPath(),inputDir,app.getStrippedPaths()));
    	unsolvedSymbolDumper.output();
	}
	long endTime = System.currentTimeMillis();
	TemporaryFile.getInstance().delete();
	CacheManager.create().shutdown();
	System.out.println("Consumed time: " + (float) ((endTime - startTime) / 1000.00) + " s,  or "
			+ (float) ((endTime - startTime) / 60000.00) + " min.");
}
 
Example #27
Source File: SimilarityCorpus3.java    From bluima with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        final String ROOT = "/Volumes/HDD2/ren_data/dev_hdd/bluebrain/9_lda/1_dca/models/20140504_dca-1m_ns/";
        final String idsFile = ROOT + "1m_ns.pmids.txt";
        final int NR_TOPICS = 1000;
        final String DOCTOPICS = ROOT + "trained__1000/1m_ns.doctopics";
        final int THE_PMID = 18077435;

        // read ids
        Map<Integer, Integer> pmid2lineid = newHashMap();
        int[] pmids = intsFrom(idsFile);
        for (int i = 0; i < pmids.length; i++) {
            pmid2lineid.put(pmids[i], i);
        }

        // read topics
        Map<Integer, double[]> pmid2topicdist = newHashMap();
        List<String> doctopics = linesFrom(DOCTOPICS);
        for (int l = 0; l < doctopics.size(); l++) {
            int pmId = pmids[l];

            String line = doctopics.get(l);
            String[] split = line.split(":  ");
            checkEquals(2, split.length);
            String[] distStr = split[1].split(" ");
            checkEquals(NR_TOPICS, distStr.length);
            double[] topicdist = new double[distStr.length];
            for (int i = 0; i < distStr.length; i++) {
                topicdist[i] = parseDouble(distStr[i]);
            }
            pmid2topicdist.put(pmId, topicdist);
        }
        checkEquals(pmid2lineid.size(), pmid2topicdist.size(),
                "doc cnt should match");
        final double[] theTopicDist = pmid2topicdist.get(THE_PMID);
        System.out.println(Arrays.toString(theTopicDist));

        checkNotNull(theTopicDist);
        System.out.println("done reading");

        Map<Integer, Double> pmid_distances = newHashMap();
        int progress = 0;
        for (Entry<Integer, double[]> pmid_pz : pmid2topicdist.entrySet()) {
            double dist = jensenShannonDivergence(pmid_pz.getValue(),
                    theTopicDist);
            pmid_distances.put(pmid_pz.getKey(), dist);
            if (progress++ % 1000 == 0) {
                System.out.println("progress " + progress);
            }
        }

        // sort and output
        TextFileWriter w = new TextFileWriter("out.txt");
        int topN = 100, i = 0;
        for (Entry<Integer, Double> pmid_distance : sortByValue(pmid_distances)
                .entrySet()) {
            int pmid = pmid_distance.getKey();
            w.addLine(pmid + "\t" + pmid_distance.getValue());
            System.out.println(pmid + "\t"
                    + Arrays.toString(pmid2topicdist.get(pmid)));
            if (i++ > topN)
                break;
        }
        w.close();
        System.out.println("done :-)");
    }
 
Example #28
Source File: SimilarityCorpus.java    From bluima with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        final int NR_TOPICS = 100;
        final String ROOT = "/Volumes/HDD2/ren_data/data_hdd/__mycorpora/1m_ns/";
        final String DOCTOPICS = ROOT + "dca/1m_ns.doctopics";
        final String idsFile = ROOT + "1m_ns.pmids.txt";
        final int THE_PMID = 18077435;

        // read ids
        Map<Integer, Integer> pmid2lineid = newHashMap();
        int[] pmids = intsFrom(idsFile);
        for (int i = 0; i < pmids.length; i++) {
            pmid2lineid.put(pmids[i], i);
        }

        // read topics
        Map<Integer, double[]> pmid2topicdist = newHashMap();
        List<String> doctopics = linesFrom(DOCTOPICS);
        for (int l = 0; l < doctopics.size(); l++) {
            int pmId = pmids[l];

            String line = doctopics.get(l);
            String[] split = line.split(":  ");
            checkEquals(2, split.length);
            String[] distStr = split[1].split(" ");
            checkEquals(NR_TOPICS, distStr.length);
            double[] topicdist = new double[distStr.length];
            for (int i = 0; i < distStr.length; i++) {
                topicdist[i] = parseDouble(distStr[i]);
            }
            pmid2topicdist.put(pmId, topicdist);
        }
        checkEquals(pmid2lineid.size(), pmid2topicdist.size(),
                "doc cnt should match");
        final double[] theTopicDist = pmid2topicdist.get(THE_PMID);
        System.out.println(Arrays.toString(theTopicDist));
        checkNotNull(theTopicDist);
        System.out.println("done reading");

        Map<Integer, Double> pmid_distances = newHashMap();
        int progress = 0;
        for (Entry<Integer, double[]> pmid_pz : pmid2topicdist.entrySet()) {
            double dist = jensenShannonDivergence(pmid_pz.getValue(),
                    theTopicDist);
            pmid_distances.put(pmid_pz.getKey(), dist);
            if (progress++ % 1000 == 0) {
                System.out.println("progress " + progress);
            }
        }

        // sort and output
        TextFileWriter w = new TextFileWriter("out.txt");
        int topN = 100, i = 0;
        for (Entry<Integer, Double> pmid_distance : sortByValue(pmid_distances)
                .entrySet()) {
            w.addLine(pmid_distance.getKey() + "\t" + pmid_distance.getValue());
            if (i++ > topN)
                break;
        }
        w.close();
        System.out.println("done :-)");
    }
 
Example #29
Source File: PropertyVersionChangerTests.java    From spring-cloud-release-tools with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Set<Project> allProjects() {
	return new HashSet<>(Arrays.asList(
			new Project[] { project("spring-cloud-aws", "1.2.0.BUILD-SNAPSHOT"),
					project("spring-cloud-sleuth", "1.2.0.BUILD-SNAPSHOT") }));
}
 
Example #30
Source File: AccessTokenGenerator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
private String getScopeHash(String[] scopes){
    Arrays.sort(scopes);
    return DigestUtils.md5Hex(String.join(" ", scopes));
}