javatips.net counter

Java Examples for java.util.List

The following java examples will help you to understand the usage of java.util.List. These source code samples are taken from different open source projects.

Example 1
Project: extFM-Tooling-master  File: MtextPrinter2.java View source code
public void setFeatureValues(String featureName, java.util.List<Object> values) {
    featureToValuesMap.put(featureName, values);
    // 'featureToPrintedIndicesMap' is therefore not needed in this case.
    if (values != null) {
        featureToPrintedIndicesMap.put(featureName, new java.util.LinkedHashSet<Integer>());
    }
}
Example 2
Project: rascal-master  File: Signature.java View source code
@Override
protected void addForLineNumber(int $line, java.util.List<AbstractAST> $result) {
    if (getLocation().getBeginLine() == $line) {
        $result.add(this);
    }
    ISourceLocation $l;
    $l = modifiers.getLocation();
    if ($l.hasLineColumn() && $l.getBeginLine() <= $line && $l.getEndLine() >= $line) {
        modifiers.addForLineNumber($line, $result);
    }
    if ($l.getBeginLine() > $line) {
        return;
    }
    $l = type.getLocation();
    if ($l.hasLineColumn() && $l.getBeginLine() <= $line && $l.getEndLine() >= $line) {
        type.addForLineNumber($line, $result);
    }
    if ($l.getBeginLine() > $line) {
        return;
    }
    $l = name.getLocation();
    if ($l.hasLineColumn() && $l.getBeginLine() <= $line && $l.getEndLine() >= $line) {
        name.addForLineNumber($line, $result);
    }
    if ($l.getBeginLine() > $line) {
        return;
    }
    $l = parameters.getLocation();
    if ($l.hasLineColumn() && $l.getBeginLine() <= $line && $l.getEndLine() >= $line) {
        parameters.addForLineNumber($line, $result);
    }
    if ($l.getBeginLine() > $line) {
        return;
    }
}
Example 3
Project: openjdk-master  File: TestGenericReturnTypeToString.java View source code
@ExpectedGenericString("java.util.List<java.lang.String>")
public java.util.List<java.lang.String> foo5() {
    return null;
}
Example 4
Project: teiid-designer-master  File: MappingLinkEditPart.java View source code
/**
     * @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#createFigure()
     **/
@Override
protected IFigure createFigure() {
    DiagramPolylineConnection connectionFigure = new DiagramPolylineConnection();
    List toolTips = ((NodeConnectionModel) getModel()).getToolTipStrings();
    if (toolTips != null && !toolTips.isEmpty())
        connectionFigure.setToolTip(connectionFigure.createToolTip(toolTips));
    connectionFigure.setLineStyle(Graphics.LINE_SOLID);
    int iStandardWidth = connectionFigure.getLineWidth();
    iStandardWidth = 1;
    connectionFigure.setLineWidth(iStandardWidth);
    connectionFigure.setForegroundColor(ColorConstants.darkBlue);
    return connectionFigure;
}
Example 5
Project: aws-sdk-android-master  File: EndpointBatchItemJsonMarshaller.java View source code
public void marshall(EndpointBatchItem endpointBatchItem, AwsJsonWriter jsonWriter) throws Exception {
    jsonWriter.beginObject();
    if (endpointBatchItem.getAddress() != null) {
        String address = endpointBatchItem.getAddress();
        jsonWriter.name("Address");
        jsonWriter.value(address);
    }
    if (endpointBatchItem.getAttributes() != null) {
        java.util.Map<String, java.util.List<String>> attributes = endpointBatchItem.getAttributes();
        jsonWriter.name("Attributes");
        jsonWriter.beginObject();
        for (java.util.Map.Entry<String, java.util.List<String>> attributesEntry : attributes.entrySet()) {
            java.util.List<String> attributesValue = attributesEntry.getValue();
            if (attributesValue != null) {
                jsonWriter.name(attributesEntry.getKey());
                jsonWriter.beginArray();
                for (String attributesValueItem : attributesValue) {
                    if (attributesValueItem != null) {
                        jsonWriter.value(attributesValueItem);
                    }
                }
                jsonWriter.endArray();
            }
        }
        jsonWriter.endObject();
    }
    if (endpointBatchItem.getChannelType() != null) {
        String channelType = endpointBatchItem.getChannelType();
        jsonWriter.name("ChannelType");
        jsonWriter.value(channelType);
    }
    if (endpointBatchItem.getDemographic() != null) {
        EndpointDemographic demographic = endpointBatchItem.getDemographic();
        jsonWriter.name("Demographic");
        EndpointDemographicJsonMarshaller.getInstance().marshall(demographic, jsonWriter);
    }
    if (endpointBatchItem.getEffectiveDate() != null) {
        String effectiveDate = endpointBatchItem.getEffectiveDate();
        jsonWriter.name("EffectiveDate");
        jsonWriter.value(effectiveDate);
    }
    if (endpointBatchItem.getEndpointStatus() != null) {
        String endpointStatus = endpointBatchItem.getEndpointStatus();
        jsonWriter.name("EndpointStatus");
        jsonWriter.value(endpointStatus);
    }
    if (endpointBatchItem.getId() != null) {
        String id = endpointBatchItem.getId();
        jsonWriter.name("Id");
        jsonWriter.value(id);
    }
    if (endpointBatchItem.getLocation() != null) {
        EndpointLocation location = endpointBatchItem.getLocation();
        jsonWriter.name("Location");
        EndpointLocationJsonMarshaller.getInstance().marshall(location, jsonWriter);
    }
    if (endpointBatchItem.getMetrics() != null) {
        java.util.Map<String, Double> metrics = endpointBatchItem.getMetrics();
        jsonWriter.name("Metrics");
        jsonWriter.beginObject();
        for (java.util.Map.Entry<String, Double> metricsEntry : metrics.entrySet()) {
            Double metricsValue = metricsEntry.getValue();
            if (metricsValue != null) {
                jsonWriter.name(metricsEntry.getKey());
                jsonWriter.value(metricsValue);
            }
        }
        jsonWriter.endObject();
    }
    if (endpointBatchItem.getOptOut() != null) {
        String optOut = endpointBatchItem.getOptOut();
        jsonWriter.name("OptOut");
        jsonWriter.value(optOut);
    }
    if (endpointBatchItem.getRequestId() != null) {
        String requestId = endpointBatchItem.getRequestId();
        jsonWriter.name("RequestId");
        jsonWriter.value(requestId);
    }
    if (endpointBatchItem.getUser() != null) {
        EndpointUser user = endpointBatchItem.getUser();
        jsonWriter.name("User");
        EndpointUserJsonMarshaller.getInstance().marshall(user, jsonWriter);
    }
    jsonWriter.endObject();
}
Example 6
Project: eclipselink.runtime-master  File: PropertyTypeTestCases.java View source code
public void testPropertyTypes() throws Exception {
    JaxbClassLoader classLoader = new JaxbClassLoader(Thread.currentThread().getContextClassLoader());
    Generator generator = new Generator(new JavaModelInputImpl(new Class[] { TestObject.class }, new JavaModelImpl(this.classLoader)));
    CoreProject proj = generator.generateProject();
    TypeInfo info = generator.getAnnotationsProcessor().getTypeInfos().get("org.eclipse.persistence.testing.jaxb.annotations.TestObject");
    Property booleanProp = info.getProperties().get("booleanTest");
    JavaClass type = booleanProp.getType();
    assertEquals("java.lang.Boolean", type.getRawName());
    Property booleanListProp = info.getProperties().get("booleanListTest");
    type = booleanListProp.getType();
    assertEquals("java.util.List", type.getRawName());
    Property byteArrayProp = info.getProperties().get("byteArrayTest");
    type = byteArrayProp.getType();
    assertEquals("java.lang.String", type.getRawName());
    Property byteArrayListProp = info.getProperties().get("byteArrayListTest");
    type = byteArrayListProp.getType();
    assertEquals("java.util.List", type.getRawName());
    assertEquals("java.lang.String", byteArrayListProp.getGenericType().getRawName());
}
Example 7
Project: xmind-master  File: CheckOpenFilesProcess.java View source code
/*
     * (non-Javadoc)
     *
     * @see
     * org.xmind.cathy.internal.jobs.OpenFilesJob#filterFilesToOpen(java.util
     * .List, org.eclipse.core.runtime.IProgressMonitor)
     */
@Override
protected void filterFilesToOpen(List<String> filesToOpen) {
    Log opening = Log.get(Log.OPENING);
    if (opening.exists()) {
        String[] contents = opening.getContents();
        for (String line : contents) {
            if (line.startsWith("xmind:") || new File(line).exists()) {
                //$NON-NLS-1$
                filesToOpen.add(line);
            }
        }
        opening.delete();
    }
}
Example 8
Project: dataverse-master  File: BundleUtil.java View source code
public static String getStringFromBundle(String key, List<String> arguments, ResourceBundle bundle) {
    if (key == null || key.isEmpty()) {
        return null;
    }
    String stringFromBundle = null;
    try {
        stringFromBundle = bundle.getString(key);
        logger.fine("string found: " + stringFromBundle);
    } catch (MissingResourceException ex) {
        logger.warning("Could not find key \"" + key + "\" in bundle file.");
        return null;
    }
    if (arguments != null) {
        Object[] argArray = new String[arguments.size()];
        argArray = arguments.toArray(argArray);
        return MessageFormat.format(stringFromBundle, argArray);
    } else {
        return stringFromBundle;
    }
}
Example 9
Project: alien4cloud-master  File: MockLocationMatchOrchestratorFilter.java View source code
@Override
public void filter(List<ILocationMatch> toFilter, Topology topology) {
    for (Iterator<ILocationMatch> it = toFilter.iterator(); it.hasNext(); ) {
        ILocationMatch locationMatch = it.next();
        if (!locationMatch.getOrchestrator().getPluginId().equals(selfContext.getPlugin().getId())) {
            it.remove();
        }
    }
}
Example 10
Project: FallUML2013-master  File: FileUtil.java View source code
public static FileInfo getFile(String extension, List<FileInfo> fileList) {
    FileInfo info = null;
    for (int i = 0; i < fileList.size(); i++) {
        String extn = fileList.get(i).getFileName().substring(fileList.get(i).getFileName().lastIndexOf(".") + 1, fileList.get(i).getFileName().length());
        if (extn.equals(extension)) {
            info = fileList.get(i);
        }
    }
    return info;
}
Example 11
Project: dcache-master  File: RandomPoolSelectionStrategy.java View source code
@Override
public PoolManagerPoolInformation select(List<PoolManagerPoolInformation> pools) {
    List<PoolManagerPoolInformation> nonFullPools = pools.stream().filter(RandomPoolSelectionStrategy::hasAvailableSpace).collect(toList());
    if (nonFullPools.isEmpty()) {
        return null;
    }
    return nonFullPools.get(_random.nextInt(nonFullPools.size()));
}
Example 12
Project: many-ql-master  File: MissingIdentifiersError.java View source code
private static String missingIdentifierString(List<Identifier> processed, Set<Identifier> all) {
    StringBuilder missing = new StringBuilder("-- Missing Identifiers --\n");
    all.stream().filter( identifier -> !processed.contains(identifier)).forEach( identifier -> missing.append("  > " + identifier + "\n"));
    return missing.toString();
}
Example 13
Project: airlift-master  File: ConfigDefaults.java View source code
static <T> ConfigDefaults<T> configDefaults(List<? extends ConfigDefaults<T>> configDefaults) {
    List<ConfigDefaults<T>> finalConfigDefaults = ImmutableList.copyOf(configDefaults);
    return  config -> {
        for (ConfigDefaults<T> configDefault : finalConfigDefaults) {
            configDefault.setDefaults(config);
        }
    };
}
Example 14
Project: hibernate-core-ogm-master  File: PersistentList.java View source code
public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException {
    List deletes = new ArrayList();
    List sn = (List) getSnapshot();
    int end;
    if (sn.size() > list.size()) {
        for (int i = list.size(); i < sn.size(); i++) {
            deletes.add(indexIsFormula ? sn.get(i) : new Integer(i));
        }
        end = list.size();
    } else {
        end = sn.size();
    }
    for (int i = 0; i < end; i++) {
        if (list.get(i) == null && sn.get(i) != null) {
            deletes.add(indexIsFormula ? sn.get(i) : new Integer(i));
        }
    }
    return deletes.iterator();
}
Example 15
Project: openmap-master  File: LayerConfigurationListenerSupport.java View source code
/**
     * Check the list of layers, make changes as required.
     * 
     * @param layerList the list of layers to check.
     */
public synchronized List<Layer> checkLayerConfiguration(List<Layer> layerList) {
    if (size() == 0)
        return null;
    List<Layer> newList = null;
    for (LayerConfigurationListener listener : this) {
        newList = listener.checkLayerConfiguration(layerList);
        // LayerHandler about the changes.
        if (newList != null) {
            layerList = newList;
        }
    }
    return newList;
}
Example 16
Project: windowtester-master  File: ExceptionHelper.java View source code
/**
     * Take a List of Throwables, and chain them together, by
     * starting at the last Throwable in the List, and setting
     * the previous Throwable as its cause.
     *   
     * @param throwables List<Throwable>
     * @return Throwable the first Throwable in the List
     */
//public static Throwable chainThrowables(List<Throwable> throwables)
public static Throwable chainThrowables(List throwables) {
    for (int i = throwables.size() - 1; i > 0; i--) {
        Throwable parent = (Throwable) throwables.get(i);
        Throwable cause = (Throwable) throwables.get(i - 1);
        if (parent != cause) {
            parent.initCause(cause);
        }
    }
    //First throwable
    return (Throwable) throwables.get(throwables.size() - 1);
}
Example 17
Project: sosies-generator-master  File: DelegateTypeAdapterTest.java View source code
@Test(timeout = 1000)
public void testDelegateInvoked_add1112() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testDelegateInvoked_add1112");
    List<com.google.gson.common.TestTypes.BagOfPrimitives> bags = new ArrayList<com.google.gson.common.TestTypes.BagOfPrimitives>();
    for (int i = 0; i < 10; ++i) {
        bags.add(new TestTypes.BagOfPrimitives(i, i, ((i % 2) == 0), String.valueOf(i)));
        bags.add(new TestTypes.BagOfPrimitives(i, i, ((i % 2) == 0), String.valueOf(i)));
    }
    String json = gson.toJson(bags);
    bags = gson.fromJson(json, new TypeToken<java.util.List<com.google.gson.common.TestTypes.BagOfPrimitives>>() {
    }.getType());
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1418, stats.numReads);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1419, stats.numWrites);
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 18
Project: molgenis-master  File: LimitMethod.java View source code
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException {
    if (arguments.size() != 3) {
        throw new TemplateModelException("Expected two arguments");
    }
    String s = DataConverter.toString(unwrap((TemplateModel) arguments.get(0)));
    Integer nrOfCharacters = DataConverter.toInt(unwrap((TemplateModel) arguments.get(1)));
    String container = DataConverter.toString(arguments.get(2));
    return limit(s, nrOfCharacters, container);
}
Example 19
Project: hashtag-view-master  File: SortUtil.java View source code
public static <T> void symmetricSort(List<T> list) {
    @SuppressWarnings("unchecked") T[] array = (T[]) new Object[list.size()];
    for (int i = 0; i < list.size(); i++) {
        if (i % 2 == 0) {
            array[(list.size() - i) / 2 + (list.size() % 2 - 1)] = list.get(i);
        } else {
            array[(list.size() + i) / 2] = list.get(i);
        }
    }
    int j = 0;
    ListIterator<T> it = list.listIterator();
    while (it.hasNext()) {
        it.next();
        it.set(array[j++]);
    }
}
Example 20
Project: eclipse-commons-master  File: CollectionUtils.java View source code
/**
	 * Compares two lists lexicographically that contain comparable elements.
	 */
public static <T extends Comparable<? super T>> int compare(List<T> list1, List<T> list2) {
    int size1 = list1.size();
    int size2 = list2.size();
    int minSize = Math.min(size1, size2);
    for (int i = 0; i < minSize; i++) {
        int difference = list1.get(i).compareTo(list2.get(i));
        if (difference != 0) {
            return difference;
        }
    }
    if (size1 == size2) {
        return 0;
    } else {
        return size1 - size2;
    }
}
Example 21
Project: ehour-master  File: TimesheetEntryRowProcessor.java View source code
@Override
public List<Map<String, Object>> processRows(List<Map<String, Object>> rows) {
    for (Map<String, Object> row : rows) {
        if (!row.containsKey(UPDATE_DATE) || row.get(UPDATE_DATE) == null) {
            row.put(UPDATE_DATE, row.get(ENTRY_DATE));
        }
    }
    return rows;
}
Example 22
Project: Yhb-2.0-master  File: PathHelper.java View source code
public static Path pathFromPoints(List<Point> points) {
    Path path = new Path();
    Point start = points.get(0);
    path.moveTo((float) start.x, (float) start.y);
    int l = points.size();
    for (int i = 1; i < l; i++) {
        Point point = points.get(i);
        path.lineTo((float) point.x, (float) point.y);
    }
    return path;
}
Example 23
Project: polly-master  File: PasteServiceLogOutput.java View source code
@Override
public void outputLogs(IrcManager irc, String channel, List<LogEntry> logs, int unfilteredSize, LogFormatter formatter, FormatManager pollyFormat) {
    final String logString = this.formatLogs(logs, formatter, pollyFormat);
    try {
        final String pasteUrl = this.paster.paste(logString);
        final String result = MSG.bind(MSG.pasteOutputResult, logs.size(), unfilteredSize, pasteUrl);
        irc.sendMessage(channel, result, this);
    } catch (Exception e) {
        irc.sendMessage(channel, MSG.pasteOutputFail, this);
    }
}
Example 24
Project: PortalWaitingList-master  File: SearchUtil.java View source code
public static void searchByPortalName(List<PortalDetail> allPortals, List<PortalDetail> resultPortals, String queryText) {
    resultPortals.clear();
    if (queryText.equals("")) {
        MailProcessUtil.getInstance().filterAndSort(SettingUtil.TypeFilterMethod.ALL, SettingUtil.ResultFilterMethod.EVERYTHING, SettingUtil.SortOrder.LAST_DATE_DESC, allPortals, resultPortals);
    } else {
        for (PortalDetail eachPortal : allPortals) {
            if (eachPortal.getName().contains(queryText))
                resultPortals.add(eachPortal);
        }
    }
}
Example 25
Project: ProjectModel-master  File: MyAjax.java View source code
public static void createAjaxResponseContent(Object object, javax.servlet.http.HttpServletResponse response, String type) {
    response.setContentType("text/" + type + "; charset=utf-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "0");
    java.io.PrintWriter out = null;
    try {
        out = response.getWriter();
    } catch (java.io.IOException e) {
    }
    out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    out.println("<HigherUp>");
    if (object instanceof String)
        out.println("<![CDATA[" + object + "]]>");
    else if (object instanceof java.util.List) {
        java.util.List list = (java.util.List) object;
        for (int i = 0; i < list.size(); i++) {
            Object obj[] = (Object[]) list.get(i);
            out.println("<Child>");
            for (int j = 0; i < obj.length; j++) {
                String value = obj[j] == null ? "" : obj[j].toString();
                out.println("<Value" + (j + 1) + "><![CDATA[" + value + "]]></Value" + (j + i) + ">");
            }
            out.println("</Child>");
        }
    }
    out.println("</HigherUp>");
}
Example 26
Project: dk-master  File: PaginationCallback.java View source code
public Pagination<T> getPage(List<Map<String, Object>> datas, Pagination<T> page) {
    int size = datas.size();
    List<T> results = new ArrayList<T>(size);
    for (int i = 0; i < size; i++) {
        Map<String, Object> data = datas.get(i);
        results.add(toCustomizedBean(data));
    }
    page.setRows(results);
    return page;
}
Example 27
Project: financius-public-master  File: SharpPathMaker.java View source code
@Override
public Path makePath(List<PointF> points) {
    final Path path = new Path();
    for (int i = 0, size = points != null ? points.size() : 0; i < size; i++) {
        final PointF point = points.get(i);
        if (point == null) {
            continue;
        }
        if (i == 0 || points.get(i - 1) == null) {
            path.moveTo(point.x, point.y);
        } else {
            path.lineTo(point.x, point.y);
        }
    }
    return path;
}
Example 28
Project: cms-ce-master  File: LogEntryEntityFetcherImpl.java View source code
public Map<LogEntryKey, LogEntryEntity> fetch(List<LogEntryKey> keys) {
    Map<LogEntryKey, LogEntryEntity> map = new LinkedHashMap<LogEntryKey, LogEntryEntity>();
    if (keys != null && keys.size() > 0) {
        // performance: fetching one and one will go faster when content is cached
        int i = 0;
        for (LogEntryKey key : keys) {
            map.put(key, logEntryDao.findByKey(key));
            i++;
        }
    }
    return map;
}
Example 29
Project: ocr-tools-master  File: Merger.java View source code
public void mergeBuffered(List<InputStream> inputs, OutputStream output) throws IOException {
    BufferedOutputStream bufferedOutput = new BufferedOutputStream(output, 8 * 1024);
    try {
        merge(inputs, bufferedOutput);
    } finally {
        bufferedOutput.flush();
        bufferedOutput.close();
    }
}
Example 30
Project: FireflowEngine20-master  File: ScriptEngineTest.java View source code
public static void listAllScriptEngines() {
    System.out.println("==搜索到的所有的脚本引擎如下……");
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factoryList = manager.getEngineFactories();
    int i = 0;
    for (ScriptEngineFactory factory : factoryList) {
        System.out.println("");
        System.out.print("No" + (i++) + "、enginename=");
        System.out.print(factory.getEngineName());
        System.out.print(";languagename=");
        System.out.print(factory.getLanguageName());
        System.out.print(";extensions=" + factory.getExtensions());
        System.out.print("; names=" + factory.getNames());
        System.out.print("; MimeTypes=" + factory.getMimeTypes());
    }
}
Example 31
Project: AIDR-master  File: TaggerAllCrisesTypesResponse.java View source code
/*
    public void setCrisisTypes(List<TaggerCrisisType> crisisTypes) {
        this.crisisTypes = crisisTypes;
    }
    */
public void setCrisisTypes(List<CrisisTypeDTO> dtoList) throws Exception {
    if (dtoList != null) {
        List<TaggerCrisisType> list = new ArrayList<TaggerCrisisType>();
        for (CrisisTypeDTO d : dtoList) {
            TaggerCrisisType t = new TaggerCrisisType(d);
            list.add(t);
        }
        this.crisisTypes = list;
    }
}
Example 32
Project: MUtils-master  File: ListSizeComparator.java View source code
@Override
public int compare(List<?> lhs, List<?> rhs) {
    int diff = lhs.size() - rhs.size();
    if (diff > 0) {
        return mOrder == Order.ASC ? 1 : -1;
    } else if (diff < 0) {
        return mOrder == Order.ASC ? -1 : 1;
    } else {
        return 0;
    }
}
Example 33
Project: tdq-studio-se-master  File: ImportObjectTest.java View source code
/**
     * Test method for
     * [email protected] [email protected]ctImportObject(org.talend.dataprofiler.ecos.model.IEcosComponent, java.util.List)}
     * .
     */
@Test
public void testExtractImportObject() {
    try {
        IEcosComponent ecosMock = mock(IEcosComponent.class);
        PowerMockito.mockStatic(ComponentInstaller.class);
        File fileMock = mock(File.class);
        when(ComponentInstaller.unzip(anyString(), anyString())).thenReturn(fileMock);
        PowerMockito.mockStatic(FilesUtils.class);
        List<File> objFiles = new ArrayList<File>();
        File objFileMock = mock(File.class);
        objFiles.add(objFileMock);
        List<File> jarFiles = new ArrayList<File>();
        File jarFileMock = mock(File.class);
        jarFiles.add(jarFileMock);
        when(FilesUtils.getAllFilesFromFolder((File) anyObject(), (FilenameFilter) anyObject())).thenReturn(objFiles).thenReturn(jarFiles);
        List<ReturnCode> information = new ArrayList<ReturnCode>();
        List<ImportObject> importObjects = ImportObject.extractImportObject(ecosMock, information);
        assertEquals(importObjects.size(), 1);
        assertEquals(information.size(), 0);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
Example 34
Project: solmix-master  File: InternalExtensionParserTest.java View source code
@Test
public void test() {
    URL url = this.getClass().getResource("java.util.List");
    List<ExtensionInfo> extensions = new InternalExtensionParser(null).getExtensions(url);
    Assert.assertEquals("Unexpected number of Extension elements.", 2, extensions.size());
    ExtensionInfo e1 = extensions.get(0);
    Assert.assertTrue(e1.isDeferred());
    Assert.assertTrue(e1.isOptional());
    ExtensionInfo e2 = extensions.get(1);
    Assert.assertEquals("java.util.LinkedList", e2.getClassname());
    Assert.assertEquals("java.util.List", e2.getInterfaceName());
    Assert.assertTrue(LinkedList.class == e2.getClassObject(Thread.currentThread().getContextClassLoader()));
}
Example 35
Project: tmdm-studio-se-master  File: ViewMainPage.java View source code
@Override
protected void refreshData() {
    try {
        if (this.comitting) {
            return;
        }
        this.refreshing = true;
        WSView wsObject = getWsViewObject();
        //$NON-NLS-1$
        desAntionComposite.setText(wsObject.getDescription() == null ? "" : wsObject.getDescription());
        btnRunProcess.setSelection(wsObject.getIsTransformerActive().isTrue());
        if (btnRunProcess.getSelection()) {
            cboProcessList.setEnabled(true);
            cboProcessList.setText(wsObject.getTransformerPK());
        } else {
            cboProcessList.setEnabled(false);
            //$NON-NLS-1$
            cboProcessList.setText("");
        }
        java.util.List<Line> vlines = new ArrayList<Line>();
        java.util.List<String> vis = wsObject.getViewableBusinessElements();
        if (vis != null) {
            for (String vi : vis) {
                String strings[] = new String[] { vi };
                Line line = new Line(viewableElementColumns, strings);
                vlines.add(line);
            }
        }
        viewableViewer.getViewer().setInput(vlines);
        java.util.List<Line> slines = new ArrayList<Line>();
        java.util.List<String> ses = wsObject.getSearchableBusinessElements();
        if (ses != null) {
            for (String se : ses) {
                String strings[] = new String[] { se };
                Line line = new Line(searchableElementColumns, strings);
                slines.add(line);
            }
        }
        searchableViewer.getViewer().setInput(slines);
        java.util.List<Line> lines = new ArrayList<Line>();
        for (WSWhereCondition wc : wsObject.getWhereConditions()) {
            Line line = new Line(conditionsColumns, Util.convertWhereCondition(wc));
            lines.add(line);
        }
        conditionViewer.getViewer().setInput(lines);
        this.refreshing = false;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        MessageDialog.openError(this.getSite().getShell(), Messages.ViewMainPage_ErrorRefreshPage, Messages.bind(Messages.ViewMainPage_ErrorRefreshPageXX, e.getLocalizedMessage()));
    }
}
Example 36
Project: FreeBuilder-master  File: CompilationUnitBuilderTest.java View source code
@Test
public void testAddLine_typesWithSameName() {
    CompilationUnitBuilder source = newSourceWriter("com.example", "Bar");
    source.addLine("// This should be imported: %s", java.util.List.class);
    source.addLine("// This should be explicit: %s", java.awt.List.class);
    assertThat(source.toString()).contains("import java.util.List;\n");
    assertThat(source.toString()).doesNotContain("import java.awt.List;\n");
    assertThat(source.toString()).contains("// This should be imported: List\n");
    assertThat(source.toString()).contains("// This should be explicit: java.awt.List\n");
}
Example 37
Project: Eclipse-Postfix-Code-Completion-master  File: NewDefiningMethodProposal.java View source code
/* (non-Javadoc)
	 * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewParameters(org.eclipse.jdt.core.dom.rewrite.ASTRewrite, java.util.List, java.util.List)
	 */
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params) throws CoreException {
    AST ast = rewrite.getAST();
    ImportRewrite importRewrite = getImportRewrite();
    ITypeBinding[] bindings = fMethod.getParameterTypes();
    IJavaProject project = getCompilationUnit().getJavaProject();
    String[][] paramNames = StubUtility.suggestArgumentNamesWithProposals(project, fParamNames);
    for (int i = 0; i < bindings.length; i++) {
        ITypeBinding curr = bindings[i];
        String[] proposedNames = paramNames[i];
        SingleVariableDeclaration newParam = ast.newSingleVariableDeclaration();
        newParam.setType(importRewrite.addImport(curr, ast));
        newParam.setName(ast.newSimpleName(proposedNames[0]));
        params.add(newParam);
        //$NON-NLS-1$
        String groupId = "arg_name_" + i;
        addLinkedPosition(rewrite.track(newParam.getName()), false, groupId);
        for (int k = 0; k < proposedNames.length; k++) {
            addLinkedPositionProposal(groupId, proposedNames[k], null);
        }
    }
}
Example 38
Project: Valkyrie-RCP-master  File: CustomizableFocusTraversalPolicy.java View source code
/**
     * Sets a custom focus traversal order for the given container. Child
     * components for which there is no order specified will receive focus after
     * components that do have an order specified in the standard "layout"
     * order.
     *
     * @param container
     *            the container
     * @param componentsInOrder
     *            a list of child components in the order that thay should
     *            receive focus
     */
public static void customizeFocusTraversalOrder(JComponent container, java.util.List componentsInOrder) {
    for (Iterator i = componentsInOrder.iterator(); i.hasNext(); ) {
        Component comp = (Component) i.next();
        if (comp.getParent() != container) {
            throw new IllegalArgumentException("Component [" + comp + "] is not a child of [" + container + "].");
        }
    }
    container.putClientProperty(FOCUS_ORDER_PROPERTY_NAME, createOrderMapFromList(componentsInOrder));
}
Example 39
Project: JFugue-for-Android-master  File: XPathFunctionImpl.java View source code
/**
     * @see javax.xml.xpath.XPathFunction#evaluate(java.util.List)
     */
public Object evaluate(List args) throws XPathFunctionException {
    Vector argsVec = listToVector(args);
    try {
        // The method key and ExpressionContext are set to null.
        return m_handler.callFunction(m_funcName, argsVec, null, null);
    } catch (TransformerException e) {
        throw new XPathFunctionException(e);
    }
}
Example 40
Project: openjdk8-jdk-master  File: WithoutParameters.java View source code
@ExpectedParameterInfo(parameterCount = 6, parameterTypes = { int.class, Foo.class, List.class, List.class, List.class, String[].class }, parameterizedTypes = { @ParameterizedInfo(Class.class), @ParameterizedInfo(Class.class), @ParameterizedInfo(value = ParameterizedType.class, string = "java.util.List<?>"), @ParameterizedInfo(value = ParameterizedType.class, string = "java.util.List<WithoutParameters$Foo>"), @ParameterizedInfo(value = ParameterizedType.class, string = "java.util.List<? extends WithoutParameters$Foo>"), @ParameterizedInfo(Class.class) }, isVarArgs = true)
public void qux(int quux, Foo quuux, List<?> l, List<Foo> l2, List<? extends Foo> l3, String... rest) {
}
Example 41
Project: LambdaDojo-master  File: S201LambdaInsteadOfAnonClass.java View source code
// 2-1 Lambda 式で書きかえてみましょう
private void rewriteByLambda() {
    // この匿名クラスを Lambda 式で書きかえ
    Comparator<Integer> comparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer x, Integer y) {
            return Integer.compare(x, y);
        }
    };
    List<Integer> numbers = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        numbers.add(i);
    }
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        Integer number = numbers.remove(random.nextInt(10 - i));
        numbers.add(number);
    }
    System.out.println("Before Sort: " + numbers);
    // 整数のリストをソート
    Collections.sort(numbers, comparator);
    System.out.println("After Sort: " + numbers);
}
Example 42
Project: octarine-master  File: Validation.java View source code
static <T> Validation<T> invalid(List<String> validationErrors) {
    return new Validation<T>() {

        @Override
        public boolean isValid() {
            return false;
        }

        @Override
        public List<String> validationErrors() {
            return validationErrors;
        }

        @Override
        public Valid<T> get() {
            throw new RecordValidationException(validationErrors());
        }
    };
}
Example 43
Project: breakout-master  File: JsonSpecList.java View source code
public E set(int index, E element) {
    E oldValue = ((List<E>) collection).get(index);
    if (!Java7.Objects.equals(oldValue, element)) {
        if (oldValue instanceof JsonSpecElement) {
            ((JsonSpecElement) oldValue).changeSupport().removePropertyChangeListener(propagator);
        }
        ((List<E>) collection).set(index, element);
        if (element instanceof JsonSpecElement) {
            ((JsonSpecElement) element).changeSupport().addPropertyChangeListener(propagator);
        }
        changeSupport.fireChildRemoved(this, oldValue);
        changeSupport.fireChildAdded(this, element);
    }
    return oldValue;
}
Example 44
Project: erlide-master  File: MapUtils.java View source code
public static <K, V> Map<V, List<K>> inverseList(final Map<K, List<V>> map) {
    final Map<V, List<K>> result = new LinkedHashMap<>();
    for (final Map.Entry<K, List<V>> entry : map.entrySet()) {
        for (final V v : entry.getValue()) {
            if (!result.containsKey(v)) {
                result.put(v, new ArrayList<K>());
            }
            result.get(v).add(entry.getKey());
        }
    }
    return result;
}
Example 45
Project: dtangler-master  File: RuleMemberSelectorImpl.java View source code
public String selectRuleMember(List<String> groupNames) {
    ActionFactory actionFactory = new ActionFactory();
    SwingRuleMemberView view = new SwingRuleMemberView(actionFactory);
    RuleMemberModel model = new RuleMemberModel(groupNames);
    RuleMemberPresenter presenter = new RuleMemberPresenter(view, model);
    new RuleMemberGlue(actionFactory, presenter, windowManager, view);
    windowManager.showModal(view);
    return model.getValue();
}
Example 46
Project: btpka3.github.com-master  File: SpringTest.java View source code
public static void main(String[] args) throws BeansException {
    final int THREAD_COUNT = 10;
    ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");
    CuratorFramework client = (CuratorFramework) appCtx.getBean("zkClient");
    List<Thread> list = new ArrayList<Thread>();
    // 创建并启动线程
    for (int i = 0; i < THREAD_COUNT; i++) {
        Thread t = new Thread(new MyTask(client, i));
        t.start();
        list.add(t);
    }
    // 等待线程结束
    for (int i = 0; i < THREAD_COUNT; i++) {
        Thread t = list.get(i);
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Example 47
Project: expenditures-master  File: MissionProcessProvider.java View source code
@Override
public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) {
    final String currentValue = StringUtils.trim(value);
    final List<MissionProcess> result = new ArrayList<MissionProcess>();
    final MissionSystem missionSystem = MissionSystem.getInstance();
    for (final MissionProcess missionProcess : missionSystem.getMissionProcessesSet()) {
        String[] processIdParts = missionProcess.getProcessNumber().split("/M");
        if (missionProcess.getProcessIdentification().equals(currentValue) || processIdParts[processIdParts.length - 1].equals(currentValue)) {
            result.add(missionProcess);
        }
    }
    return result;
}
Example 48
Project: FTL-Hyperion-master  File: EventAction.java View source code
@Override
public void preform(String action, Object... params) {
    Ship ship = game.getShip((String) params[0]);
    MapEvent event = game.getEvent(ship);
    String s1 = (String) params[1];
    if (s1.equals("ListActions")) {
        List<String> actions = event.getActions();
        for (int i = 0; i < actions.size(); i++) {
            System.out.println("" + i + ": " + actions.get(i));
        }
    } else {
        int actionIndex = Integer.parseInt(s1);
        List<String> actions = event.getActions();
        String eventAction = actions.get(actionIndex);
        event.preformAction(eventAction);
    }
}
Example 49
Project: avaje-ebeanorm-master  File: CustomerTest.java View source code
@Test
public void canInsert() {
    Customer customer = new Customer();
    customer.setName("Rob");
    //customer.setFoo("one");
    customer.save();
//
//    assertThat(customer.getId()).isNotNull();
//    Customer rob = Ebean.find(Customer.class)
//        .where().eq("name", "Rob")
//        .findUnique();
//
//    rob.setShortDesc("cone");
//    Ebean.save(rob);
//    long now = System.currentTimeMillis();
//    Timestamp ts = new Timestamp(now - 1000*60*10);
//
//    List<Customer> list = Ebean.find(Customer.class)
//        .asOf(ts)
//        .findList();
//
//    System.out.print("asd");
}
Example 50
Project: traffic-balance-master  File: JSONMessageComposer.java View source code
@Override
public String composeLocationDataMessage(List<Location> locations) {
    JSONArray array = new JSONArray();
    try {
        for (Location loc : locations) {
            JSONObject object = new JSONObject();
            object.put("lon", loc.getLongitude());
            object.put("lat", loc.getLatitude());
            object.put("time", loc.getTime());
            object.put("speed", loc.getSpeed());
            object.put("acc", loc.getAccuracy());
            object.put("course", loc.getBearing());
            array.put(object);
        }
    } catch (JSONException e) {
        Log.e("JSONComposer", e.toString());
    }
    return array.toString();
}
Example 51
Project: sonar-java-master  File: CollectionCallingItselfCheck.java View source code
void fun() {
    List<String> strings = new ArrayList<String>();
    strings.add("Hello");
    // Compliant - does not compile, as there is no method "add(List<String>)" in List. The method invocation is not resolved
    strings.add(strings);
    // Noncompliant {{Remove or correct this "addAll" call.}}
    strings.addAll(strings);
    // Noncompliant {{Remove or correct this "containsAll" call.}}
    strings.containsAll(strings);
    // Noncompliant {{Remove or correct this "removeAll" call.}}
    strings.removeAll(strings);
    // Noncompliant [[sc=5;ec=31]] {{Remove or correct this "retainAll" call.}}
    strings.retainAll(strings);
    strings.wait();
    strings.foo();
}
Example 52
Project: checkstyle-master  File: InputMethodReferences.java View source code
public void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
    numbers.forEach(String.CASE_INSENSITIVE_ORDER::equals);
    InputMethodReferences tl = new InputMethodReferences();
    String roster = new String();
    Supplier<InputMethodReferences> supplier = InputMethodReferences<String>::new;
    numbers.forEach(this::println);
    numbers.forEach(super::println);
    Supplier<InputMethodReferences2> supplier2 = InputMethodReferences2::new;
    Supplier<InputMethodReferences2> suppl = InputMethodReferences2::<Integer>new;
    Function<Integer, String[]> messageArrayFactory = String[]::new;
}
Example 53
Project: abmash-master  File: JavaScriptResult.java View source code
public Boolean hasAdequateReturnValue() {
    // TODO other return values
    if (returnValue instanceof WebElement) {
        return true;
    }
    if (returnValue instanceof Double) {
        return (Double) returnValue != 0.0;
    }
    if (returnValue instanceof Long) {
        return (Long) returnValue != 0;
    }
    if (returnValue instanceof Boolean) {
        return (Boolean) returnValue;
    }
    if (returnValue instanceof String) {
        return !((String) returnValue).equals("");
    }
    if (returnValue instanceof List<?>) {
        return !((List<?>) returnValue).isEmpty();
    }
    if (returnValue instanceof Map<?, ?>) {
        return !((Map<?, ?>) returnValue).isEmpty();
    }
    return false;
}
Example 54
Project: milton2-master  File: SendMailScratch.java View source code
public static void main(String[] arr) {
    String host = "XXX";
    String user = "XXX";
    String password = "XXX";
    int port = 465;
    RemoteSmtpMailSender sender = new RemoteSmtpMailSender(host, user, password, port);
    sender.setUseSsl(true);
    sender.start();
    StandardMessageImpl sm = new StandardMessageImpl();
    sm.setFrom(MailboxAddress.parse("[email protected]"));
    List<MailboxAddress> to = new ArrayList();
    to.add(MailboxAddress.parse("[email protected]"));
    sm.setTo(to);
    sm.setSubject("hello!");
    sender.sendMail(sm);
}
Example 55
Project: castor-master  File: NodeBuilder.java View source code
/**
     * Build the object we expect when we unmarshal 'input.xml'.
     */
public Object buildInstance() {
    NodeList nodeList = new NodeList();
    Node nodeOne = new Node();
    nodeOne.setNodeNum(1);
    Node nodeTwo = new Node();
    nodeTwo.setNodeNum(2);
    Node nodeThree = new Node();
    nodeThree.setNodeNum(3);
    List siblings = new ArrayList();
    siblings.add(nodeTwo);
    siblings.add(nodeThree);
    nodeOne.setSiblings(siblings);
    siblings = new ArrayList();
    siblings.add(nodeOne);
    siblings.add(nodeThree);
    nodeTwo.setSiblings(siblings);
    siblings = new ArrayList();
    siblings.add(nodeOne);
    siblings.add(nodeTwo);
    nodeThree.setSiblings(siblings);
    nodeList.addNode(nodeOne);
    nodeList.addNode(nodeTwo);
    nodeList.addNode(nodeThree);
    return nodeList;
}
Example 56
Project: raylew_algorithm-master  File: MaxK.java View source code
/**
     * 求最大的5个数
     * @param lst
     * @return
     */
public static List<Integer> max5(List<Integer> lst) {
    if (lst.size() <= 5)
        return lst;
    int a = lst.remove(lst.size() - 1);
    List<Integer> b = max5(lst);
    for (int i = 0; i < b.size(); i++) {
        int t = b.get(i);
        if (a > t) {
            lst.set(i, a);
            a = t;
        }
    }
    return b;
}
Example 57
Project: ilarkesto-master  File: GwtServiceInterfaceGenerator.java View source code
@Override
protected void printCode(JavaPrinter out) {
    out.package_(getPackageName());
    out.beginInterface(module.getValue() + "Service", Arrays.asList(com.google.gwt.user.client.rpc.RemoteService.class.getName()));
    List<Node> calls = module.getChildrenByTypeRecursive(ServiceCall);
    for (Node call : calls) {
        List<String> params = getParameterTypesAndNames(call, "String");
        params.add(0, "int conversationNumber");
        out.interfaceMethod(getPackageName() + ".DataTransferObject", Str.lowercaseFirstLetter(call.getValue()), params);
    }
    out.endInterface();
}
Example 58
Project: Klyph-master  File: TagSerializer.java View source code
public void serializeMap(Map<String, List<Tag>> tags, JSONObject json, String field) {
    JSONObject tagObject = new JSONObject();
    for (Iterator<String> iterator = tags.keySet().iterator(); iterator.hasNext(); ) {
        String key = (String) iterator.next();
        List<Tag> tag = tags.get(key);
        try {
            tagObject.put(key, super.serializeArray(tag));
        } catch (JSONException e) {
            Log.d("TagSerializer", "JsonException " + e.getMessage());
        }
    }
    try {
        json.put(field, tagObject);
    } catch (JSONException e) {
        Log.d("TagSerializer", "JsonException " + e.getMessage());
    }
}
Example 59
Project: schemacrawler-master  File: TestSqliteDistribution.java View source code
@Test
public void testSqliteMain() throws Exception {
    final OutputFormat outputFormat = OutputFormat.text;
    final String referenceFile = "sqlite.main" + "." + outputFormat.name();
    final File testOutputFile = File.createTempFile("schemacrawler." + referenceFile + ".", ".test");
    testOutputFile.delete();
    final File sqliteDbFile = copyResourceToTempFile("/sc.db");
    schemacrawler.tools.sqlite.Main.main(new String[] { "-database=" + sqliteDbFile.getAbsolutePath(), "-command=details,dump,count", "-infolevel=detailed", "-outputfile=" + testOutputFile });
    final List<String> failures = compareOutput(referenceFile, testOutputFile, outputFormat.name());
    if (failures.size() > 0) {
        fail(failures.toString());
    }
}
Example 60
Project: thundernetwork-master  File: ByteToMessageObjectHandler.java View source code
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    try {
        if (in.readableBytes() > 0) {
            byte[] data = new byte[in.readableBytes()];
            in.readBytes(data);
            Message message = serializater.deserializeMessage(data);
            out.add(message);
        //                System.out.println("Incoming: " + message);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 61
Project: korsakow-editor-master  File: ResourceTreeMediaFileTransferHandler.java View source code
@Override
protected boolean importMedia(List<? extends IMedia> media) {
    int[] dropPointIndexRef = new int[1];
    KNode dropPointNode = resourceTreeTransferHandler.getDropPointNode(dropPointIndexRef);
    if (dropPointNode == null) {
        dropPointNode = resourceTreeTransferHandler.resourceTreeTable.getRootNode();
    }
    int dropPointIndex = dropPointIndexRef[0];
    if (dropPointIndex < 0)
        dropPointIndex = dropPointNode.getChildCount();
    boolean addedsome = false;
    for (IMedia medium : media) {
        KNode node = ResourceNode.create(medium);
        resourceTreeTransferHandler.resourceTreeTable.getTreeTableModel().insertNodeInto(node, dropPointNode, dropPointIndex);
        Application.getInstance().notifyResourceAdded(medium);
        addedsome = true;
    }
    return addedsome;
}
Example 62
Project: ldbc_snb_datagen-master  File: ExistsCheck.java View source code
@Override
public boolean check(List<String> values) {
    for (String val : values) {
        boolean found = false;
        for (ColumnSet<T> column : refColumns) {
            if (column.contains(parser.parse(val))) {
                found = true;
                break;
            }
        }
        if (!found)
            return false;
    }
    return true;
}
Example 63
Project: sitebricks-master  File: SearchResultExtractorTest.java View source code
@Test
public void testExtractLonger() throws Exception {
    List<String> messages = ImmutableList.of("* search  42187 275543 287963 298411 298834 299843 305799 306131 319620 323938 328364 329370 329566 329599 331454 332401 338293 339646 341368 342169 342969 343541 344924 345047 345730 348037 349247 351914 351941 351945 352041 352461 352462", "* Ok SEARCH completed (Success)");
    String thing = "[42187 275543 287963 298411 298834 299843 305799 306131 319620 323938 328364 329370 329566 329599 331454 332401 338293 339646 341368 342169 342969 343541 344924 345047 345730 348037 349247 351914 351941 351945 352041 352461 352462]".replace(" ", ", ");
    assertEquals(thing, new SearchResultExtractor().extract(messages).toString());
}
Example 64
Project: Desktop-master  File: DocearPasteAction.java View source code
@SuppressWarnings("unchecked")
public void actionPerformed(final ActionEvent evt) {
    final MClipboardController clipboardController = (MClipboardController) ClipboardController.getController();
    final NodeModel targetNode = Controller.getCurrentController().getSelection().getSelected();
    final Transferable transferable = clipboardController.getClipboardContents();
    try {
        //$NON-NLS-1$
        final DataFlavor fileListFlavor = new DataFlavor("application/x-java-file-list; class=java.util.List");
        //$NON-NLS-1$
        final DataFlavor uriListFlavor = new DataFlavor("text/uri-list; class=java.lang.String");
        if (!transferable.isDataFlavorSupported(MindMapNodesSelection.mindMapNodesFlavor) && (transferable.isDataFlavorSupported(fileListFlavor) || transferable.isDataFlavorSupported(uriListFlavor))) {
            List<File> fileList = new ArrayList<File>();
            if (transferable.isDataFlavorSupported(fileListFlavor)) {
                fileList = (List<File>) (transferable.getTransferData(fileListFlavor));
            } else if (transferable.isDataFlavorSupported(uriListFlavor)) {
                fileList = DocearNodeDropListener.textURIListToFileList((String) transferable.getTransferData(uriListFlavor));
            }
            DocearNodeDropListener.pasteFileList(fileList, targetNode, targetNode.isNewChildLeft());
            return;
        }
    } catch (Exception e) {
        clipboardController.paste(clipboardController.getClipboardContents(), targetNode, false, targetNode.isNewChildLeft());
    }
    clipboardController.paste(clipboardController.getClipboardContents(), targetNode, false, targetNode.isNewChildLeft());
}
Example 65
Project: TFC2-master  File: ItemSoil.java View source code
@Override
public void addInformation(ItemStack is, EntityPlayer player, List arraylist, boolean flag) {
    super.addInformation(is, player, arraylist, flag);
    if (is.getItemDamage() < Global.STONE_ALL.length)
        arraylist.add(TextFormatting.DARK_GRAY + Core.translate("global." + Global.STONE_ALL[is.getItemDamage()]));
    else
        arraylist.add(TextFormatting.DARK_RED + Core.translate("global.unknown"));
}
Example 66
Project: pentaho-kettle-master  File: DataOverrideHandler.java View source code
public void showFeatureList() {
    Shell parent = getShell();
    DatabaseMeta dbinfo = new DatabaseMeta();
    getInfo(dbinfo);
    try {
        java.util.List<RowMetaAndData> buffer = dbinfo.getFeatureSummary();
        if (buffer.size() > 0) {
            RowMetaInterface rowMeta = buffer.get(0).getRowMeta();
            java.util.List<Object[]> rowData = new ArrayList<Object[]>();
            for (RowMetaAndData row : buffer) {
                rowData.add(row.getData());
            }
            PreviewRowsDialog prd = new PreviewRowsDialog(parent, dbinfo, SWT.NONE, null, rowMeta, rowData);
            prd.setTitleMessage(BaseMessages.getString(PKG, "DatabaseDialog.FeatureList.title"), BaseMessages.getString(PKG, "DatabaseDialog.FeatureList.title"));
            prd.open();
        }
    } catch (Exception e) {
        new ErrorDialog(parent, BaseMessages.getString(PKG, "DatabaseDialog.FeatureListError.title"), BaseMessages.getString(PKG, "DatabaseDialog.FeatureListError.description"), e);
    }
}
Example 67
Project: spring-framework-2.5.x-master  File: EditAccountFormAction.java View source code
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    AccountActionForm workingAcctForm = (AccountActionForm) form;
    AccountActionForm acctForm = (AccountActionForm) request.getSession().getAttribute("accountForm");
    String username = acctForm.getAccount().getUsername();
    if (workingAcctForm.getAccount() == null) {
        Account account = getPetStore().getAccount(username);
        workingAcctForm.setAccount(account);
    }
    if (workingAcctForm.getCategories() == null) {
        List categories = getPetStore().getCategoryList();
        workingAcctForm.setCategories(categories);
    }
    return mapping.findForward("success");
}
Example 68
Project: violetumleditor-master  File: MenuUtils.java View source code
public static void alterMenuBar(JMenuBar menuBar) {
    MenuElement[] subMenuElements = menuBar.getSubElements();
    List<MenuElement> menuEntryStack = new ArrayList<MenuElement>();
    if (subMenuElements.length > 0) {
        menuEntryStack.addAll(Arrays.asList(subMenuElements));
    }
    while (!menuEntryStack.isEmpty()) {
        MenuElement menuElement = menuEntryStack.get(0);
        if (menuElement instanceof JMenuItem) {
            final JMenuItem menuItem = (JMenuItem) menuElement;
            menuItem.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    System.out.println(menuItem.getName());
                }
            });
        }
        MenuElement[] subElements = menuElement.getSubElements();
        if (subElements.length > 0) {
            menuEntryStack.addAll(Arrays.asList(subElements));
        }
        menuEntryStack.remove(0);
    }
}
Example 69
Project: RapidBeans-master  File: ConfigApplicationTest.java View source code
/**
	 * load a test configuration.
	 */
public void testLoadConfiguration() {
    Document doc = new Document(new File("../org.rapidbeans/testdata/rapidclubadmin/config/Client.xml"));
    ConfigApplication configRoot = (ConfigApplication) doc.getRoot();
    ConfigDocument doccfg = configRoot.getDocuments().iterator().next();
    assertEquals("billingperiod", doccfg.getName());
    ConfigView stdViewcfg = doccfg.getViews().iterator().next();
    assertEquals("trainings", stdViewcfg.getName());
    List<ConfigEditorBean> edCfgs = (List<ConfigEditorBean>) configRoot.getBeaneditors();
    ConfigEditorBean edTrainer = edCfgs.get(4);
    assertNull(edTrainer.getEditorclass());
    assertEquals("org.rapidbeans.clubadmin.domain.Trainer", edTrainer.getBeantype());
}
Example 70
Project: VaadinUtils-master  File: ExtensionsRegistryFactory.java View source code
@Override
public ExtensionsRegistry createRegistry(String registryId, JRPropertiesMap properties) {
    // TODO Auto-generated method stub
    return new ExtensionsRegistry() {

        @SuppressWarnings("unchecked")
        @Override
        public <T> List<T> getExtensions(Class<T> extensionType) {
            if (extensionType == net.sf.jasperreports.engine.export.JRHyperlinkProducerFactory.class) {
                List<T> list = new LinkedList<T>();
                list.add((T) new CustomJRHyperlinkProducerFactory());
                return list;
            }
            return new LinkedList<T>();
        }
    };
}
Example 71
Project: ha-bridge-master  File: GroupResponse.java View source code
public static GroupResponse createGroupResponse(List<DeviceDescriptor> deviceList) {
    String[] theList = new String[deviceList.size()];
    int i = 0;
    for (DeviceDescriptor device : deviceList) {
        theList[i] = device.getId();
        i++;
    }
    GroupResponse theResponse = new GroupResponse();
    theResponse.setAction(DeviceState.createDeviceState());
    theResponse.setName("Lightset 0");
    theResponse.setLights(theList);
    return theResponse;
}
Example 72
Project: spork-streaming-master  File: UnionConverter.java View source code
@Override
public JavaDStream<Tuple> convert(List<JavaDStream<Tuple>> predecessors, POUnion physicalOperator) throws IOException {
    SparkUtil.assertPredecessorSizeGreaterThan(predecessors, physicalOperator, 0);
    JavaDStream<Tuple> unionDStream = sc.union(predecessors.get(0), predecessors.subList(1, predecessors.size()));
    return unionDStream;
}
Example 73
Project: nmonvisualizer-master  File: FileHelper.java View source code
public static void recurseDirectories(File[] files, FileFilter filter, List<String> filenames) {
    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            recurseDirectories(files[i].listFiles(), filter, filenames);
        } else {
            if (filter.accept(files[i])) {
                filenames.add(files[i].getAbsolutePath());
            }
        }
    }
}
Example 74
Project: pmd-eclipse-plugin-master  File: RuleSetExcludeIncludePatternContentProvider.java View source code
/**
	 * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(Object)
	 */
public RuleSetExcludeIncludePattern[] getElements(Object inputElement) {
    if (inputElement instanceof RuleSet) {
        RuleSet ruleSet = (RuleSet) inputElement;
        List<String> patterns = exclude ? ruleSet.getExcludePatterns() : ruleSet.getIncludePatterns();
        RuleSetExcludeIncludePattern[] patternList = new RuleSetExcludeIncludePattern[patterns.size()];
        for (int i = 0; i < patternList.length; i++) {
            patternList[i] = new RuleSetExcludeIncludePattern(ruleSet, exclude, i);
        }
        return patternList;
    }
    return emptyRuleSetPattern;
}
Example 75
Project: substeps-eclipse-plugin-master  File: SubstepHoverModel.java View source code
private static String getStepsAsString(final List<Step> steps) {
    final StringBuilder sb = new StringBuilder();
    for (final Step step : steps) {
        sb.append("\t");
        sb.append(step.getLine());
        sb.append("\n");
    }
    return sb.toString();
}
Example 76
Project: quickml-master  File: ClassifiersTest.java View source code
public void getOptimizedDownsampledRandomForestIntegrationTest() throws Exception {
    double fractionOfDataForValidation = .2;
    int rebuildsPerValidation = 1;
    List<ClassifierInstance> trainingData = getAdvertisingInstances().subList(0, 3000);
    OnespotDateTimeExtractor dateTimeExtractor = new OnespotDateTimeExtractor();
    Pair<Map<String, Serializable>, DownsamplingClassifier> downsamplingClassifierPair = Classifiers.<ClassifierInstance>getOptimizedDownsampledRandomForest(trainingData, rebuildsPerValidation, fractionOfDataForValidation, new WeightedAUCCrossValLossFunction(1.0), dateTimeExtractor);
    logger.info("logged weighted auc loss should be between 0.25 and 0.28");
}
Example 77
Project: nubes-master  File: AcceptLanguageLocaleResolver.java View source code
@Override
public Locale resolve(RoutingContext context, List<Locale> availableLocales) {
    String accept = context.request().getHeader(ACCEPT_LANGUAGE.toString());
    if (accept == null) {
        return null;
    }
    List<LanguageRange> ranges = LanguageRange.parse(accept);
    if (ranges.isEmpty()) {
        return null;
    }
    return Locale.lookup(ranges, availableLocales);
}
Example 78
Project: eclipse.jdt.ui-master  File: ModifierCorrectionsQuickFixTest17.java View source code
public void testAddSafeVarargs1() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("p", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package p;\n");
    buf.append("import java.util.List;\n");
    buf.append("public class E {\n");
    buf.append("    public static <T> List<T> asList(T ... a) {\n");
    buf.append("        return null;\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
    CompilationUnit astRoot = getASTRoot(cu);
    ArrayList<IJavaCompletionProposal> proposals = collectCorrections(cu, astRoot);
    assertCorrectLabels(proposals);
    assertNumberOfProposals(proposals, 4);
    String[] expected = new String[1];
    buf = new StringBuffer();
    buf.append("package p;\n");
    buf.append("import java.util.List;\n");
    buf.append("public class E {\n");
    buf.append("    @SafeVarargs\n");
    buf.append("    public static <T> List<T> asList(T ... a) {\n");
    buf.append("        return null;\n");
    buf.append("    }\n");
    buf.append("}\n");
    expected[0] = buf.toString();
    assertExpectedExistInProposals(proposals, expected);
}
Example 79
Project: bigtable-sql-master  File: ArtifactDownloaderFactoryImpl.java View source code
/**
	 * @see net.sourceforge.squirrel_sql.client.update.downloader.ArtifactDownloaderFactory#create(java.util.List)
	 */
public ArtifactDownloader create(List<ArtifactStatus> artifactStatus) {
    Utilities.checkNull("create", "artifactStatus", artifactStatus);
    if (artifactStatus.size() == 0) {
        throw new IllegalArgumentException("create: list parameter must have one or more artifacts");
    }
    return new ArtifactDownloaderImpl(artifactStatus);
}
Example 80
Project: deep-spark-master  File: IncreaseCountersQueryBuilder.java View source code
/*
     * (non-Javadoc)
     * 
     * @see com.stratio.deep.commons.querybuilder.QueryBuilder#prepareBatchQuery(java.util.List)
     */
@Override
public String prepareBatchQuery(List<String> statements) {
    StringBuilder sb = new StringBuilder("BEGIN COUNTER BATCH\n");
    for (String statement : statements) {
        sb.append(statement).append("\n");
    }
    sb.append(" APPLY BATCH;");
    return sb.toString();
}
Example 81
Project: cloudtm-data-platform-master  File: FenixCheckDisconnectedReportGenerator.java View source code
@Override
protected void generateCheckDisconnected(DomainClass domClass, PrintWriter out) {
    newline(out);
    printMethod(out, "protected", "boolean", "checkDisconnected");
    startMethodBody(out);
    println(out, "java.util.List<String> relationList = new java.util.ArrayList<String>();");
    println(out, "boolean result = checkDisconnected(relationList);");
    println(out, "doCheckDisconnectedAction(relationList);");
    println(out, "return result;");
    endMethodBody(out);
    newline(out);
    printMethod(out, "protected", "boolean", "checkDisconnected", "java.util.List connectedRelationList");
    startMethodBody(out);
    if (domClass.hasSuperclass()) {
        println(out, "super.checkDisconnected(connectedRelationList);");
    }
    Iterator<Role> roleSlotsIter = domClass.getRoleSlots();
    while (roleSlotsIter.hasNext()) {
        Role role = roleSlotsIter.next();
        if (role.getName() != null) {
            onNewline(out);
            print(out, "if (");
            if (role.getMultiplicityUpper() == 1) {
                print(out, "has");
            } else {
                print(out, "hasAny");
            }
            print(out, capitalize(role.getName()));
            println(out, String.format("()) connectedRelationList.add(\"%s\"); ", role.getName()));
        }
    }
    println(out, "return connectedRelationList.isEmpty();");
    endMethodBody(out);
}
Example 82
Project: cdt-tests-runner-master  File: WinCLIInfoSharedLibraryInfo.java View source code
/* (non-Javadoc)
	 * @see org.eclipse.cdt.debug.mi.core.output.CLIInfoSharedLibraryInfo#parseShared(java.lang.String, java.util.List)
	 */
protected void parseShared(String str, List aList) {
    // skip the header (DLL   Name)
    if (//$NON-NLS-1$
    !str.startsWith("DLL")) {
        //$NON-NLS-1$
        String from = "";
        //$NON-NLS-1$
        String to = "";
        boolean syms = true;
        int index = str.lastIndexOf(' ');
        if (index > 0) {
            String sub = str.substring(index).trim();
            // Go figure they do not print the "0x" to indicate hexadecimal!!
            if (//$NON-NLS-1$
            !sub.startsWith("0x")) {
                //$NON-NLS-1$
                sub = "0x" + sub;
            }
            from = sub;
            str = str.substring(0, index).trim();
        }
        MIShared s = new MIShared(from, to, syms, str.trim());
        aList.add(s);
    }
}
Example 83
Project: tapestry-model-master  File: SearchableHibernateGridDataSourceProvider.java View source code
@Override
public GridDataSource createGridDataSource(Class entityType, Map<TynamoPropertyDescriptor, SearchFilterPredicate> propertySearchFilterMap, List<TynamoPropertyDescriptor> searchablePropertyDescriptors, String searchString) {
    java.util.List<String> fieldNames = new ArrayList<String>();
    for (TynamoPropertyDescriptor propertyDescriptor : searchablePropertyDescriptors) {
        fieldNames.add(propertyDescriptor.getName());
    }
    // don't bother with a text query if there are no @Fields
    if (fieldNames.size() <= 0)
        return createGridDataSource(entityType);
    MultiFieldQueryParser parser = new MultiFieldQueryParser(fieldNames.toArray(new String[fieldNames.size()]), new StandardAnalyzer(Version.LUCENE_4_10_2));
    // required
    try {
        return new SearchableHibernateGridDataSource(session, entityType, session.createFullTextQuery(parser.parse(searchString), entityType), propertySearchFilterMap);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}
Example 84
Project: platform_tools_motodev-master  File: AllDensitiesSupportCondition.java View source code
/**
     * @see com.motorolamobility.preflighting.core.checker.condition.Condition#execute(com.motorolamobility.preflighting.core.applicationdata.ApplicationData, java.util.List, com.motorolamobility.preflighting.core.validation.ValidationManagerConfiguration, com.motorolamobility.preflighting.core.validation.ValidationResult)
     */
@Override
public void execute(ApplicationData data, List<DeviceSpecification> deviceSpecs, ValidationManagerConfiguration valManagerConfig, ValidationResult results) throws PreflightingCheckerException {
    // First we need to check if this test is valid at all.
    // If the minSdkVersion is 3 (or lower) or the <supports-screen> tag does not exit, return an OK result.
    MissingDrawableChecker checker;
    if (getChecker() instanceof MissingDrawableChecker) {
        checker = (MissingDrawableChecker) getChecker();
        missingDrawableData = checker.getMissingDrawableData();
        if (missingDrawableData.isTestApplicable()) {
            generateResults(results, valManagerConfig);
        }
    }
}
Example 85
Project: jlibs-master  File: SelectColumnMethod.java View source code
private ColumnProperty getColumn() {
    String columnProp = ModelUtil.getAnnotationValue(method, mirror, "column");
    if (columnProp.length() > 0) {
        ColumnProperty column = columns.findByProperty(columnProp);
        if (column == null)
            throw new AnnotationError(method, "invalid column property: " + columnProp);
        return column;
    } else {
        ColumnProperty column = new ColumnProperty<ExecutableElement>(method, mirror) {

            @Override
            public String columnName() {
                String value = ModelUtil.getAnnotationValue(method, mirror, "expression");
                return replacePropertiesWithColumns(value);
            }

            @Override
            public String columnName(boolean quoted) {
                return '"' + columnName() + '"';
            }

            @Override
            public String propertyName() {
                return "__value";
            }

            @Override
            public TypeMirror propertyType() {
                TypeMirror returnType = method.getReturnType();
                String s = ModelUtil.toString(returnType, false);
                if (s.startsWith("java.util.List<"))
                    return ((List<? extends TypeMirror>) ((DeclaredType) returnType).getTypeArguments()).get(0);
                else if (s.equals("java.util.List"))
                    throw new AnnotationError(method, "the type of elements in returning List must be specified using Generics.");
                return returnType;
            }

            @Override
            public String getPropertyCode(String object) {
                throw new UnsupportedOperationException();
            }

            @Override
            public String setPropertyCode(String object, String value) {
                throw new UnsupportedOperationException();
            }

            @Override
            protected AnnotationMirror typeMapperMirror() {
                return null;
            }
        };
        column.validateType();
        return column;
    }
}
Example 86
Project: pcgen-master  File: DefaultListFacadeTest.java View source code
/**
	 * Test method for [email protected] pcgen.core.facade.util.DefaultListFacade#updateContents(java.util.List)}.
	 */
@Test
public void testUpdateContents() {
    TestListener listener = new TestListener();
    DefaultListFacade<String> theList = new DefaultListFacade<>(Arrays.asList("A", "B", "C", "E"));
    theList.addListListener(listener);
    List<String> newElements = Arrays.asList("A", "C", "D", "E");
    theList.updateContents(newElements);
    assertEquals("Lists have not been made the same", newElements, theList.getContents());
    assertEquals("Incorrect number of adds", 1, listener.addCount);
    assertEquals("Incorrect number of removes", 1, listener.removeCount);
    assertEquals("Incorrect number of changes", 0, listener.changeCount);
    assertEquals("Incorrect number of modifies", 0, listener.modifyCount);
}
Example 87
Project: Payara-master  File: ResourceHandlers.java View source code
/*
     * This handler takes in a list of rows, there should be 'Enabled' attribute in each row.
     * Get the resource-ref of this resource and do a logical And with this Enabled attribute
     * to get the real status
     */
@Handler(id = "gf.getResourceRealStatus", input = { @HandlerInput(name = "endpoint", type = String.class), @HandlerInput(name = "rows", type = java.util.List.class, required = true) }, output = { @HandlerOutput(name = "result", type = List.class) })
public static void getResourceRealStatus(HandlerContext handlerCtx) {
    List<Map> rows = (List) handlerCtx.getInputValue("rows");
    Map<String, String> targetsMap = new HashMap<String, String>();
    for (Map oneRow : rows) {
        try {
            String name = (String) oneRow.get("name");
            String encodedName = URLEncoder.encode(name, "UTF-8");
            List<String> targets = DeployUtil.getApplicationTarget(name, "resource-ref");
            if (targets.size() == 0) {
                //The resource is only created on domain, no source-ref exists.
                continue;
            }
            String enabledStr = DeployUtil.getTargetEnableInfo(encodedName, false, false);
            List<String> targetUrls = new ArrayList<String>();
            for (String target : targets) {
                if (TargetUtil.isCluster(target)) {
                    targetsMap.put(GuiUtil.getSessionValue("REST_URL") + "/clusters/cluster/" + target, target);
                    targetUrls.add(GuiUtil.getSessionValue("REST_URL") + "/clusters/cluster/" + target);
                } else {
                    targetsMap.put(GuiUtil.getSessionValue("REST_URL") + "/servers/server/" + target, target);
                    targetUrls.add(GuiUtil.getSessionValue("REST_URL") + "/servers/server/" + target);
                }
            }
            oneRow.put("targetUrls", targetUrls);
            oneRow.put("targetsMap", targetsMap);
            oneRow.put("enabled", enabledStr);
        } catch (Exception ex) {
            GuiUtil.handleException(handlerCtx, ex);
        }
    }
    handlerCtx.setOutputValue("result", rows);
}
Example 88
Project: geotools-old-master  File: JTSGeometryFactory.java View source code
/**
     * @inheritDoc
     * @see org.opengis.geometry.coordinate.Factory#createLineString(java.util.List)
     */
public LineString createLineString(final List /*<Position>*/
points) {
    LineString result = new LineStringImpl();
    PointArray pa = result.getControlPoints();
    List list = pa;
    Iterator it = points.iterator();
    while (it.hasNext()) {
        //            Object o = it.next();
        //            if (o instanceof DirectPosition) {
        //                list.add(o);
        //            } else if (o instanceof Position) {
        //                Position p = (Position) o;
        //                DirectPosition dp = p.getDirectPosition();
        //                /*if (dp == null) {
        //                    dp = p.getIndirect().getDirectPosition();
        //                }*/
        //                list.add(dp);
        //            }
        Position position = (Position) it.next();
        DirectPosition directPosition = position.getDirectPosition();
        list.add(directPosition);
    }
    return result;
}
Example 89
Project: framework-master  File: MSSQLGenerator.java View source code
/*
     * (non-Javadoc)
     *
     * @see com.vaadin.addon.sqlcontainer.query.generator.DefaultSQLGenerator#
     * generateSelectQuery(java.lang.String, java.util.List,
     * com.vaadin.addon.sqlcontainer.query.FilteringMode, java.util.List, int,
     * int, java.lang.String)
     */
@Override
public StatementHelper generateSelectQuery(String tableName, List<Filter> filters, List<OrderBy> orderBys, int offset, int pagelength, String toSelect) {
    if (tableName == null || tableName.trim().equals("")) {
        throw new IllegalArgumentException("Table name must be given.");
    }
    /* Adjust offset and page length parameters to match "row numbers" */
    offset = pagelength > 1 ? ++offset : offset;
    pagelength = pagelength > 1 ? --pagelength : pagelength;
    toSelect = toSelect == null ? "*" : toSelect;
    StatementHelper sh = getStatementHelper();
    StringBuffer query = new StringBuffer();
    /* Row count request is handled here */
    if ("COUNT(*)".equalsIgnoreCase(toSelect)) {
        query.append(String.format("SELECT COUNT(*) AS %s FROM (SELECT * FROM %s", QueryBuilder.quote("rowcount"), tableName));
        if (filters != null && !filters.isEmpty()) {
            query.append(QueryBuilder.getWhereStringForFilters(filters, sh));
        }
        query.append(") AS t");
        sh.setQueryString(query.toString());
        return sh;
    }
    /* SELECT without row number constraints */
    if (offset == 0 && pagelength == 0) {
        query.append("SELECT ").append(toSelect).append(" FROM ").append(tableName);
        if (filters != null) {
            query.append(QueryBuilder.getWhereStringForFilters(filters, sh));
        }
        if (orderBys != null) {
            for (OrderBy o : orderBys) {
                generateOrderBy(query, o, orderBys.indexOf(o) == 0);
            }
        }
        sh.setQueryString(query.toString());
        return sh;
    }
    /* Remaining SELECT cases are handled here */
    query.append("SELECT * FROM (SELECT row_number() OVER (");
    if (orderBys != null) {
        for (OrderBy o : orderBys) {
            generateOrderBy(query, o, orderBys.indexOf(o) == 0);
        }
    }
    query.append(") AS rownum, " + toSelect + " FROM ").append(tableName);
    if (filters != null) {
        query.append(QueryBuilder.getWhereStringForFilters(filters, sh));
    }
    query.append(") AS a WHERE a.rownum BETWEEN ").append(offset).append(" AND ").append(Integer.toString(offset + pagelength));
    sh.setQueryString(query.toString());
    return sh;
}
Example 90
Project: cloudbees-api-client-master  File: CloudResourceProvider.java View source code
/**
     * Lists up all the cloud resources.
     */
public Iterator<CloudResource> iterator() {
    try {
        JsonNode res = getOwner().retrieve().get("resources");
        if (res == null || !res.isArray())
            throw new IllegalStateException("Expected a JSON array but " + getOwner() + " gave us " + res);
        ReferencedResource[] dto = CloudResource.MAPPER.readValue(res, ReferencedResource[].class);
        List<CloudResource> r = new ArrayList<CloudResource>(dto.length);
        for (ReferencedResource rr : dto) {
            r.add(rr.toCloudResource(getOwner()));
        }
        return r.iterator();
    } catch (IOException e) {
        throw new Error(e);
    }
}
Example 91
Project: sysart-itext-master  File: BookmarksTest.java View source code
@Test
public void testNoBreakSpace() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    writer.setPageEvent(new PdfPageEventHelper() {

        public void onParagraph(PdfWriter writer, Document document, float position) {
            PdfContentByte cb = writer.getDirectContent();
            PdfDestination destination = new PdfDestination(PdfDestination.FITH, position);
            new PdfOutline(cb.getRootOutline(), destination, TITLE);
        }
    });
    document.add(new Paragraph("Hello World"));
    document.close();
    // read bookmark back
    PdfReader r = new PdfReader(baos.toByteArray());
    List bookmarks = SimpleBookmark.getBookmark(r);
    assertEquals("bookmark size", 1, bookmarks.size());
    HashMap<String, Object> b = (HashMap<String, Object>) bookmarks.get(0);
    String title = (String) b.get("Title");
    assertEquals("bookmark title", TITLE, title);
}
Example 92
Project: R2015-master  File: TestMain.java View source code
public static void main(String[] args) {
    System.out.println("Hello");
    printArray(new int[] { 1, 2, 3 });
    List<String> li = new ArrayList<String>();
    for (int i = 0; i < 6; i++) {
        li.add("element " + i);
    }
    for (int count = 0; count < li.size(); count++) {
        System.out.println(count + " " + li.get(count));
    }
    li.remove(1);
    System.out.println("After 1st removal (element 1 removed) --------------------");
    for (int count = 0; count < li.size(); count++) {
        System.out.println(count + " " + li.get(count));
    }
    li.remove(3);
    System.out.println("After 2nd removal (element 3 (4 in original) removed) --------------------");
    for (int count = 0; count < li.size(); count++) {
        System.out.println(count + " " + li.get(count));
    }
    System.out.println(li.get(2));
}
Example 93
Project: Strata-master  File: MapTokenEvaluator.java View source code
@Override
public EvaluationResult evaluate(Map<?, ?> map, CalculationFunctions functions, String firstToken, List<String> remainingTokens) {
    return MapStream.of(map).filterKeys( key -> firstToken.equalsIgnoreCase(key.toString())).findFirst().map( e -> EvaluationResult.success(e.getValue(), remainingTokens)).orElse(invalidTokenFailure(map, firstToken));
}
Example 94
Project: dlna-master  File: FileFilterUtil.java View source code
public static List<File> getFiles(String path, String[] postfix) {
    File file = new File(path);
    File[] files = file.listFiles();
    List<File> lists = new ArrayList();
    if (files == null || files.length == 0) {
        return null;
    }
    for (int i = 0; i < files.length; i++) {
        File childFile = files[i];
        System.out.println("" + childFile.getPath());
        if (childFile.isFile()) {
            childFile.getName();
            int index = childFile.getName().lastIndexOf(".");
            index++;
            String name = childFile.getName().substring(index, childFile.getName().length());
            for (int j = 0; j < postfix.length; j++) {
                if (name.equalsIgnoreCase(postfix[j])) {
                    lists.add(childFile);
                }
            }
        } else if (childFile.isDirectory() && formateToDepth(childFile.getAbsolutePath())) {
            List<File> lsts = getFiles(childFile.getAbsolutePath(), postfix);
            if (lsts != null && lsts.size() != 0) {
                lists.addAll(lsts);
            }
        }
    }
    return lists;
}
Example 95
Project: oobd-master  File: JcaCRLStore.java View source code
private static Collection convertCRLs(Collection collection) throws CRLException {
    List list = new ArrayList(collection.size());
    for (Iterator it = collection.iterator(); it.hasNext(); ) {
        Object crl = it.next();
        if (crl instanceof X509CRL) {
            try {
                list.add(new X509CRLHolder(((X509CRL) crl).getEncoded()));
            } catch (IOException e) {
                throw new CRLException("cannot read encoding: " + e.getMessage());
            }
        } else {
            list.add((X509CRLHolder) crl);
        }
    }
    return list;
}
Example 96
Project: liferay-ide-master  File: FindJavaProblemsHandler.java View source code
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        Liferay7UpgradeAssistantSettings settings = UpgradeAssistantSettingsUtil.getObjectFromStore(Liferay7UpgradeAssistantSettings.class);
        String[] projectLocations = settings.getJavaProjectLocations();
        List<IPath> locations = new ArrayList<>();
        for (String projectLocation : projectLocations) {
            locations.add(new Path(projectLocation));
        }
        new MigrateProjectHandler().findMigrationProblems(locations.toArray(new IPath[0]));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 97
Project: bixie-master  File: TruePositives02.java View source code
public int getNewIndex(int index, List<Object> ints, List<Object> chars, List<Object> bytes, List<Object> booleans) {
    int max = 0;
    if (booleans.size() > 0 && index < 63)
        max = 64;
    else if (bytes.size() > 0 && index < 56)
        max = 57;
    else if (chars.size() > 0 && index < 48)
        max = 49;
    else if (ints.size() > 0 && index < 32)
        max = 33;
    if (max != 0) {
        int rand = getInt(4);
        max = max - index;
        // hence the line above always sets index to 1
        if (max > rand)
            max = rand;
        else if (max != 1)
            // unreachable
            max = getInt(max);
        index += max;
    }
    return index;
}
Example 98
Project: tr069-master  File: MessageListenerTask.java View source code
@Override
public void runImpl() throws Throwable {
    List<Message> messages = tr069ServerListenerInbox.getUnreadMessages();
    for (Message message : messages) {
        if (message.getMessageType().equals(Message.MTYPE_PUB_TR069_TEST_END) && message.getObjectType().equals(Message.OTYPE_UNIT)) {
            logger.debug("Message signals end to Test, remove TestUnit from TestUnitCahe (unitId: " + message.getObjectId() + ")");
            TestUnitCache.remove(message.getObjectId());
            message.setProcessed(true);
        }
    }
    tr069ServerListenerInbox.deleteReadMessage();
}
Example 99
Project: android_platform_libcore-master  File: nodeinsertbeforenewchildexists.java View source code
/**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
public void runTest() throws Throwable {
    Document doc;
    NodeList elementList;
    Node employeeNode;
    NodeList childList;
    Node refChild;
    Node newChild;
    Node child;
    int length;
    String childName;
    Node insertedNode;
    java.util.List expectedWhitespace = new java.util.ArrayList();
    expectedWhitespace.add("#text");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("name");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("position");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("salary");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("gender");
    expectedWhitespace.add("#text");
    expectedWhitespace.add("employeeId");
    expectedWhitespace.add("address");
    expectedWhitespace.add("#text");
    java.util.List expectedNoWhitespace = new java.util.ArrayList();
    expectedNoWhitespace.add("name");
    expectedNoWhitespace.add("position");
    expectedNoWhitespace.add("salary");
    expectedNoWhitespace.add("gender");
    expectedNoWhitespace.add("employeeId");
    expectedNoWhitespace.add("address");
    java.util.List expected = new java.util.ArrayList();
    java.util.List result = new java.util.ArrayList();
    doc = (Document) load("staff", true);
    elementList = doc.getElementsByTagName("employee");
    employeeNode = elementList.item(1);
    childList = employeeNode.getChildNodes();
    length = (int) childList.getLength();
    if (equals(6, length)) {
        expected = expectedNoWhitespace;
        refChild = childList.item(5);
        newChild = childList.item(0);
    } else {
        expected = expectedWhitespace;
        refChild = childList.item(11);
        newChild = childList.item(1);
    }
    insertedNode = employeeNode.insertBefore(newChild, refChild);
    for (int indexN100DD = 0; indexN100DD < childList.getLength(); indexN100DD++) {
        child = (Node) childList.item(indexN100DD);
        childName = child.getNodeName();
        result.add(childName);
    }
    assertEquals("childNames", expected, result);
}
Example 100
Project: jdroid-master  File: SampleSearchUseCase.java View source code
@Override
protected PagedResult<String> doSearch(String searchValue, int page, int pageSize, SortingType sortingType) {
    List<String> pagedResults = Lists.newArrayList();
    Boolean isLastPage = false;
    int from = (page - 1) * pageSize;
    int to = from + pageSize;
    if (to >= results.size()) {
        to = results.size();
        isLastPage = true;
    }
    for (String each : results.subList(from, to)) {
        if (each.contains(searchValue)) {
            pagedResults.add(each);
        }
    }
    PagedResult<String> pagedResult = new PagedResult<>(pagedResults, isLastPage);
    ExecutorUtils.sleep(5);
    return pagedResult;
}
Example 101
Project: csrf-jhipster-master  File: CustomAuditEventRepository.java View source code
@Override
public List<AuditEvent> find(String principal, Date after) {
    final List<PersistentAuditEvent> persistentAuditEvents;
    if (principal == null && after == null) {
        persistentAuditEvents = persistenceAuditEventRepository.findAll();
    } else if (after == null) {
        persistentAuditEvents = persistenceAuditEventRepository.findByPrincipal(principal);
    } else {
        persistentAuditEvents = persistenceAuditEventRepository.findByPrincipalAndAuditEventDateGreaterThan(principal, new LocalDateTime(after));
    }
    return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
}