Java Examples for org.apache.tools.ant.types.Path

The following java examples will help you to understand the usage of org.apache.tools.ant.types.Path. These source code samples are taken from different open source projects.

Example 1
Project: android-platform-tools-base-master  File: AaptExecTask.java View source code
/**
     * Sets the value of the "resources" attribute.
     * @param resources the value.
     *
     * @deprecated Use nested element(s) <res path="value" />
     */
@Deprecated
public void setResources(Path resources) {
    System.out.println("WARNNG: Using deprecated 'resources' attribute in AaptExecLoopTask." + "Use nested element(s) <res path=\"value\" /> instead.");
    if (mResources == null) {
        mResources = new ArrayList<Path>();
    }
    mResources.add(new Path(getProject(), resources.toString()));
}
Example 2
Project: crux-master  File: SchemaGeneratorTask.java View source code
/**
	 * Compile files using GWT compiler
	 * @param file
	 * @throws Exception
	 */
protected void generateSchemas(File baseDir) throws Exception {
    log("Generating Schemas to: " + baseDir.getCanonicalPath() + "/" + outputDir);
    Java javatask = (Java) getProject().createTask("java");
    javatask.setClassname(SchemaGenerator.class.getName());
    javatask.setFork(true);
    javatask.createJvmarg().setValue("-Dfile.encoding=" + this.inputCharset);
    for (Argument arg : jvmArgs) {
        if (arg != null) {
            javatask.createJvmarg().setValue(arg.getParts()[0]);
        }
    }
    javatask.createArg().setValue(baseDir.getCanonicalPath());
    javatask.createArg().setValue(outputDir.getCanonicalPath());
    javatask.createArg().setValue("-generateDoc");
    addCompilerParameters(javatask);
    for (Path path : this.classpath) {
        javatask.setClasspath(path);
    }
    int resultCode = javatask.executeJava();
    if (resultCode != 0) {
        log("Error generating schemas.", 1);
    }
}
Example 3
Project: mkgmap-master  File: MKGMapTask.java View source code
public void execute() {
    List<String> args = new ArrayList<String>();
    try {
        CommandArgsReader argsReader = new CommandArgsReader(new Main());
        if (configFile != null)
            args.add("--read-config=" + configFile);
        for (Path path : paths) {
            String[] includedFiles = path.list();
            for (String filename : includedFiles) {
                log("processing " + filename);
                args.add("--input-file=" + filename);
            }
        }
        argsReader.readArgs(args.toArray(new String[args.size()]));
    } catch (Exception ex) {
        throw new BuildException(ex);
    }
}
Example 4
Project: eclipse.jdt.core-master  File: JDTCompilerAdapter.java View source code
protected Commandline setupJavacCommand() throws BuildException {
    Commandline cmd = new Commandline();
    this.customDefaultOptions = new CompilerOptions().getMap();
    Class javacClass = Javac.class;
    String[] compilerArgs = processCompilerArguments(javacClass);
    cmd.createArgument().setValue("-noExit");
    if (this.bootclasspath != null) {
        cmd.createArgument().setValue("-bootclasspath");
        if (this.bootclasspath.size() != 0) {
            cmd.createArgument().setPath(this.bootclasspath);
        } else {
            cmd.createArgument().setValue(Util.EMPTY_STRING);
        }
    }
    if (this.extdirs != null) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-extdirs");
        cmd.createArgument().setPath(this.extdirs);
    }
    Path classpath = new Path(this.project);
    /*
		 * The java runtime is already handled, so we simply want to retrieve the
		 * ant runtime and the compile classpath.
		 */
    classpath.append(getCompileClasspath());
    /*
		 * Set the classpath for the Eclipse compiler.
		 */
    //$NON-NLS-1$
    cmd.createArgument().setValue("-classpath");
    createClasspathArgument(cmd, classpath);
    // For -sourcepath, use the "sourcepath" value if present.
    // Otherwise default to the "srcdir" value.
    Path sourcepath = null;
    // retrieve the method getSourcepath() using reflect
    // This is done to improve the compatibility to ant 1.5
    Method getSourcepathMethod = null;
    try {
        //$NON-NLS-1$
        getSourcepathMethod = javacClass.getMethod("getSourcepath", (Class[]) null);
    } catch (NoSuchMethodException e) {
    }
    Path compileSourcePath = null;
    if (getSourcepathMethod != null) {
        try {
            compileSourcePath = (Path) getSourcepathMethod.invoke(this.attributes, (Object[]) null);
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }
    }
    if (compileSourcePath != null) {
        sourcepath = compileSourcePath;
    } else {
        sourcepath = this.src;
    }
    //$NON-NLS-1$
    cmd.createArgument().setValue("-sourcepath");
    createClasspathArgument(cmd, sourcepath);
    final String javaVersion = JavaEnvUtils.getJavaVersion();
    //$NON-NLS-1$//$NON-NLS-2$
    String memoryParameterPrefix = javaVersion.equals(JavaEnvUtils.JAVA_1_1) ? "-J-" : "-J-X";
    if (this.memoryInitialSize != null) {
        if (!this.attributes.isForkedJavac()) {
            //$NON-NLS-1$
            this.attributes.log(//$NON-NLS-1$
            AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryInitialSize"), //$NON-NLS-1$
            Project.MSG_WARN);
        } else {
            cmd.createArgument().setValue(memoryParameterPrefix + "ms" + //$NON-NLS-1$
            this.memoryInitialSize);
        }
    }
    if (this.memoryMaximumSize != null) {
        if (!this.attributes.isForkedJavac()) {
            //$NON-NLS-1$
            this.attributes.log(//$NON-NLS-1$
            AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryMaximumSize"), //$NON-NLS-1$
            Project.MSG_WARN);
        } else {
            cmd.createArgument().setValue(memoryParameterPrefix + "mx" + //$NON-NLS-1$
            this.memoryMaximumSize);
        }
    }
    if (this.debug) {
        // retrieve the method getSourcepath() using reflect
        // This is done to improve the compatibility to ant 1.5
        Method getDebugLevelMethod = null;
        try {
            getDebugLevelMethod = //$NON-NLS-1$
            javacClass.getMethod(//$NON-NLS-1$
            "getDebugLevel", //$NON-NLS-1$
            (Class[]) null);
        } catch (NoSuchMethodException e) {
        }
        String debugLevel = null;
        if (getDebugLevelMethod != null) {
            try {
                debugLevel = (String) getDebugLevelMethod.invoke(this.attributes, (Object[]) null);
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
        if (debugLevel != null) {
            this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE);
            if (debugLevel.length() != 0) {
                if (//$NON-NLS-1$
                debugLevel.indexOf("vars") != //$NON-NLS-1$
                -1) {
                    this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
                }
                if (//$NON-NLS-1$
                debugLevel.indexOf("lines") != //$NON-NLS-1$
                -1) {
                    this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
                }
                if (//$NON-NLS-1$
                debugLevel.indexOf("source") != //$NON-NLS-1$
                -1) {
                    this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
                }
            }
        } else {
            this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
        }
    } else {
        this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE);
        this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE);
        this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE);
    }
    /*
		 * Handle the nowarn option. If none, then we generate all warnings.
		 */
    if (this.attributes.getNowarn()) {
        // disable all warnings
        Object[] entries = this.customDefaultOptions.entrySet().toArray();
        for (int i = 0, max = entries.length; i < max; i++) {
            Map.Entry entry = (Map.Entry) entries[i];
            if (!(entry.getKey() instanceof String))
                continue;
            if (!(entry.getValue() instanceof String))
                continue;
            if (((String) entry.getValue()).equals(CompilerOptions.WARNING)) {
                this.customDefaultOptions.put(entry.getKey(), CompilerOptions.IGNORE);
            }
        }
        this.customDefaultOptions.put(CompilerOptions.OPTION_TaskTags, Util.EMPTY_STRING);
        if (this.deprecation) {
            this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
            this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED);
            this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED);
        }
    } else if (this.deprecation) {
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED);
    } else {
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.DISABLED);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.DISABLED);
    }
    /*
		 * destDir option.
		 */
    if (this.destDir != null) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-d");
        cmd.createArgument().setFile(this.destDir.getAbsoluteFile());
    }
    /*
		 * verbose option
		 */
    if (this.verbose) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-verbose");
    }
    /*
		 * failnoerror option
		 */
    if (!this.attributes.getFailonerror()) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-proceedOnError");
    }
    /*
		 * target option.
		 */
    if (this.target != null) {
        this.customDefaultOptions.put(CompilerOptions.OPTION_TargetPlatform, this.target);
    }
    /*
		 * source option
		 */
    String source = this.attributes.getSource();
    if (source != null) {
        this.customDefaultOptions.put(CompilerOptions.OPTION_Source, source);
        this.customDefaultOptions.put(CompilerOptions.OPTION_Compliance, source);
    }
    if (compilerArgs != null) {
        /*
			 * Add extra argument on the command line
			 */
        final int length = compilerArgs.length;
        if (length != 0) {
            for (int i = 0, max = length; i < max; i++) {
                String arg = compilerArgs[i];
                if (//$NON-NLS-1$
                this.logFileName == null && "-log".equals(arg) && //$NON-NLS-1$
                ((i + 1) < max)) {
                    this.logFileName = compilerArgs[i + 1];
                }
                cmd.createArgument().setValue(arg);
            }
        }
    }
    /*
		 * encoding option. javac task encoding property must be the last encoding on the command
		 * line as compiler arg might also specify an encoding.
		 */
    if (this.encoding != null) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-encoding");
        cmd.createArgument().setValue(this.encoding);
    }
    /*
		 * Eclipse compiler doesn't have a -sourcepath option. This is
		 * handled through the javac task that collects all source files in
		 * srcdir option.
		 */
    logAndAddFilesToCompile(cmd);
    return cmd;
}
Example 5
Project: spring-framework-2.5.x-master  File: CommonsAttributeCompilerUtils.java View source code
public static void ideAttributeCompile(String testWildcards) {
    System.out.println("Compiling attributes under IDE");
    Project project = new Project();
    //URL markerUrl = CommonsAttributeCompilerUtils.class.getResource(MARKER_FILE);
    //File markerFile = new File(markerUrl.getFile());
    // we know marker is in /target/test-classes
    File root = new File("./");
    project.setBaseDir(root);
    project.init();
    AttributeCompiler commonsAttributesCompiler = new AttributeCompiler();
    commonsAttributesCompiler.setProject(project);
    //commonsAttributesCompiler.setSourcepathref("test");
    String tempPath = "target/generated-commons-attributes-src";
    commonsAttributesCompiler.setDestdir(new File(tempPath));
    FileSet fileset = new FileSet();
    fileset.setDir(new File(root.getPath() + File.separator + "test"));
    String attributeClasses = testWildcards;
    fileset.setIncludes(attributeClasses);
    commonsAttributesCompiler.addFileset(fileset);
    commonsAttributesCompiler.execute();
    System.out.println("Compiling Java sources generated by Commons Attributes using Javac: requires tools.jar on Eclipse project classpath");
    // We now have the generated Java source: compile it.
    // This requires Javac on the source path
    Javac javac = new Javac();
    javac.setProject(project);
    //project.setCoreLoader(Thread.currentThread().getContextClassLoader());
    Path path = new Path(project, tempPath);
    javac.setSrcdir(path);
    // Couldn't get this to work: trying to use Eclipse
    //javac.setCompiler("org.eclipse.jdt.core.JDTCompilerAdapter");
    File destDir = new File(root.getPath() + File.separator + "target/test-classes");
    if (!destDir.exists()) {
        destDir.mkdir();
    }
    javac.setDestdir(destDir);
    javac.setIncludes(attributeClasses);
    javac.execute();
}
Example 6
Project: WS171-development-master  File: SetupTask.java View source code
@Override
public void execute() throws BuildException {
    Project antProject = getProject();
    // get the SDK location
    String sdkLocation = antProject.getProperty(ProjectProperties.PROPERTY_SDK);
    // check if it's valid and exists
    if (sdkLocation == null || sdkLocation.length() == 0) {
        throw new BuildException("SDK Location is not set.");
    }
    File sdk = new File(sdkLocation);
    if (sdk.isDirectory() == false) {
        throw new BuildException(String.format("SDK Location '%s' is not valid.", sdkLocation));
    }
    // get the target property value
    String targetHashString = antProject.getProperty(ProjectProperties.PROPERTY_TARGET);
    if (targetHashString == null) {
        throw new BuildException("Android Target is not set.");
    }
    // load up the sdk targets.
    final ArrayList<String> messages = new ArrayList<String>();
    SdkManager manager = SdkManager.createManager(sdkLocation, new ISdkLog() {

        public void error(Throwable t, String errorFormat, Object... args) {
            if (errorFormat != null) {
                messages.add(String.format("Error: " + errorFormat, args));
            }
            if (t != null) {
                messages.add("Error: " + t.getMessage());
            }
        }

        public void printf(String msgFormat, Object... args) {
            messages.add(String.format(msgFormat, args));
        }

        public void warning(String warningFormat, Object... args) {
            messages.add(String.format("Warning: " + warningFormat, args));
        }
    });
    if (manager == null) {
        // since we failed to parse the SDK, lets display the parsing output.
        for (String msg : messages) {
            System.out.println(msg);
        }
        throw new BuildException("Failed to parse SDK content.");
    }
    // resolve it
    IAndroidTarget androidTarget = manager.getTargetFromHashString(targetHashString);
    if (androidTarget == null) {
        throw new BuildException(String.format("Unable to resolve target '%s'", targetHashString));
    }
    // display it
    System.out.println("Project Target: " + androidTarget.getName());
    if (androidTarget.isPlatform() == false) {
        System.out.println("Vendor: " + androidTarget.getVendor());
        System.out.println("Platform Version: " + androidTarget.getApiVersionName());
    }
    System.out.println("API level: " + androidTarget.getApiVersionNumber());
    // sets up the properties to find android.jar/framework.aidl/target tools
    String androidJar = androidTarget.getPath(IAndroidTarget.ANDROID_JAR);
    antProject.setProperty(PROPERTY_ANDROID_JAR, androidJar);
    antProject.setProperty(PROPERTY_ANDROID_AIDL, androidTarget.getPath(IAndroidTarget.ANDROID_AIDL));
    antProject.setProperty(PROPERTY_AAPT, androidTarget.getPath(IAndroidTarget.AAPT));
    antProject.setProperty(PROPERTY_AIDL, androidTarget.getPath(IAndroidTarget.AIDL));
    antProject.setProperty(PROPERTY_DX, androidTarget.getPath(IAndroidTarget.DX));
    // sets up the boot classpath
    // create the Path object
    Path bootclasspath = new Path(antProject);
    // create a PathElement for the framework jar
    PathElement element = bootclasspath.createPathElement();
    element.setPath(androidJar);
    // create PathElement for each optional library.
    IOptionalLibrary[] libraries = androidTarget.getOptionalLibraries();
    if (libraries != null) {
        HashSet<String> visitedJars = new HashSet<String>();
        for (IOptionalLibrary library : libraries) {
            String jarPath = library.getJarPath();
            if (visitedJars.contains(jarPath) == false) {
                visitedJars.add(jarPath);
                element = bootclasspath.createPathElement();
                element.setPath(library.getJarPath());
            }
        }
    }
    // finally sets the path in the project with a reference
    antProject.addReference(REF_CLASSPATH, bootclasspath);
    // find the file to import, and import it.
    String templateFolder = androidTarget.getPath(IAndroidTarget.TEMPLATES);
    // Now the import section. This is only executed if the task actually has to import a file.
    if (mDoImport) {
        // make sure the file exists.
        File templates = new File(templateFolder);
        if (templates.isDirectory() == false) {
            throw new BuildException(String.format("Template directory '%s' is missing.", templateFolder));
        }
        // now check the rules file exists.
        File rules = new File(templateFolder, ANDROID_RULES);
        if (rules.isFile() == false) {
            throw new BuildException(String.format("Build rules file '%s' is missing.", templateFolder));
        }
        // set the file location to import
        setFile(rules.getAbsolutePath());
        // and import
        super.execute();
    }
}
Example 7
Project: jaxws-master  File: WsTask2.java View source code
private void setupForkCommand(String className) {
    ClassLoader loader = this.getClass().getClassLoader();
    while (loader != null && !(loader instanceof AntClassLoader)) {
        loader = loader.getParent();
    }
    String antcp = loader != null ? //taskedef cp
    ((AntClassLoader) loader).getClasspath() : //system classloader, ie. env CLASSPATH=...
    System.getProperty("java.class.path");
    // try to find tools.jar and add it to the cp
    // so the behaviour on all JDKs is the same
    // (avoid creating MaskingClassLoader on non-Mac JDKs)
    File jreHome = new File(System.getProperty("java.home"));
    File toolsJar = new File(jreHome.getParent(), "lib/tools.jar");
    if (toolsJar.exists()) {
        antcp += File.pathSeparatorChar + toolsJar.getAbsolutePath();
    }
    getCommandline().createClasspath(getProject()).append(new Path(getProject(), antcp));
    /*
        * TODO JDK9
        String apiCp = getApiClassPath(this.getClass().getClassLoader());
        if (apiCp != null) {
            //TODO: jigsaw - Xbootclaspath may get deprecated/removed
            //and replaced with '-L' or '-m' options
            //see also: http://mail.openjdk.java.net/pipermail/jigsaw-dev/2010-April/000778.html
            getCommandline().createVmArgument().setLine("-Xbootclasspath/p:" + apiCp);
        }*/
    getCommandline().setClassname(className);
}
Example 8
Project: castor-master  File: AntJavaCompiler.java View source code
/**
     * Creates and returns a Ant Javac compiler.
     * @param srcDir Source directory for compiation.
     * @param destDir Destination directory for compilation.
     *
     * @return Ant Javac compiler
     */
private Javac makeCompiler(final File srcDir, final File destDir) {
    Project project = new Project();
    project.init();
    project.setBasedir(srcDir.getAbsolutePath());
    Javac compiler = new Javac();
    compiler.setProject(project);
    compiler.setDestdir(destDir.getAbsoluteFile());
    compiler.setOptimize(false);
    compiler.setDebug(true);
    compiler.setDebugLevel("lines,vars,source");
    compiler.setIncludejavaruntime(true);
    if (XMLTestCase._verbose) {
        compiler.setListfiles(true);
        compiler.setVerbose(true);
    } else {
        compiler.setNowarn(true);
    }
    if (_javaVersion != null) {
        compiler.setSource(_javaVersion);
    }
    Path classpath = compiler.createClasspath();
    classpath.setPath(System.getProperty("java.class.path"));
    classpath.add(new Path(project, destDir.getAbsolutePath()));
    compiler.setClasspath(classpath);
    return compiler;
}
Example 9
Project: CodingSpectator-master  File: JDTCompilerAdapter.java View source code
protected Commandline setupJavacCommand() throws BuildException {
    Commandline cmd = new Commandline();
    this.customDefaultOptions = new CompilerOptions().getMap();
    Class javacClass = Javac.class;
    String[] compilerArgs = processCompilerArguments(javacClass);
    cmd.createArgument().setValue("-noExit");
    if (this.bootclasspath != null) {
        cmd.createArgument().setValue("-bootclasspath");
        if (this.bootclasspath.size() != 0) {
            cmd.createArgument().setPath(this.bootclasspath);
        } else {
            cmd.createArgument().setValue(Util.EMPTY_STRING);
        }
    }
    Path classpath = new Path(this.project);
    if (this.extdirs != null) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-extdirs");
        cmd.createArgument().setPath(this.extdirs);
    }
    /*
		 * The java runtime is already handled, so we simply want to retrieve the
		 * ant runtime and the compile classpath.
		 */
    classpath.append(getCompileClasspath());
    // For -sourcepath, use the "sourcepath" value if present.
    // Otherwise default to the "srcdir" value.
    Path sourcepath = null;
    // retrieve the method getSourcepath() using reflect
    // This is done to improve the compatibility to ant 1.5
    Method getSourcepathMethod = null;
    try {
        //$NON-NLS-1$
        getSourcepathMethod = javacClass.getMethod("getSourcepath", null);
    } catch (NoSuchMethodException e) {
    }
    Path compileSourcePath = null;
    if (getSourcepathMethod != null) {
        try {
            compileSourcePath = (Path) getSourcepathMethod.invoke(this.attributes, null);
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }
    }
    if (compileSourcePath != null) {
        sourcepath = compileSourcePath;
    } else {
        sourcepath = this.src;
    }
    classpath.append(sourcepath);
    /*
		 * Set the classpath for the Eclipse compiler.
		 */
    //$NON-NLS-1$
    cmd.createArgument().setValue("-classpath");
    createClasspathArgument(cmd, classpath);
    final String javaVersion = JavaEnvUtils.getJavaVersion();
    //$NON-NLS-1$//$NON-NLS-2$
    String memoryParameterPrefix = javaVersion.equals(JavaEnvUtils.JAVA_1_1) ? "-J-" : "-J-X";
    if (this.memoryInitialSize != null) {
        if (!this.attributes.isForkedJavac()) {
            //$NON-NLS-1$
            this.attributes.log(//$NON-NLS-1$
            AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryInitialSize"), //$NON-NLS-1$
            Project.MSG_WARN);
        } else {
            cmd.createArgument().setValue(memoryParameterPrefix + "ms" + //$NON-NLS-1$
            this.memoryInitialSize);
        }
    }
    if (this.memoryMaximumSize != null) {
        if (!this.attributes.isForkedJavac()) {
            //$NON-NLS-1$
            this.attributes.log(//$NON-NLS-1$
            AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryMaximumSize"), //$NON-NLS-1$
            Project.MSG_WARN);
        } else {
            cmd.createArgument().setValue(memoryParameterPrefix + "mx" + //$NON-NLS-1$
            this.memoryMaximumSize);
        }
    }
    if (this.debug) {
        // retrieve the method getSourcepath() using reflect
        // This is done to improve the compatibility to ant 1.5
        Method getDebugLevelMethod = null;
        try {
            getDebugLevelMethod = //$NON-NLS-1$
            javacClass.getMethod(//$NON-NLS-1$
            "getDebugLevel", //$NON-NLS-1$
            null);
        } catch (NoSuchMethodException e) {
        }
        String debugLevel = null;
        if (getDebugLevelMethod != null) {
            try {
                debugLevel = (String) getDebugLevelMethod.invoke(this.attributes, null);
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
        if (debugLevel != null) {
            this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE);
            if (debugLevel.length() != 0) {
                if (//$NON-NLS-1$
                debugLevel.indexOf("vars") != //$NON-NLS-1$
                -1) {
                    this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
                }
                if (//$NON-NLS-1$
                debugLevel.indexOf("lines") != //$NON-NLS-1$
                -1) {
                    this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
                }
                if (//$NON-NLS-1$
                debugLevel.indexOf("source") != //$NON-NLS-1$
                -1) {
                    this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
                }
            }
        } else {
            this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
        }
    } else {
        this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE);
        this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE);
        this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE);
    }
    /*
		 * Handle the nowarn option. If none, then we generate all warnings.
		 */
    if (this.attributes.getNowarn()) {
        // disable all warnings
        Object[] entries = this.customDefaultOptions.entrySet().toArray();
        for (int i = 0, max = entries.length; i < max; i++) {
            Map.Entry entry = (Map.Entry) entries[i];
            if (!(entry.getKey() instanceof String))
                continue;
            if (!(entry.getValue() instanceof String))
                continue;
            if (((String) entry.getValue()).equals(CompilerOptions.WARNING)) {
                this.customDefaultOptions.put(entry.getKey(), CompilerOptions.IGNORE);
            }
        }
        this.customDefaultOptions.put(CompilerOptions.OPTION_TaskTags, Util.EMPTY_STRING);
        if (this.deprecation) {
            this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
            this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED);
            this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED);
        }
    } else if (this.deprecation) {
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED);
    } else {
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.DISABLED);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.DISABLED);
    }
    /*
		 * destDir option.
		 */
    if (this.destDir != null) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-d");
        cmd.createArgument().setFile(this.destDir.getAbsoluteFile());
    }
    /*
		 * verbose option
		 */
    if (this.verbose) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-verbose");
    }
    /*
		 * failnoerror option
		 */
    if (!this.attributes.getFailonerror()) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-proceedOnError");
    }
    /*
		 * target option.
		 */
    if (this.target != null) {
        this.customDefaultOptions.put(CompilerOptions.OPTION_TargetPlatform, this.target);
    }
    /*
		 * source option
		 */
    String source = this.attributes.getSource();
    if (source != null) {
        this.customDefaultOptions.put(CompilerOptions.OPTION_Source, source);
    }
    if (compilerArgs != null) {
        /*
			 * Add extra argument on the command line
			 */
        final int length = compilerArgs.length;
        if (length != 0) {
            for (int i = 0, max = length; i < max; i++) {
                String arg = compilerArgs[i];
                if (//$NON-NLS-1$
                this.logFileName == null && "-log".equals(arg) && //$NON-NLS-1$
                ((i + 1) < max)) {
                    this.logFileName = compilerArgs[i + 1];
                }
                cmd.createArgument().setValue(arg);
            }
        }
    }
    /*
		 * encoding option. javac task encoding property must be the last encoding on the command
		 * line as compiler arg might also specify an encoding.
		 */
    if (this.encoding != null) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-encoding");
        cmd.createArgument().setValue(this.encoding);
    }
    /*
		 * Eclipse compiler doesn't have a -sourcepath option. This is
		 * handled through the javac task that collects all source files in
		 * srcdir option.
		 */
    logAndAddFilesToCompile(cmd);
    return cmd;
}
Example 10
Project: eclipselink.runtime-master  File: StaticWeaveAntTask.java View source code
/**
     * Parse the class path element and store them into vector.
     */
private Vector getPathElement() {
    Vector pathElements = new Vector();
    for (int i = 0; i < classPaths.size(); i++) {
        String thisPath = ((Path) classPaths.get(i)).toString();
        if (thisPath != null) {
            String[] thisSplitedPath = thisPath.split(File.pathSeparator);
            if (thisSplitedPath != null) {
                for (int j = 0; j < thisSplitedPath.length; j++) {
                    pathElements.add(thisSplitedPath[j]);
                }
            }
        }
    }
    return pathElements;
}
Example 11
Project: core-android-master  File: StringEncrypt.java View source code
/**
	 * Entry point, per ogni file del path (passato come argomento nel
	 * build.xml) viene creato un file encoded con le stringhe cifrate. Al
	 * termine viene generato un file M.java con tutti i metodi relativi alle
	 * stringhe.
	 */
public void execute() {
    File userdir = new File(System.getProperty("user.dir"));
    String dir = userdir.toURI().getPath();
    logInfo("execute: " + dir, true);
    for (Iterator itPaths = paths.iterator(); itPaths.hasNext(); ) {
        Path path = (Path) itPaths.next();
        String[] includedFiles = path.list();
        for (int i = 0; i < includedFiles.length; i++) {
            URI fileUri = (new File(includedFiles[i])).toURI();
            String filename = fileUri.getPath().replace(dir + "/", "");
            File destfile = new File(destDir + "/" + filename.replace(baseDir, ""));
            logInfo("  encode: " + filename + " -> " + destfile);
            mkdir(destfile.getParent());
            try {
                // viene creato un nuovo file con la codifica delle stringhe
                encodeFile(filename, destfile.getAbsolutePath());
            } catch (IOException ex) {
                ex.printStackTrace();
                logInfo(ex.toString());
            }
        }
    }
    // logInfo("Decoding class: " + mFile);
    // istanza che si occupa di generare il file M.java
    DecodingClass dc = new DecodingClass(destDir + "/com/android/m/M.java", mFile);
    for (EncodedTuple tuple : encodedTuples) {
        dc.append(tuple.method, tuple.ebytes, tuple.kbytes);
    }
    dc.close();
}
Example 12
Project: Eclipse-Postfix-Code-Completion-master  File: JDTCompilerAdapter.java View source code
protected Commandline setupJavacCommand() throws BuildException {
    Commandline cmd = new Commandline();
    this.customDefaultOptions = new CompilerOptions().getMap();
    Class javacClass = Javac.class;
    String[] compilerArgs = processCompilerArguments(javacClass);
    cmd.createArgument().setValue("-noExit");
    if (this.bootclasspath != null) {
        cmd.createArgument().setValue("-bootclasspath");
        if (this.bootclasspath.size() != 0) {
            cmd.createArgument().setPath(this.bootclasspath);
        } else {
            cmd.createArgument().setValue(Util.EMPTY_STRING);
        }
    }
    if (this.extdirs != null) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-extdirs");
        cmd.createArgument().setPath(this.extdirs);
    }
    Path classpath = new Path(this.project);
    /*
		 * The java runtime is already handled, so we simply want to retrieve the
		 * ant runtime and the compile classpath.
		 */
    classpath.append(getCompileClasspath());
    /*
		 * Set the classpath for the Eclipse compiler.
		 */
    //$NON-NLS-1$
    cmd.createArgument().setValue("-classpath");
    createClasspathArgument(cmd, classpath);
    // For -sourcepath, use the "sourcepath" value if present.
    // Otherwise default to the "srcdir" value.
    Path sourcepath = null;
    // retrieve the method getSourcepath() using reflect
    // This is done to improve the compatibility to ant 1.5
    Method getSourcepathMethod = null;
    try {
        //$NON-NLS-1$
        getSourcepathMethod = javacClass.getMethod("getSourcepath", (Class[]) null);
    } catch (NoSuchMethodException e) {
    }
    Path compileSourcePath = null;
    if (getSourcepathMethod != null) {
        try {
            compileSourcePath = (Path) getSourcepathMethod.invoke(this.attributes, (Object[]) null);
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }
    }
    if (compileSourcePath != null) {
        sourcepath = compileSourcePath;
    } else {
        sourcepath = this.src;
    }
    //$NON-NLS-1$
    cmd.createArgument().setValue("-sourcepath");
    createClasspathArgument(cmd, sourcepath);
    final String javaVersion = JavaEnvUtils.getJavaVersion();
    //$NON-NLS-1$//$NON-NLS-2$
    String memoryParameterPrefix = javaVersion.equals(JavaEnvUtils.JAVA_1_1) ? "-J-" : "-J-X";
    if (this.memoryInitialSize != null) {
        if (!this.attributes.isForkedJavac()) {
            //$NON-NLS-1$
            this.attributes.log(//$NON-NLS-1$
            AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryInitialSize"), //$NON-NLS-1$
            Project.MSG_WARN);
        } else {
            cmd.createArgument().setValue(memoryParameterPrefix + "ms" + //$NON-NLS-1$
            this.memoryInitialSize);
        }
    }
    if (this.memoryMaximumSize != null) {
        if (!this.attributes.isForkedJavac()) {
            //$NON-NLS-1$
            this.attributes.log(//$NON-NLS-1$
            AntAdapterMessages.getString("ant.jdtadapter.info.ignoringMemoryMaximumSize"), //$NON-NLS-1$
            Project.MSG_WARN);
        } else {
            cmd.createArgument().setValue(memoryParameterPrefix + "mx" + //$NON-NLS-1$
            this.memoryMaximumSize);
        }
    }
    if (this.debug) {
        // retrieve the method getSourcepath() using reflect
        // This is done to improve the compatibility to ant 1.5
        Method getDebugLevelMethod = null;
        try {
            getDebugLevelMethod = //$NON-NLS-1$
            javacClass.getMethod(//$NON-NLS-1$
            "getDebugLevel", //$NON-NLS-1$
            (Class[]) null);
        } catch (NoSuchMethodException e) {
        }
        String debugLevel = null;
        if (getDebugLevelMethod != null) {
            try {
                debugLevel = (String) getDebugLevelMethod.invoke(this.attributes, (Object[]) null);
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
        if (debugLevel != null) {
            this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE);
            if (debugLevel.length() != 0) {
                if (//$NON-NLS-1$
                debugLevel.indexOf("vars") != //$NON-NLS-1$
                -1) {
                    this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
                }
                if (//$NON-NLS-1$
                debugLevel.indexOf("lines") != //$NON-NLS-1$
                -1) {
                    this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
                }
                if (//$NON-NLS-1$
                debugLevel.indexOf("source") != //$NON-NLS-1$
                -1) {
                    this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
                }
            }
        } else {
            this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
            this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
        }
    } else {
        this.customDefaultOptions.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE);
        this.customDefaultOptions.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE);
        this.customDefaultOptions.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE);
    }
    /*
		 * Handle the nowarn option. If none, then we generate all warnings.
		 */
    if (this.attributes.getNowarn()) {
        // disable all warnings
        Object[] entries = this.customDefaultOptions.entrySet().toArray();
        for (int i = 0, max = entries.length; i < max; i++) {
            Map.Entry entry = (Map.Entry) entries[i];
            if (!(entry.getKey() instanceof String))
                continue;
            if (!(entry.getValue() instanceof String))
                continue;
            if (((String) entry.getValue()).equals(CompilerOptions.WARNING)) {
                this.customDefaultOptions.put(entry.getKey(), CompilerOptions.IGNORE);
            }
        }
        this.customDefaultOptions.put(CompilerOptions.OPTION_TaskTags, Util.EMPTY_STRING);
        if (this.deprecation) {
            this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
            this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED);
            this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED);
        }
    } else if (this.deprecation) {
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.ENABLED);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.ENABLED);
    } else {
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode, CompilerOptions.DISABLED);
        this.customDefaultOptions.put(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod, CompilerOptions.DISABLED);
    }
    /*
		 * destDir option.
		 */
    if (this.destDir != null) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-d");
        cmd.createArgument().setFile(this.destDir.getAbsoluteFile());
    }
    /*
		 * verbose option
		 */
    if (this.verbose) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-verbose");
    }
    /*
		 * failnoerror option
		 */
    if (!this.attributes.getFailonerror()) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-proceedOnError");
    }
    /*
		 * target option.
		 */
    if (this.target != null) {
        this.customDefaultOptions.put(CompilerOptions.OPTION_TargetPlatform, this.target);
    }
    /*
		 * source option
		 */
    String source = this.attributes.getSource();
    if (source != null) {
        this.customDefaultOptions.put(CompilerOptions.OPTION_Source, source);
    }
    if (compilerArgs != null) {
        /*
			 * Add extra argument on the command line
			 */
        final int length = compilerArgs.length;
        if (length != 0) {
            for (int i = 0, max = length; i < max; i++) {
                String arg = compilerArgs[i];
                if (//$NON-NLS-1$
                this.logFileName == null && "-log".equals(arg) && //$NON-NLS-1$
                ((i + 1) < max)) {
                    this.logFileName = compilerArgs[i + 1];
                }
                cmd.createArgument().setValue(arg);
            }
        }
    }
    /*
		 * encoding option. javac task encoding property must be the last encoding on the command
		 * line as compiler arg might also specify an encoding.
		 */
    if (this.encoding != null) {
        //$NON-NLS-1$
        cmd.createArgument().setValue("-encoding");
        cmd.createArgument().setValue(this.encoding);
    }
    /*
		 * Eclipse compiler doesn't have a -sourcepath option. This is
		 * handled through the javac task that collects all source files in
		 * srcdir option.
		 */
    logAndAddFilesToCompile(cmd);
    return cmd;
}

Java Examples for org.apache.cordova.CordovaArgs

The following java examples will help you to understand the usage of org.apache.cordova.CordovaArgs. These source code samples are taken from different open source projects.

Example 1
Project: btpka3.github.com-master  File: MyCordovaPlugin.java View source code
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
    if ("add".equals(action)) {
        Log.e(TAG, "======== android : args = [" + args.getInt(0) + ", " + args.getInt(1) + "]");
        this.add(args.getInt(0), args.getInt(1), callbackContext);
        return true;
    }
    return false;
}
Example 2
Project: xface-android-master  File: PluginManager.java View source code
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
    if ("startup".equals(action)) {
        // The onPageStarted event of CordovaWebViewClient resets the queue of messages to be returned to javascript in response
        // to exec calls. Since this event occurs on the UI thread and exec calls happen on the WebCore thread it is possible
        // that onPageStarted occurs after exec calls have started happening on a new page, which can cause the message queue
        // to be reset between the queuing of a new message and its retrieval by javascript. To avoid this from happening,
        // javascript always sends a "startup" exec upon loading a new page which causes all future exec calls to happen on the UI
        // thread (and hence after onPageStarted) until there are no more pending exec calls remaining.
        numPendingUiExecs.getAndIncrement();
        ctx.getActivity().runOnUiThread(new Runnable() {

            public void run() {
                numPendingUiExecs.getAndDecrement();
            }
        });
        return true;
    }
    return false;
}
Example 3
Project: cordova-androidwear-master  File: AndroidWearPlugin.java View source code
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
    if (ACTION_ONCONNECT.equals(action))
        onConnect(args, callbackContext);
    else if (ACTION_ONDATARECEIVED.equals(action))
        onDataReceived(args, callbackContext);
    else if (ACTION_ONERROR.equals(action))
        onError(args, callbackContext);
    else if (ACTION_SENDDATA.equals(action))
        sendData(args, callbackContext);
    else
        return false;
    return true;
}
Example 4
Project: radioflow-master  File: InAppBrowser.java View source code
/**
     * Executes the request and returns PluginResult.
     *
     * @param action the action to execute.
     * @param args JSONArry of arguments for the plugin.
     * @param callbackContext the callbackContext used when calling back into JavaScript.
     * @return A PluginResult object with a status and message.
     */
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
    if (action.equals("open")) {
        this.callbackContext = callbackContext;
        final String url = args.getString(0);
        String t = args.optString(1);
        if (t == null || t.equals("") || t.equals(NULL)) {
            t = SELF;
        }
        final String target = t;
        final HashMap<String, Boolean> features = parseFeature(args.optString(2));
        LOG.d(LOG_TAG, "target = " + target);
        this.cordova.getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                String result = "";
                // SELF
                if (SELF.equals(target)) {
                    LOG.d(LOG_TAG, "in self");
                    /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
                         * Previously the Config class had a static method, isUrlWhitelisted(). That
                         * responsibility has been moved to the plugins, with an aggregating method in
                         * PluginManager.
                         */
                    Boolean shouldAllowNavigation = null;
                    if (url.startsWith("javascript:")) {
                        shouldAllowNavigation = true;
                    }
                    if (shouldAllowNavigation == null) {
                        try {
                            Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
                            shouldAllowNavigation = (Boolean) iuw.invoke(null, url);
                        } catch (NoSuchMethodException e) {
                            LOG.d(LOG_TAG, e.getLocalizedMessage());
                        } catch (IllegalAccessException e) {
                            LOG.d(LOG_TAG, e.getLocalizedMessage());
                        } catch (InvocationTargetException e) {
                            LOG.d(LOG_TAG, e.getLocalizedMessage());
                        }
                    }
                    if (shouldAllowNavigation == null) {
                        try {
                            Method gpm = webView.getClass().getMethod("getPluginManager");
                            PluginManager pm = (PluginManager) gpm.invoke(webView);
                            Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
                            shouldAllowNavigation = (Boolean) san.invoke(pm, url);
                        } catch (NoSuchMethodException e) {
                            LOG.d(LOG_TAG, e.getLocalizedMessage());
                        } catch (IllegalAccessException e) {
                            LOG.d(LOG_TAG, e.getLocalizedMessage());
                        } catch (InvocationTargetException e) {
                            LOG.d(LOG_TAG, e.getLocalizedMessage());
                        }
                    }
                    // load in webview
                    if (Boolean.TRUE.equals(shouldAllowNavigation)) {
                        LOG.d(LOG_TAG, "loading in webview");
                        webView.loadUrl(url);
                    } else //Load the dialer
                    if (url.startsWith(WebView.SCHEME_TEL)) {
                        try {
                            LOG.d(LOG_TAG, "loading in dialer");
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse(url));
                            cordova.getActivity().startActivity(intent);
                        } catch (android.content.ActivityNotFoundException e) {
                            LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
                        }
                    } else // load in InAppBrowser
                    {
                        LOG.d(LOG_TAG, "loading in InAppBrowser");
                        result = showWebPage(url, features);
                    }
                } else // SYSTEM
                if (SYSTEM.equals(target)) {
                    LOG.d(LOG_TAG, "in system");
                    result = openExternal(url);
                } else // BLANK - or anything else
                {
                    LOG.d(LOG_TAG, "in blank");
                    result = showWebPage(url, features);
                }
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        });
    } else if (action.equals("close")) {
        closeDialog();
    } else if (action.equals("injectScriptCode")) {
        String jsWrapper = null;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContext.getCallbackId());
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectScriptFile")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectStyleCode")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectStyleFile")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("show")) {
        this.cordova.getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                dialog.show();
            }
        });
        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
        pluginResult.setKeepCallback(true);
        this.callbackContext.sendPluginResult(pluginResult);
    } else {
        return false;
    }
    return true;
}
Example 5
Project: phonegap-geolocation-master  File: PluginManager.java View source code
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
    if ("startup".equals(action)) {
        // The onPageStarted event of CordovaWebViewClient resets the queue of messages to be returned to javascript in response
        // to exec calls. Since this event occurs on the UI thread and exec calls happen on the WebCore thread it is possible
        // that onPageStarted occurs after exec calls have started happening on a new page, which can cause the message queue
        // to be reset between the queuing of a new message and its retrieval by javascript. To avoid this from happening,
        // javascript always sends a "startup" exec upon loading a new page which causes all future exec calls to happen on the UI
        // thread (and hence after onPageStarted) until there are no more pending exec calls remaining.
        numPendingUiExecs.getAndIncrement();
        ctx.getActivity().runOnUiThread(new Runnable() {

            public void run() {
                numPendingUiExecs.getAndDecrement();
            }
        });
        return true;
    }
    return false;
}
Example 6
Project: Developing-with-Cordova-master  File: PluginManager.java View source code
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
    if ("startup".equals(action)) {
        // The onPageStarted event of CordovaWebViewClient resets the queue of messages to be returned to javascript in response
        // to exec calls. Since this event occurs on the UI thread and exec calls happen on the WebCore thread it is possible
        // that onPageStarted occurs after exec calls have started happening on a new page, which can cause the message queue
        // to be reset between the queuing of a new message and its retrieval by javascript. To avoid this from happening,
        // javascript always sends a "startup" exec upon loading a new page which causes all future exec calls to happen on the UI
        // thread (and hence after onPageStarted) until there are no more pending exec calls remaining.
        numPendingUiExecs.getAndIncrement();
        ctx.getActivity().runOnUiThread(new Runnable() {

            public void run() {
                numPendingUiExecs.getAndDecrement();
            }
        });
        return true;
    }
    return false;
}
Example 7
Project: pg-twit-master  File: PluginManager.java View source code
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
    if ("startup".equals(action)) {
        // The onPageStarted event of CordovaWebViewClient resets the queue of messages to be returned to javascript in response
        // to exec calls. Since this event occurs on the UI thread and exec calls happen on the WebCore thread it is possible
        // that onPageStarted occurs after exec calls have started happening on a new page, which can cause the message queue
        // to be reset between the queuing of a new message and its retrieval by javascript. To avoid this from happening,
        // javascript always sends a "startup" exec upon loading a new page which causes all future exec calls to happen on the UI
        // thread (and hence after onPageStarted) until there are no more pending exec calls remaining.
        numPendingUiExecs.getAndIncrement();
        ctx.getActivity().runOnUiThread(new Runnable() {

            public void run() {
                numPendingUiExecs.getAndDecrement();
            }
        });
        return true;
    }
    return false;
}

Java Examples for org.eclipse.emf.ecore.EEnum

The following java examples will help you to understand the usage of org.eclipse.emf.ecore.EEnum. These source code samples are taken from different open source projects.

Example 1
Project: extFM-Tooling-master  File: MtextCodeCompletionHelper.java View source code
public void run() {
    if (feature instanceof org.eclipse.emf.ecore.EReference) {
        org.eclipse.emf.ecore.EReference reference = (org.eclipse.emf.ecore.EReference) feature;
        if (featureType instanceof org.eclipse.emf.ecore.EClass) {
            if (reference.isContainment()) {
                // the FOLLOW set should contain only non-containment references
                assert false;
            } else {
                proposals.addAll(handleNCReference(expectedTerminal, container, reference, expectedTerminal.getPrefix(), expectedFeature.getTokenName()));
            }
        }
    } else if (feature instanceof org.eclipse.emf.ecore.EAttribute) {
        org.eclipse.emf.ecore.EAttribute attribute = (org.eclipse.emf.ecore.EAttribute) feature;
        if (featureType instanceof org.eclipse.emf.ecore.EEnum) {
            org.eclipse.emf.ecore.EEnum enumType = (org.eclipse.emf.ecore.EEnum) featureType;
            proposals.addAll(handleEnumAttribute(expectedTerminal, expectedFeature, enumType, expectedTerminal.getPrefix(), container));
        } else {
            // handle EAttributes (derive default value depending on the type of the
            // attribute, figure out token resolver, and call deResolve())
            proposals.addAll(handleAttribute(expectedTerminal, expectedFeature, container, attribute, expectedTerminal.getPrefix()));
        }
    } else {
        // there should be no other subclass of EStructuralFeature
        assert false;
    }
}
Example 2
Project: cdo-master  File: CDOServerBrowser.java View source code
protected String showPackage(InternalCDOPackageInfo info, InternalCDOPackageRegistry packageRegistry, CDOServerBrowser browser, String param, PrintStream out, String prefix) {
    EPackage ePackage = info.getEPackage();
    out.println("<h3>" + prefix + ePackage.getName() + "  [" + ePackage.getNsURI() + "]</h3>");
    for (EClassifier classifier : ePackage.getEClassifiers()) {
        String name = classifier.getName();
        if (param == null) {
            param = name;
        }
        String label = name.equals(param) ? name : browser.href(name, getName(), "classifier", name);
        out.print(prefix + "  <b>" + label);
        if (classifier instanceof EEnum) {
            EEnum eenum = (EEnum) classifier;
            out.print("  " + eenum.getELiterals());
        } else if (classifier instanceof EDataType) {
            EDataType eDataType = (EDataType) classifier;
            out.print("  " + eDataType.getInstanceClassName());
        }
        out.println("</b><br>");
    }
    for (EPackage sub : ePackage.getESubpackages()) {
        InternalCDOPackageInfo subInfo = packageRegistry.getPackageInfo(sub);
        param = showPackage(subInfo, packageRegistry, browser, param, out, prefix + "  ");
    }
    return param;
}
Example 3
Project: teiid-designer-master  File: EmfTestUtil.java View source code
/**
     * Builds a dummy model based on the library scenario, creating a resource set.
     * DOES NOT REQUIRE THE PLUGIN ENVIRONMENT TO CREATE THE RESOURCE SET
     * @param displayContents - if true, the model structure will be printed out to the console after it is built
     * @return ResourceSet - the dummy resource set.
     */
public static EPackage generateMetamodel(boolean displayContents) {
    //$NON-NLS-1$
    final String nsURI = "http://www.metamatrix.com/metabase/3.1/metamodels/Library.xml";
    //$NON-NLS-1$
    final String nsPrefix = "Library";
    // Create the package for the model
    //$NON-NLS-1$
    EPackage ePackage = createEPackage(null, "library", nsURI, nsPrefix);
    EPackage.Registry.INSTANCE.put(nsURI, ePackage);
    // Create necessary data types
    //$NON-NLS-1$
    EDataType myString = createEDataType(ePackage, "myString", java.lang.String.class);
    //$NON-NLS-1$
    EDataType myInt = createEDataType(ePackage, "myInt", java.lang.Integer.class);
    // Create classifiers for the model
    //$NON-NLS-1$
    EClass book = createEClass(ePackage, "Book", false, false);
    //$NON-NLS-1$
    EClass library = createEClass(ePackage, "Library", false, false);
    //$NON-NLS-1$
    EClass writer = createEClass(ePackage, "Writer", false, false);
    // Create enumeration for the model
    //$NON-NLS-1$
    EEnum bookCategory = createEEnum(ePackage, "BookCategory");
    // Create enumeration literals for the model
    //$NON-NLS-1$
    addEnumLiteral(bookCategory, createEnumLiteral("MYSTERY"));
    //$NON-NLS-1$
    addEnumLiteral(bookCategory, createEnumLiteral("SCIENCE_FICTION"));
    //$NON-NLS-1$
    addEnumLiteral(bookCategory, createEnumLiteral("BIOGRAPHY"));
    // Add the attributes to the book class
    //$NON-NLS-1$
    createEAttribute(book, "title", myString);
    //$NON-NLS-1$
    createEAttribute(book, "pages", myInt);
    //$NON-NLS-1$
    createEAttribute(book, "category", bookCategory);
    // Add the attributes to the writer class
    //$NON-NLS-1$
    createEAttribute(writer, "name", myString);
    // Add the attributes to the library class
    //$NON-NLS-1$
    createEAttribute(library, "name", myString);
    // Create a two-way reference between books and writers in which
    // a book has only one reference to a writer and a writer
    // has zero or more references to books
    //$NON-NLS-1$
    EReference books = createEReference("books", book, 0, ETypedElement.UNBOUNDED_MULTIPLICITY, false);
    //$NON-NLS-1$
    EReference author = createEReference("author", writer, 1, 1, false);
    author.setEOpposite(books);
    books.setEOpposite(author);
    book.getEReferences().add(author);
    writer.getEReferences().add(books);
    // Create a containment reference in which a library contains
    // one or more books
    //$NON-NLS-1$
    EReference libBooks = createEReference("books", book, 1, ETypedElement.UNBOUNDED_MULTIPLICITY, true);
    library.getEReferences().add(libBooks);
    // Create a containment reference in which a library contains
    // one or more writers
    //$NON-NLS-1$
    EReference writers = createEReference("writers", writer, 1, ETypedElement.UNBOUNDED_MULTIPLICITY, true);
    library.getEReferences().add(writers);
    return ePackage;
}

Java Examples for android.app.ActionBar.Tab

The following java examples will help you to understand the usage of android.app.ActionBar.Tab. These source code samples are taken from different open source projects.

Example 1
Project: devcoin-android-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof SherlockFragmentActivity) {
            trans = ((SherlockFragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 2
Project: SealBrowser-master  File: TabletUIManager.java View source code
public void onTabSelected(Tab tab) {
    updateUrlBar();
    CustomWebView webView = getCurrentWebView();
    if ((webView != null) && (!webView.isPrivateBrowsingEnabled())) {
        Controller.getInstance().getAddonManager().onTabSwitched(mActivity, webView);
    }
}
Example 3
Project: AndroidBinding-master  File: TabNavigationAdapter.java View source code
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    int pos = tab.getPosition();
    ArrayList<Object> initiators = new ArrayList<Object>();
    initiators.add(TabNavigationAdapter.this);
    try {
        TabNavigationSelectedItem item = ((TabNavigationSelectedItem) BinderV30.getAttributeForView(getView(), "tabNavigationSelectedItem"));
        item.set(mAdapter.getItem(pos), initiators);
        TabNavigationOnItemSelected selected = (TabNavigationOnItemSelected) BinderV30.getAttributeForView(getView(), "tabNavigationOnItemSelected");
        selected.invokeCommand(getView(), tab, ft);
    } catch (AttributeNotDefinedException e) {
        e.printStackTrace();
    }
}
Example 4
Project: andlytics-master  File: DetailsActivity.java View source code
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    if (fragment == null) {
        fragment = Fragment.instantiate(activity, clazz.getName());
        ft.add(android.R.id.content, fragment, tag);
    } else {
        ft.attach(fragment);
    }
    activity.setTitle(((StatsView<?>) fragment).getTitle());
    if (activity.appName != null) {
        activity.getActionBar().setSubtitle(activity.appName);
    }
}
Example 5
Project: Lyric-Music-Player-master  File: CompatHoneycomb.java View source code
/**
	 * Add ActionBar tabs for LibraryActivity.
	 *
	 * @param activity The activity to add to.
	 */
public static void addActionBarTabs(final LibraryActivity activity) {
    ActionBar.TabListener listener = new ActionBar.TabListener() {

        private final LibraryActivity mActivity = activity;

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            mActivity.mViewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        }
    };
    ActionBar ab = activity.getActionBar();
    ab.removeAllTabs();
    int[] order = activity.mPagerAdapter.mTabOrder;
    int[] titles = LibraryPagerAdapter.TITLES;
    for (int i = 0, n = activity.mPagerAdapter.getCount(); i != n; ++i) {
        ab.addTab(ab.newTab().setText(titles[order[i]]).setTabListener(listener));
    }
    ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
Example 6
Project: andevcon-2014-jl-master  File: VideoPlayerActivity.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
    setContentView(R.layout.video_player);
    mContent = (Content) findViewById(R.id.content);
    mContent.init(this, (TextView) findViewById(R.id.title), (Button) findViewById(R.id.play), (SeekBar) findViewById(R.id.seekbar));
    ActionBar bar = getActionBar();
    bar.addTab(bar.newTab().setText("Tab 1").setTabListener(this));
    bar.addTab(bar.newTab().setText("Tab 2").setTabListener(this));
    bar.addTab(bar.newTab().setText("Tab 3").setTabListener(this));
}
Example 7
Project: FileExplorer-master  File: FileExplorerTabActivity.java View source code
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    Object tag = tab.getTag();
    for (int i = 0; i < mTabs.size(); i++) {
        if (mTabs.get(i) == tag) {
            mViewPager.setCurrentItem(i);
        }
    }
    if (!tab.getText().equals(mContext.getString(R.string.tab_sd))) {
        ActionMode actionMode = ((FileExplorerTabActivity) mContext).getActionMode();
        if (actionMode != null) {
            actionMode.finish();
        }
    }
}
Example 8
Project: AudioPlayer-master  File: ListUI.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme_Holo);
    super.onCreate(savedInstanceState);
    // 注册异常捕获
    CrashHandler.GetInstance().init();
    setContentView(R.layout.listui);
    ActionBar actionbar = getActionBar();
    // 不显示主界面按钮
    actionbar.setDisplayShowHomeEnabled(false);
    actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    // 不显示标题
    actionbar.setDisplayShowTitleEnabled(false);
    Tab tab = actionbar.newTab();
    tab.setText("音乐库");
    tab.setTag(Fragment_ListCategory.class);
    tab.setTabListener(this);
    actionbar.addTab(tab, true);
    Tab tab2 = actionbar.newTab();
    tab2.setText("视频库");
    tab2.setTag(Fragment_VideoList.class);
    tab2.setTabListener(this);
    actionbar.addTab(tab2);
    playorpause = (ImageView) findViewById(R.id.stplay);
    next = (ImageView) findViewById(R.id.stnext);
    icon = (ImageView) findViewById(R.id.sticon);
    title = (TextView) findViewById(R.id.sttitle);
    artist = (TextView) findViewById(R.id.startist);
    pbar = (ProgressBar) findViewById(R.id.pbar);
    playorpause.setOnClickListener(this);
    icon.setOnClickListener(this);
    next.setOnClickListener(this);
    IntentFilter filter = new IntentFilter();
    // 过滤器设置
    filter.addAction(MyAction.INTENT_STATUS);
    filter.addAction(MyAction.INTENT_UI_UPDATE);
    filter.addAction(MyAction.INTENT_EXIT);
    registerReceiver(Receiver, filter// 注册
    );
    filter = new IntentFilter();
    // 过滤器设置
    filter.addAction(MyAction.INTENT_POSITION);
    registerReceiver(PosReceiver, filter// 注册
    );
    startService(new Intent(MyAction.INTENT_START_SERVICE));
    bindService(new Intent(MyAction.INTENT_START_SERVICE), ServiceConnector, // 绑定后台服务
    Context.BIND_AUTO_CREATE);
}
Example 9
Project: android-sdk-sources-for-api-level-23-master  File: FrameworkActionBarWrapper.java View source code
// TODO: Use an adapter, like List View to set up tabs.
// For Tab
@SuppressWarnings("deprecation")
private void setupTabs(int num) {
    for (int i = 1; i <= num; i++) {
        Tab tab = mActionBar.newTab().setText("Tab" + i).setTabListener(new TabListener() {

            @Override
            public void onTabUnselected(Tab t, FragmentTransaction ft) {
            // pass
            }

            @Override
            public void onTabSelected(Tab t, FragmentTransaction ft) {
            // pass
            }

            @Override
            public void onTabReselected(Tab t, FragmentTransaction ft) {
            // pass
            }
        });
        mActionBar.addTab(tab);
    }
}
Example 10
Project: android_packages_apps-master  File: MessageCompose.java View source code
/**
     * Updates UI components that allows the user to switch between reply/reply all/forward.
     */
private void updateActionSelector() {
    ActionBar actionBar = getActionBar();
    if (shouldUseActionTabs()) {
        // Tab-based mode switching.
        if (actionBar.getTabCount() > 0) {
            selectActionTab(mAction);
        } else {
            createAndAddTab(R.string.reply_action, ACTION_REPLY);
            createAndAddTab(R.string.reply_all_action, ACTION_REPLY_ALL);
            createAndAddTab(R.string.forward_action, ACTION_FORWARD);
        }
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    } else {
        // Spinner based mode switching.
        if (mActionSpinnerAdapter == null) {
            mActionSpinnerAdapter = new ActionSpinnerAdapter(this);
            actionBar.setListNavigationCallbacks(mActionSpinnerAdapter, ACTION_SPINNER_LISTENER);
        }
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        actionBar.setSelectedNavigationItem(ActionSpinnerAdapter.getActionPosition(mAction));
    }
    actionBar.setDisplayShowTitleEnabled(false);
}
Example 11
Project: GWSHolmesWatson-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 12
Project: BuzzBuddy-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 13
Project: astrid-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 14
Project: TasksProject-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 15
Project: ExcusePro-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 16
Project: unutopia-android-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 17
Project: ijoyplus-android-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 18
Project: CSipSimple-old-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof SherlockFragmentActivity) {
            trans = ((SherlockFragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 19
Project: doode-android-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof SherlockFragmentActivity) {
            trans = ((SherlockFragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 20
Project: luper-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 21
Project: travelinfo-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 22
Project: SmartAndroidSource-master  File: ActionBarWrapper.java View source code
@Override
public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    if (mListener != null) {
        FragmentTransaction trans = null;
        if (mActivity instanceof FragmentActivity) {
            trans = ((FragmentActivity) mActivity).getSupportFragmentManager().beginTransaction().disallowAddToBackStack();
        }
        mListener.onTabReselected(this, trans);
        if (trans != null && !trans.isEmpty()) {
            trans.commit();
        }
    }
}
Example 23
Project: hci-2011-2-master  File: ActionBarWrapper.java View source code
@Override
public void removeTab(Tab tab) {
    final int tabCount = getActionBar().getTabCount();
    for (int i = 0; i < tabCount; i++) {
        if (getActionBar().getTabAt(i).getTag().equals(tab)) {
            getActionBar().removeTabAt(i);
            break;
        }
    }
}
Example 24
Project: Musubi-Android-master  File: ActionBarWrapper.java View source code
@Override
public void removeTab(Tab tab) {
    final int tabCount = getActionBar().getTabCount();
    for (int i = 0; i < tabCount; i++) {
        if (getActionBar().getTabAt(i).getTag().equals(tab)) {
            getActionBar().removeTabAt(i);
            break;
        }
    }
}
Example 25
Project: WeddingCalculator-master  File: MainActivity.java View source code
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // enable these two lines will show the progress spinner on actionbar
    //requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);          
    setContentView(R.layout.activity_main);
    //setProgressBarIndeterminateVisibility(true);
    mActionBar = getActionBar();
    mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    /** Getting a reference to ViewPager from the layout */
    mPager = (ViewPager) findViewById(R.id.pager);
    /** Getting a reference to FragmentManager */
    FragmentManager fm = getSupportFragmentManager();
    ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            mActionBar.setSelectedNavigationItem(position);
        }
    };
    mPager.setOnPageChangeListener(pageChangeListener);
    MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(fm);
    mPager.setAdapter(fragmentPagerAdapter);
    mActionBar.setDisplayShowTitleEnabled(true);
    ActionBar.TabListener tabListener = new ActionBar.TabListener() {

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            mPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        }
    };
    Tab tab = mActionBar.newTab().setText(MainActivity.this.getResources().getText(R.string.Fragment1)).setTabListener(tabListener);
    mActionBar.addTab(tab);
    tab = mActionBar.newTab().setText(MainActivity.this.getResources().getText(R.string.Fragment2)).setTabListener(tabListener);
    mActionBar.addTab(tab);
    tab = mActionBar.newTab().setText(MainActivity.this.getResources().getText(R.string.Fragment3)).setTabListener(tabListener);
    mActionBar.addTab(tab);
    tab = mActionBar.newTab().setText(MainActivity.this.getResources().getText(R.string.Fragment4)).setTabListener(tabListener);
    mActionBar.addTab(tab);
    tab = mActionBar.newTab().setText(MainActivity.this.getResources().getText(R.string.Fragment5)).setTabListener(tabListener);
    mActionBar.addTab(tab);
    //setup ActionBar background color
    mActionBar.setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.tab_background)));
    mActionBar.setSplitBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.tab_slider)));
    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo("com.bezier.app.weddingcalculator", PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }
}

Java Examples for java.lang.Integer

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

Example 1
Project: sosies-generator-master  File: StreamingTypeAdaptersTest.java View source code
@Test(timeout = 1000)
public void testNullSafe_add1436() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testNullSafe_add1436");
    TypeAdapter<Person> typeAdapter = new TypeAdapter<Person>() {

        @Override
        public Person read(JsonReader in) throws IOException {
            String[] values = in.nextString().split(",");
            return new Person(values[0], java.lang.Integer.parseInt(values[1]));
        }

        public void write(JsonWriter out, Person person) throws IOException {
            out.value((((person.name) + ",") + (person.age)));
        }
    };
    Gson gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter).create();
    Truck truck = new Truck();
    truck.horsePower = 1.0;
    truck.passengers = new ArrayList<Person>();
    truck.passengers.add(null);
    truck.passengers.add(new Person("jesse", 30));
    try {
        gson.toJson(truck, Truck.class);
    } catch (NullPointerException expected) {
    }
    String json = "{horsePower:1.0,passengers:[null,\'jesse,30\']}";
    try {
        gson.fromJson(json, Truck.class);
    } catch (JsonSyntaxException expected) {
    }
    gson = new GsonBuilder().registerTypeAdapter(Person.class, typeAdapter.nullSafe()).create();
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2446, gson, 2445, gson.toJson(truck, com.google.gson.functional.StreamingTypeAdaptersTest.Truck.class));
    truck = gson.fromJson(json, Truck.class);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2447, truck.horsePower);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2449, truck.passengers, 2448, truck.passengers.get(0));
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2450, truck.passengers.get(1).name);
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 2
Project: ARTPart-master  File: Main.java View source code
private static void arrayStore() throws Exception {
    try {
        Object[] array = new String[10];
        Object o = new Exception();
        array[0] = o;
        fail();
    } catch (ArrayStoreException ex) {
        assertEquals("java.lang.Exception cannot be stored in an array of type java.lang.String[]", ex.getMessage());
    }
    try {
        Object[] array = new C[10][];
        Object o = new Integer(5);
        array[0] = o;
        fail();
    } catch (ArrayStoreException ex) {
        assertEquals("java.lang.Integer cannot be stored in an array of type Main$C[][]", ex.getMessage());
    }
    try {
        Object[] array = new Float[10][];
        Object o = new C[4];
        array[0] = o;
        fail();
    } catch (ArrayStoreException ex) {
        assertEquals("Main$C[] cannot be stored in an array of type java.lang.Float[][]", ex.getMessage());
    }
    try {
        String[] src = new String[] { null, null, null, null, "hello", "goodbye" };
        Integer[] dst = new Integer[10];
        System.arraycopy(src, 1, dst, 0, 5);
    } catch (ArrayStoreException ex) {
        assertEquals("source[4] of type java.lang.String cannot be stored in destination array of type java.lang.Integer[]", ex.getMessage());
    }
    try {
        String[] src = new String[1];
        int[] dst = new int[1];
        System.arraycopy(src, 0, dst, 0, 1);
    } catch (ArrayStoreException ex) {
        assertEquals("Incompatible types: src=java.lang.String[], dst=int[]", ex.getMessage());
    }
    try {
        float[] src = new float[1];
        Runnable[] dst = new Runnable[1];
        System.arraycopy(src, 0, dst, 0, 1);
    } catch (ArrayStoreException ex) {
        assertEquals("Incompatible types: src=float[], dst=java.lang.Runnable[]", ex.getMessage());
    }
    try {
        boolean[] src = new boolean[1];
        double[][] dst = new double[1][];
        System.arraycopy(src, 0, dst, 0, 1);
    } catch (ArrayStoreException ex) {
        assertEquals("Incompatible types: src=boolean[], dst=double[][]", ex.getMessage());
    }
    try {
        String src = "hello";
        Object[] dst = new Object[1];
        System.arraycopy(src, 0, dst, 0, 1);
    } catch (ArrayStoreException ex) {
        assertEquals("source of type java.lang.String is not an array", ex.getMessage());
    }
    try {
        Object[] src = new Object[1];
        Integer dst = new Integer(5);
        System.arraycopy(src, 0, dst, 0, 1);
    } catch (ArrayStoreException ex) {
        assertEquals("destination of type java.lang.Integer is not an array", ex.getMessage());
    }
    // destination is an array.
    try {
        System.arraycopy(new C(), 0, "hello", 0, 1);
    } catch (ArrayStoreException ex) {
        assertEquals("source of type Main$C is not an array", ex.getMessage());
    }
}
Example 3
Project: open-mika-master  File: invoke2.java View source code
public void test(TestHarness harness) {
    // Don't use `.class' because gcj doesn't handle it yet.
    harness.setclass("java.lang.reflect.Method");
    harness.checkPoint("invoke(java.lang.Object,java.lang.Object[])java.lang.Object");
    Class ic = null;
    try {
        ic = Class.forName("gnu.testlet.wonka.lang.reflect.Method.invoke2");
    } catch (Throwable _) {
    }
    Class[] na_list = new Class[0];
    Method na_meth = getMethod(ic, "no_args", na_list);
    Class[] ti_list = new Class[1];
    ti_list[0] = Integer.TYPE;
    Method ti_meth = getMethod(ic, "takes_int", ti_list);
    Class[] rv_list = new Class[2];
    rv_list[0] = null;
    try {
        rv_list[0] = Class.forName("java.lang.Integer");
    } catch (Throwable _) {
    }
    rv_list[1] = rv_list[0];
    Method rv_meth = getMethod(ic, "returns_void", rv_list);
    //harness.checkPoint ("no_args");
    Object[] args0 = new Object[0];
    // Successful invocation.
    try_invoke(harness, na_meth, this, args0, "zardoz");
    // Null `this' should fail.
    try_invoke(harness, na_meth, null, args0, new NullPointerException());
    // Too few arguments.
    try_invoke(harness, ti_meth, this, args0, new IllegalArgumentException());
    // Wrong class for `this'.
    try_invoke(harness, na_meth, new NullPointerException(), args0, new IllegalArgumentException());
    //harness.checkPoint ("takes_int");
    Object[] args1 = new Object[1];
    args1[0] = new Integer(5);
    try_invoke(harness, na_meth, this, args1, new IllegalArgumentException());
    try_invoke(harness, ti_meth, this, args1, new Integer(8));
    // null should work for object as this is a static method.
    try_invoke(harness, ti_meth, null, args1, new Integer(8));
    args1[0] = "joe louis";
    try_invoke(harness, ti_meth, null, args1, new IllegalArgumentException());
    args1[0] = new Short((short) 3);
    try_invoke(harness, ti_meth, null, args1, new Integer(6));
    args1[0] = new Long(72);
    try_invoke(harness, ti_meth, null, args1, new IllegalArgumentException());
    args1[0] = null;
    try_invoke(harness, ti_meth, null, args1, new IllegalArgumentException());
    //harness.debug("DEBUG: the test above fails on Sun's JDK since it throws a NullPointerException\n"+
    //	"\tSun's JDK throws a NullPointerException since a null Object is passed in the Array\n"+
    //	"\tWonka throws an IllegalArgumentException since we Expect an Object of Integer WITH a value wich should be passed");		
    args1[0] = new Integer(-5);
    try_invoke(harness, ti_meth, null, args1, new InvocationTargetException(new IllegalArgumentException()));
    //harness.checkPoint ("returns_void");
    Object[] args2 = new Object[2];
    args2[0] = new Integer(7);
    args2[1] = new Integer(8);
    try_invoke(harness, rv_meth, this, args2, null);
    harness.check(save, 15);
}
Example 4
Project: classlib6-master  File: NamingContextExtPOA.java View source code
public org.omg.CORBA.portable.OutputStream _invoke(String $method, org.omg.CORBA.portable.InputStream in, org.omg.CORBA.portable.ResponseHandler $rh) {
    org.omg.CORBA.portable.OutputStream out = null;
    java.lang.Integer __method = (java.lang.Integer) _methods.get($method);
    if (__method == null)
        throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
    switch(__method.intValue()) {
        /**
   * This operation creates a stringified name from the array of Name
   * components.
   * 
   * @param n Name of the object <p>
   * 
   * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidName
   * Indicates the name does not identify a binding.<p>
   * 
   */
        case // CosNaming/NamingContextExt/to_string
        0:
            {
                try {
                    org.omg.CosNaming.NameComponent n[] = org.omg.CosNaming.NameHelper.read(in);
                    String $result = null;
                    $result = this.to_string(n);
                    out = $rh.createReply();
                    out.write_string($result);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                }
                break;
            }
        /**
   * This operation  converts a Stringified Name into an  equivalent array
   * of Name Components. 
   * 
   * @param sn Stringified Name of the object <p>
   * 
   * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidName
   * Indicates the name does not identify a binding.<p>
   * 
   */
        case // CosNaming/NamingContextExt/to_name
        1:
            {
                try {
                    String sn = org.omg.CosNaming.NamingContextExtPackage.StringNameHelper.read(in);
                    org.omg.CosNaming.NameComponent $result[] = null;
                    $result = this.to_name(sn);
                    out = $rh.createReply();
                    org.omg.CosNaming.NameHelper.write(out, $result);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                }
                break;
            }
        /**
   * This operation creates a URL based "iiopname://" format name
   * from the Stringified Name of the object.
   * 
   * @param addr internet based address of the host machine where  Name Service is running <p>
   * @param sn Stringified Name of the object <p>
   * 
   * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidName
   * Indicates the name does not identify a binding.<p>
   * @exception org.omg.CosNaming.NamingContextPackage.InvalidAddress
   * Indicates the internet based address of the host machine is 
   * incorrect <p>
   * 
   */
        case // CosNaming/NamingContextExt/to_url
        2:
            {
                try {
                    String addr = org.omg.CosNaming.NamingContextExtPackage.AddressHelper.read(in);
                    String sn = org.omg.CosNaming.NamingContextExtPackage.StringNameHelper.read(in);
                    String $result = null;
                    $result = this.to_url(addr, sn);
                    out = $rh.createReply();
                    out.write_string($result);
                } catch (org.omg.CosNaming.NamingContextExtPackage.InvalidAddress $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                }
                break;
            }
        /**
   * This operation resolves the Stringified name into the object
   * reference. 
   * 
   * @param sn Stringified Name of the object <p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.NotFound
   * Indicates there is no object reference for the given name. <p>
   * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed
   * Indicates that the given compound name is incorrect <p>
   * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidName
   * Indicates the name does not identify a binding.<p>
   * 
   */
        case // CosNaming/NamingContextExt/resolve_str
        3:
            {
                try {
                    String sn = org.omg.CosNaming.NamingContextExtPackage.StringNameHelper.read(in);
                    org.omg.CORBA.Object $result = null;
                    $result = this.resolve_str(sn);
                    out = $rh.createReply();
                    org.omg.CORBA.ObjectHelper.write(out, $result);
                } catch (org.omg.CosNaming.NamingContextPackage.NotFound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.NotFoundHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                }
                break;
            }
        /**
   * Creates a binding of a name and an object in the naming context.
   * Naming contexts that are bound using bind do not participate in name
   * resolution when compound names are passed to be resolved. 
   * 
   * @param n Name of the object <p>
   * 
   * @param obj The Object to bind with the given name<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates
   * the name does not identify a binding.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed 
   * Indicates that the implementation has given up for some reason.
   * The client, however, may be able to continue the operation
   * at the returned naming context.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.InvalidName 
   * Indicates that the name is invalid. <p>
   *
   * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound 
   * Indicates an object is already bound to the specified name.<p> 
   */
        case // CosNaming/NamingContext/bind
        4:
            {
                try {
                    org.omg.CosNaming.NameComponent n[] = org.omg.CosNaming.NameHelper.read(in);
                    org.omg.CORBA.Object obj = org.omg.CORBA.ObjectHelper.read(in);
                    this.bind(n, obj);
                    out = $rh.createReply();
                } catch (org.omg.CosNaming.NamingContextPackage.NotFound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.NotFoundHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper.write(out, $ex);
                }
                break;
            }
        /**
   * Names an object that is a naming context. Naming contexts that
   * are bound using bind_context() participate in name resolution 
   * when compound names are passed to be resolved.
   * 
   * @param n Name of the object <p>
   * 
   * @param nc NamingContect object to bind with the given name <p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has
   * given up for some reason. The client, however, may be able to 
   * continue the operation at the returned naming context.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid. <p>
   *
   * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound Indicates an object is already 
   * bound to the specified name.<p>
   */
        case // CosNaming/NamingContext/bind_context
        5:
            {
                try {
                    org.omg.CosNaming.NameComponent n[] = org.omg.CosNaming.NameHelper.read(in);
                    org.omg.CosNaming.NamingContext nc = org.omg.CosNaming.NamingContextHelper.read(in);
                    this.bind_context(n, nc);
                    out = $rh.createReply();
                } catch (org.omg.CosNaming.NamingContextPackage.NotFound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.NotFoundHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper.write(out, $ex);
                }
                break;
            }
        /**
   * Creates a binding of a name and an object in the naming context
   * even if the name is already bound in the context. Naming contexts 
   * that are bound using rebind do not participate in name resolution 
   * when compound names are passed to be resolved.
   * 
   * @param  n Name of the object <p>
   * 
   * @parm obj The Object to rebind with the given name <p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has
   * given up for some reason. The client, however, may be able to 
   * continue the operation at the returned naming context.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid. <p>
   */
        case // CosNaming/NamingContext/rebind
        6:
            {
                try {
                    org.omg.CosNaming.NameComponent n[] = org.omg.CosNaming.NameHelper.read(in);
                    org.omg.CORBA.Object obj = org.omg.CORBA.ObjectHelper.read(in);
                    this.rebind(n, obj);
                    out = $rh.createReply();
                } catch (org.omg.CosNaming.NamingContextPackage.NotFound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.NotFoundHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                }
                break;
            }
        /** 
   * Creates a binding of a name and a naming context in the naming
   * context even if the name is already bound in the context. Naming 
   * contexts that are bound using rebind_context() participate in name 
   * resolution when compound names are passed to be resolved.
   * 
   * @param n Name of the object <p>
   * 
   * @param nc NamingContect object to rebind with the given name <p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has
   * given up for some reason. The client, however, may be able to 
   * continue the operation at the returned naming context.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid. <p>
   */
        case // CosNaming/NamingContext/rebind_context
        7:
            {
                try {
                    org.omg.CosNaming.NameComponent n[] = org.omg.CosNaming.NameHelper.read(in);
                    org.omg.CosNaming.NamingContext nc = org.omg.CosNaming.NamingContextHelper.read(in);
                    this.rebind_context(n, nc);
                    out = $rh.createReply();
                } catch (org.omg.CosNaming.NamingContextPackage.NotFound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.NotFoundHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                }
                break;
            }
        /** 
   * The resolve operation is the process of retrieving an object
   * bound to a name in a given context. The given name must exactly 
   * match the bound name. The naming service does not return the type 
   * of the object. Clients are responsible for "narrowing" the object 
   * to the appropriate type. That is, clients typically cast the returned 
   * object from Object to a more specialized interface.
   * 
   * @param n Name of the object <p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has
   * given up for some reason. The client, however, may be able to 
   * continue the operation at the returned naming context.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid. <p>
   */
        case // CosNaming/NamingContext/resolve
        8:
            {
                try {
                    org.omg.CosNaming.NameComponent n[] = org.omg.CosNaming.NameHelper.read(in);
                    org.omg.CORBA.Object $result = null;
                    $result = this.resolve(n);
                    out = $rh.createReply();
                    org.omg.CORBA.ObjectHelper.write(out, $result);
                } catch (org.omg.CosNaming.NamingContextPackage.NotFound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.NotFoundHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                }
                break;
            }
        /** 
   * The unbind operation removes a name binding from a context.
   * 
   * @param n Name of the object <p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has
   * given up for some reason. The client, however, may be able to 
   * continue the operation at the returned naming context.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid. <p>
   */
        case // CosNaming/NamingContext/unbind
        9:
            {
                try {
                    org.omg.CosNaming.NameComponent n[] = org.omg.CosNaming.NameHelper.read(in);
                    this.unbind(n);
                    out = $rh.createReply();
                } catch (org.omg.CosNaming.NamingContextPackage.NotFound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.NotFoundHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                }
                break;
            }
        /**
   * The list operation allows a client to iterate through a set of
   * bindings in a naming context. <p>
   * 
   * The list operation returns at most the requested number of
   * bindings in BindingList bl. 
   * <ul>
   * <li>If the naming context contains additional 
   * bindings, the list operation returns a BindingIterator with the 
   * additional bindings. 
   * <li>If the naming context does not contain additional 
   * bindings, the binding iterator is a nil object reference.
   * </ul>
   * 
   * @param how_many the maximum number of bindings to return <p>
   * 
   * @param bl the returned list of bindings <p>
   * 
   * @param bi the returned binding iterator <p>
   */
        case // CosNaming/NamingContext/list
        10:
            {
                int how_many = in.read_ulong();
                org.omg.CosNaming.BindingListHolder bl = new org.omg.CosNaming.BindingListHolder();
                org.omg.CosNaming.BindingIteratorHolder bi = new org.omg.CosNaming.BindingIteratorHolder();
                this.list(how_many, bl, bi);
                out = $rh.createReply();
                org.omg.CosNaming.BindingListHelper.write(out, bl.value);
                org.omg.CosNaming.BindingIteratorHelper.write(out, bi.value);
                break;
            }
        /**
   * This operation returns a naming context implemented by the same
   * naming server as the context on which the operation was invoked. 
   * The new context is not bound to any name.
   */
        case // CosNaming/NamingContext/new_context
        11:
            {
                org.omg.CosNaming.NamingContext $result = null;
                $result = this.new_context();
                out = $rh.createReply();
                org.omg.CosNaming.NamingContextHelper.write(out, $result);
                break;
            }
        /**
   * This operation creates a new context and binds it to the name
   * supplied as an argument. The newly-created context is implemented 
   * by the same naming server as the context in which it was bound (that 
   * is, the naming server that implements the context denoted by the 
   * name argument excluding the last component).
   * 
   * @param n Name of the object <p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.NotFound Indicates the name does not identify a binding.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound Indicates an object is already 
   * bound to the specified name.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed Indicates that the implementation has
   * given up for some reason. The client, however, may be able to 
   * continue the operation at the returned naming context.<p>
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.InvalidName Indicates that the name is invalid. <p>
   */
        case // CosNaming/NamingContext/bind_new_context
        12:
            {
                try {
                    org.omg.CosNaming.NameComponent n[] = org.omg.CosNaming.NameHelper.read(in);
                    org.omg.CosNaming.NamingContext $result = null;
                    $result = this.bind_new_context(n);
                    out = $rh.createReply();
                    org.omg.CosNaming.NamingContextHelper.write(out, $result);
                } catch (org.omg.CosNaming.NamingContextPackage.NotFound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.NotFoundHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.CannotProceedHelper.write(out, $ex);
                } catch (org.omg.CosNaming.NamingContextPackage.InvalidName $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.InvalidNameHelper.write(out, $ex);
                }
                break;
            }
        /** 
   * The destroy operation deletes a naming context. If the naming 
   * context contains bindings, the NotEmpty exception is raised.
   * 
   * @exception org.omg.CosNaming.NamingContextPackage.NotEmpty Indicates that the Naming Context contains bindings.
   */
        case // CosNaming/NamingContext/destroy
        13:
            {
                try {
                    this.destroy();
                    out = $rh.createReply();
                } catch (org.omg.CosNaming.NamingContextPackage.NotEmpty $ex) {
                    out = $rh.createExceptionReply();
                    org.omg.CosNaming.NamingContextPackage.NotEmptyHelper.write(out, $ex);
                }
                break;
            }
        default:
            throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
    }
    return out;
}
Example 5
Project: openjdk-master  File: GetModule.java View source code
public static void main(String[] args) {
    Module module;
    Module javaBaseModule;
    // Module for primitive type, should be "java.base"
    java.lang.Integer primitive_int = 1;
    try {
        javaBaseModule = (Module) callGetModule(primitive_int.getClass());
        if (!javaBaseModule.getName().equals("java.base")) {
            throw new RuntimeException("Unexpected module name for primitive type: " + javaBaseModule.getName());
        }
    } catch (Throwable e) {
        throw new RuntimeException("Unexpected exception for Integer: " + e.toString());
    }
    // Module for array of primitives, should be "java.base"
    int[] int_array = { 1, 2, 3 };
    try {
        javaBaseModule = (Module) callGetModule(int_array.getClass());
        if (!javaBaseModule.getName().equals("java.base")) {
            throw new RuntimeException("Unexpected module name for array of primitives: " + javaBaseModule.getName());
        }
    } catch (Throwable e) {
        throw new RuntimeException("Unexpected exception for [I: " + e.toString());
    }
    // Module for multi-dimensional array of primitives, should be "java.base"
    int[][] multi_int_array = { { 1, 2, 3 }, { 4, 5, 6 } };
    try {
        javaBaseModule = (Module) callGetModule(multi_int_array.getClass());
        if (!javaBaseModule.getName().equals("java.base")) {
            throw new RuntimeException("Unexpected module name for multi-dimensional array of primitives: " + javaBaseModule.getName());
        }
    } catch (Throwable e) {
        throw new RuntimeException("Unexpected exception for multi-dimensional Integer array: " + e.toString());
    }
    // Module for java.lang.String, should be "java.base"
    java.lang.String str = "abc";
    try {
        module = (Module) callGetModule(str.getClass());
        if (!module.getName().equals("java.base")) {
            throw new RuntimeException("Unexpected module name for class String: " + module.getName());
        }
    } catch (Throwable e) {
        throw new RuntimeException("Unexpected exception for String: " + e.toString());
    }
    // Module for array of java.lang.Strings, should be "java.base"
    java.lang.String[] str_array = { "a", "b", "c" };
    try {
        javaBaseModule = (Module) callGetModule(str_array.getClass());
        if (!javaBaseModule.getName().equals("java.base")) {
            throw new RuntimeException("Unexpected module name for array of Strings: " + javaBaseModule.getName());
        }
    } catch (Throwable e) {
        throw new RuntimeException("Unexpected exception for String array: " + e.toString());
    }
    // Module for multi-dimensional array of java.lang.Strings, should be "java.base"
    java.lang.String[][] multi_str_array = { { "a", "b", "c" }, { "d", "e", "f" } };
    try {
        javaBaseModule = (Module) callGetModule(multi_str_array.getClass());
        if (!javaBaseModule.getName().equals("java.base")) {
            throw new RuntimeException("Unexpected module name for multi-dimensional array of Strings: " + javaBaseModule.getName());
        }
    } catch (Throwable e) {
        throw new RuntimeException("Unexpected exception for multidimensional String array: " + e.toString());
    }
    // Module for java.lang.management.LockInfo
    try {
        LockInfo li = new LockInfo("java.lang.Class", 57);
        module = (Module) callGetModule(li.getClass());
        if (!module.getName().equals("java.management")) {
            throw new RuntimeException("Unexpected module name for class LockInfo: " + module.getName());
        }
    } catch (Throwable e) {
        throw new RuntimeException("Unexpected exception for LockInfo: " + e.toString());
    }
    // Unnamed module.
    try {
        module = (Module) callGetModule(MyClassLoader.class);
        if (module == null || module.getName() != null) {
            throw new RuntimeException("Bad module for unnamed module");
        }
    } catch (Throwable e) {
        throw new RuntimeException("Unexpected exception for unnamed module: " + e.toString());
    }
    try {
        module = (Module) callGetModule(null);
        throw new RuntimeException("Failed to get expected NullPointerException");
    } catch (NullPointerException e) {
    }
}
Example 6
Project: geotools-old-master  File: XSISimpleTypes.java View source code
/*
     * loads the mapping of names -> simpletypes on demand
     */
private static void load() {
    m = new HashMap();
    m.put(Integer.getInstance().getName(), Integer.getInstance());
    m.put(Decimal.getInstance().getName(), Decimal.getInstance());
    m.put(NegativeInteger.getInstance().getName(), NegativeInteger.getInstance());
    m.put(PositiveInteger.getInstance().getName(), PositiveInteger.getInstance());
    m.put(NonNegativeInteger.getInstance().getName(), NonNegativeInteger.getInstance());
    m.put(NonPositiveInteger.getInstance().getName(), NonPositiveInteger.getInstance());
    m.put(Long.getInstance().getName(), Long.getInstance());
    m.put(Int.getInstance().getName(), Int.getInstance());
    m.put(Short.getInstance().getName(), Short.getInstance());
    m.put(Byte.getInstance().getName(), Byte.getInstance());
    m.put(UnsignedLong.getInstance().getName(), UnsignedLong.getInstance());
    m.put(UnsignedShort.getInstance().getName(), UnsignedShort.getInstance());
    m.put(UnsignedInt.getInstance().getName(), UnsignedInt.getInstance());
    m.put(UnsignedByte.getInstance().getName(), UnsignedByte.getInstance());
    m.put(Float.getInstance().getName(), Float.getInstance());
    m.put(Double.getInstance().getName(), Double.getInstance());
    m.put(Date.getInstance().getName(), Date.getInstance());
    m.put(DateTime.getInstance().getName(), DateTime.getInstance());
    m.put(Duration.getInstance().getName(), Duration.getInstance());
    m.put(gDay.getInstance().getName(), gDay.getInstance());
    m.put(gMonth.getInstance().getName(), gMonth.getInstance());
    m.put(gMonthDay.getInstance().getName(), gMonthDay.getInstance());
    m.put(gYear.getInstance().getName(), gYear.getInstance());
    m.put(gYearMonth.getInstance().getName(), gYearMonth.getInstance());
    m.put(Time.getInstance().getName(), Time.getInstance());
    m.put(ID.getInstance().getName(), ID.getInstance());
    m.put(IDREF.getInstance().getName(), IDREF.getInstance());
    m.put(IDREFS.getInstance().getName(), IDREFS.getInstance());
    m.put(ENTITY.getInstance().getName(), ENTITY.getInstance());
    m.put(ENTITIES.getInstance().getName(), ENTITIES.getInstance());
    m.put(NMTOKEN.getInstance().getName(), NMTOKEN.getInstance());
    m.put(NMTOKENS.getInstance().getName(), NMTOKENS.getInstance());
    m.put(NOTATION.getInstance().getName(), NOTATION.getInstance());
    m.put(String.getInstance().getName(), String.getInstance());
    m.put(NormalizedString.getInstance().getName(), NormalizedString.getInstance());
    m.put(Token.getInstance().getName(), Token.getInstance());
    m.put(QName.getInstance().getName(), QName.getInstance());
    m.put(Name.getInstance().getName(), Name.getInstance());
    m.put(NCName.getInstance().getName(), NCName.getInstance());
    m.put(Boolean.getInstance().getName(), Boolean.getInstance());
    m.put(AnyURI.getInstance().getName(), AnyURI.getInstance());
    m.put(Base64Binary.getInstance().getName(), Base64Binary.getInstance());
    m.put(HexBinary.getInstance().getName(), HexBinary.getInstance());
    m.put(Language.getInstance().getName(), Language.getInstance());
    m.put(Integer.getInstance().getInstanceType(), Integer.getInstance());
    m.put(Decimal.getInstance().getInstanceType(), Decimal.getInstance());
    m.put(NegativeInteger.getInstance().getInstanceType(), NegativeInteger.getInstance());
    m.put(PositiveInteger.getInstance().getInstanceType(), PositiveInteger.getInstance());
    m.put(NonNegativeInteger.getInstance().getInstanceType(), NonNegativeInteger.getInstance());
    m.put(NonPositiveInteger.getInstance().getInstanceType(), NonPositiveInteger.getInstance());
    m.put(Long.getInstance().getInstanceType(), Long.getInstance());
    m.put(Int.getInstance().getInstanceType(), Int.getInstance());
    m.put(Short.getInstance().getInstanceType(), Short.getInstance());
    m.put(Byte.getInstance().getInstanceType(), Byte.getInstance());
    m.put(UnsignedLong.getInstance().getInstanceType(), UnsignedLong.getInstance());
    m.put(UnsignedShort.getInstance().getInstanceType(), UnsignedShort.getInstance());
    m.put(UnsignedInt.getInstance().getInstanceType(), UnsignedInt.getInstance());
    m.put(UnsignedByte.getInstance().getInstanceType(), UnsignedByte.getInstance());
    m.put(Float.getInstance().getInstanceType(), Float.getInstance());
    m.put(Double.getInstance().getInstanceType(), Double.getInstance());
    m.put(Date.getInstance().getInstanceType(), Date.getInstance());
    m.put(DateTime.getInstance().getInstanceType(), DateTime.getInstance());
    m.put(Duration.getInstance().getInstanceType(), Duration.getInstance());
    m.put(gDay.getInstance().getInstanceType(), gDay.getInstance());
    m.put(gMonth.getInstance().getInstanceType(), gMonth.getInstance());
    m.put(gMonthDay.getInstance().getInstanceType(), gMonthDay.getInstance());
    m.put(gYear.getInstance().getInstanceType(), gYear.getInstance());
    m.put(gYearMonth.getInstance().getInstanceType(), gYearMonth.getInstance());
    m.put(Time.getInstance().getInstanceType(), Time.getInstance());
    m.put(ID.getInstance().getInstanceType(), ID.getInstance());
    m.put(IDREF.getInstance().getInstanceType(), IDREF.getInstance());
    m.put(IDREFS.getInstance().getInstanceType(), IDREFS.getInstance());
    m.put(ENTITY.getInstance().getInstanceType(), ENTITY.getInstance());
    m.put(ENTITIES.getInstance().getInstanceType(), ENTITIES.getInstance());
    m.put(NMTOKEN.getInstance().getInstanceType(), NMTOKEN.getInstance());
    m.put(NMTOKENS.getInstance().getInstanceType(), NMTOKENS.getInstance());
    m.put(NOTATION.getInstance().getInstanceType(), NOTATION.getInstance());
    m.put(String.getInstance().getInstanceType(), String.getInstance());
    m.put(NormalizedString.getInstance().getInstanceType(), NormalizedString.getInstance());
    m.put(Token.getInstance().getInstanceType(), Token.getInstance());
    m.put(QName.getInstance().getInstanceType(), QName.getInstance());
    m.put(Name.getInstance().getInstanceType(), Name.getInstance());
    m.put(NCName.getInstance().getInstanceType(), NCName.getInstance());
    m.put(Boolean.getInstance().getInstanceType(), Boolean.getInstance());
    m.put(AnyURI.getInstance().getInstanceType(), AnyURI.getInstance());
    m.put(Base64Binary.getInstance().getInstanceType(), Base64Binary.getInstance());
    m.put(HexBinary.getInstance().getInstanceType(), HexBinary.getInstance());
    m.put(Language.getInstance().getInstanceType(), Language.getInstance());
}
Example 7
Project: eclipselink.runtime-master  File: MWQueryTests.java View source code
public void testReadAllQueryOrderingAttributeValidProblem() {
    String errorNumber = ProblemConstants.QUERYABLE_NOT_VALID_FOR_READ_ALL_QUERY_ORDERING_ITEM;
    QueryProject queryProject = new QueryProject();
    MWRelationalReadAllQuery query = (MWRelationalReadAllQuery) queryProject.getEmployeeDescriptor().getQueryManager().queryWithSignature("myQuery4(java.lang.Integer)");
    assertFalse(hasProblem(errorNumber, query));
    MWMapping mapping = queryProject.getEmployeeDescriptor().mappingNamed("lastName");
    assertTrue(mapping.isTraversableForReadAllQueryOrderable());
    mapping = mapping.asMWOneToManyMapping();
    assertTrue(hasProblem(errorNumber, query));
    assertFalse(mapping.isTraversableForReadAllQueryOrderable());
    mapping = mapping.asMWDirectMapping();
    assertFalse(hasProblem(errorNumber, query));
    mapping = mapping.asMWAggregateMapping();
    assertTrue(mapping.isTraversableForReadAllQueryOrderable());
    assertTrue(hasProblem(errorNumber, query));
    mapping = mapping.asMWDirectMapping();
    assertFalse(hasProblem(errorNumber, query));
    mapping = mapping.asMWOneToOneMapping();
    assertTrue(mapping.isTraversableForReadAllQueryOrderable());
    assertTrue(hasProblem(errorNumber, query));
    mapping = mapping.asMWDirectMapping();
    assertFalse(hasProblem(errorNumber, query));
    mapping = mapping.asMWVariableOneToOneMapping();
    assertFalse(mapping.isTraversableForReadAllQueryOrderable());
    assertTrue(hasProblem(errorNumber, query));
    mapping = mapping.asMWTypeConversionMapping();
    assertTrue(mapping.isTraversableForReadAllQueryOrderable());
    assertFalse(hasProblem(errorNumber, query));
    mapping = (MWMapping) mapping.asMWDirectCollectionMapping();
    assertFalse(mapping.isTraversableForReadAllQueryOrderable());
    assertTrue(hasProblem(errorNumber, query));
    mapping = mapping.asMWSerializedMapping();
    assertTrue(mapping.isTraversableForReadAllQueryOrderable());
    assertFalse(hasProblem(errorNumber, query));
    mapping = (MWMapping) mapping.asMWDirectMapMapping();
    assertFalse(mapping.isTraversableForReadAllQueryOrderable());
    assertTrue(hasProblem(errorNumber, query));
    mapping = mapping.asMWObjectTypeMapping();
    assertTrue(mapping.isTraversableForReadAllQueryOrderable());
    assertFalse(hasProblem(errorNumber, query));
    mapping = mapping.asMWTransformationMapping();
    assertFalse(mapping.isTraversableForReadAllQueryOrderable());
    assertTrue(hasProblem(errorNumber, query));
    mapping = mapping.asMWDirectMapping();
    assertFalse(hasProblem(errorNumber, query));
    mapping = mapping.asMWDirectToXmlTypeMapping();
    assertFalse(mapping.isTraversableForReadAllQueryOrderable());
    assertTrue(hasProblem(errorNumber, query));
    mapping = mapping.asMWDirectMapping();
    assertFalse(hasProblem(errorNumber, query));
    queryProject.getEmployeeDescriptor().removeMapping(mapping);
    assertTrue(hasProblem(ProblemConstants.QUERYABLE_NULL_FOR_ORDERING_ITEM, query));
}
Example 8
Project: databus-master  File: DbusBootstrapProducerStatsEvent.java View source code
// Used by DatumReader.  Applications should not call. 
@SuppressWarnings(value = "unchecked")
public void put(int field$, java.lang.Object value$) {
    switch(field$) {
        case 0:
            ownerId = (java.lang.Integer) value$;
            break;
        case 1:
            timestampLastResetMs = (java.lang.Long) value$;
            break;
        case 2:
            timeSinceLastResetMs = (java.lang.Long) value$;
            break;
        case 3:
            dimension = (java.lang.CharSequence) value$;
            break;
        case 4:
            numErrFellOffRelay = (java.lang.Long) value$;
            break;
        case 5:
            numErrSqlException = (java.lang.Long) value$;
            break;
        case 6:
            numWindows = (java.lang.Long) value$;
            break;
        case 7:
            latencyPerWindow = (java.lang.Long) value$;
            break;
        case 8:
            numDataEventsPerWindow = (java.lang.Long) value$;
            break;
        case 9:
            currentSCN = (java.lang.Long) value$;
            break;
        case 10:
            currentLogId = (java.lang.Long) value$;
            break;
        case 11:
            currentRowId = (java.lang.Long) value$;
            break;
        default:
            throw new org.apache.avro.AvroRuntimeException("Bad index");
    }
}
Example 9
Project: JDK-master  File: BootstrapServer.java View source code
/**
     * Main startup routine for the bootstrap server.
     * It first determines the port on which to listen, checks that the
     * specified file is available, and then creates the resolver
     * that will be used to service the requests in the
     * BootstrapServerRequestDispatcher.
     * @param args the command-line arguments to the main program.
     */
public static final void main(String[] args) {
    String propertiesFilename = null;
    int initialPort = ORBConstants.DEFAULT_INITIAL_PORT;
    // Process arguments
    for (int i = 0; i < args.length; i++) {
        // Look for the filename
        if (args[i].equals("-InitialServicesFile") && i < args.length - 1) {
            propertiesFilename = args[i + 1];
        }
        // communicate.
        if (args[i].equals("-ORBInitialPort") && i < args.length - 1) {
            initialPort = java.lang.Integer.parseInt(args[i + 1]);
        }
    }
    if (propertiesFilename == null) {
        System.out.println(CorbaResourceUtil.getText("bootstrap.usage", "BootstrapServer"));
        return;
    }
    // Create a file
    File file = new File(propertiesFilename);
    // Verify that if it exists, it is readable
    if (file.exists() == true && file.canRead() == false) {
        System.err.println(CorbaResourceUtil.getText("bootstrap.filenotreadable", file.getAbsolutePath()));
        return;
    }
    // Success: start up
    System.out.println(CorbaResourceUtil.getText("bootstrap.success", Integer.toString(initialPort), file.getAbsolutePath()));
    Properties props = new Properties();
    // Use the SERVER_PORT to create an Acceptor using the
    // old legacy code in ORBConfiguratorImpl.  When (if?)
    // the legacy support is removed, this code will need
    // to create an Acceptor directly.
    props.put(ORBConstants.SERVER_PORT_PROPERTY, Integer.toString(initialPort));
    ORB orb = (ORB) org.omg.CORBA.ORB.init(args, props);
    LocalResolver lres = orb.getLocalResolver();
    Resolver fres = ResolverDefault.makeFileResolver(orb, file);
    Resolver cres = ResolverDefault.makeCompositeResolver(fres, lres);
    LocalResolver sres = ResolverDefault.makeSplitLocalResolver(cres, lres);
    orb.setLocalResolver(sres);
    try {
        // This causes the acceptors to start listening.
        orb.resolve_initial_references(ORBConstants.ROOT_POA_NAME);
    } catch (org.omg.CORBA.ORBPackage.InvalidName e) {
        RuntimeException rte = new RuntimeException("This should not happen");
        rte.initCause(e);
        throw rte;
    }
    orb.run();
}
Example 10
Project: jade_agents-master  File: MonitorAgentGUI.java View source code
/** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
@SuppressWarnings("unchecked")
private // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
void initComponents() {
    jComboBoxPlan = new javax.swing.JComboBox();
    jButtonProduce = new javax.swing.JButton();
    jSpinnerCount = new javax.swing.JSpinner();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    setTitle("Produce New Item");
    jComboBoxPlan.setModel(plans);
    jComboBoxPlan.addActionListener(new java.awt.event.ActionListener() {

        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jComboBoxPlanActionPerformed(evt);
        }
    });
    jButtonProduce.setText("Produce");
    jButtonProduce.addActionListener(new java.awt.event.ActionListener() {

        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonProduceActionPerformed(evt);
        }
    });
    jSpinnerCount.setModel(new javax.swing.SpinnerNumberModel(1, 1, 100, 1));
    jTable1.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {}, new String[] { "Component", "Count" }) {

        Class[] types = new Class[] { java.lang.String.class, java.lang.Integer.class };

        public Class getColumnClass(int columnIndex) {
            return types[columnIndex];
        }
    });
    jScrollPane1.setViewportView(jTable1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(jComboBoxPlan, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(jSpinnerCount, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jButtonProduce)).addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap()));
    layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jComboBoxPlan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jSpinnerCount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(jButtonProduce)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
    pack();
}
Example 11
Project: flink-master  File: User.java View source code
@Override
public User build() {
    try {
        User record = new User();
        record.name = fieldSetFlags()[0] ? this.name : (java.lang.CharSequence) defaultValue(fields()[0]);
        record.favorite_number = fieldSetFlags()[1] ? this.favorite_number : (java.lang.Integer) defaultValue(fields()[1]);
        record.favorite_color = fieldSetFlags()[2] ? this.favorite_color : (java.lang.CharSequence) defaultValue(fields()[2]);
        return record;
    } catch (Exception e) {
        throw new org.apache.avro.AvroRuntimeException(e);
    }
}
Example 12
Project: sonar-java-master  File: AssertionsWithoutMessageCheck.java View source code
void foo() {
    // Noncompliant [[sc=5;ec=38]] {{Add a message to this assertion.}}
    org.junit.Assert.assertTrue(true);
    org.junit.Assert.assertTrue("message", true);
    // Noncompliant {{Add a message to this assertion.}}
    org.junit.Assert.assertTrue(1 > 2);
    // Noncompliant
    org.junit.Assert.assertFalse(false);
    org.junit.Assert.assertFalse("message", false);
    org.junit.Assert.assertEquals("message", "foo", "bar");
    // Noncompliant
    org.junit.Assert.assertEquals("foo", "bar");
    // Noncompliant
    junit.framework.Assert.assertTrue(true);
    junit.framework.Assert.assertTrue("message", true);
    junit.framework.Assert.assertEquals("message", "foo", "bar");
    junit.framework.Assert.assertEquals("message", "foo", "bar");
    // Noncompliant
    junit.framework.Assert.assertEquals("foo", "bar");
    junit.framework.Assert.assertNotNull("foo", "bar");
    // Noncompliant
    junit.framework.Assert.assertNotNull("foo");
    // Noncompliant {{Add a message to this assertion.}}
    org.fest.assertions.Assertions.assertThat(true).isTrue();
    org.fest.assertions.Assertions.assertThat(true).as("verifying the truth").isTrue();
    org.fest.assertions.Assertions.Assertions.assertThat("").isEqualTo("").as("");
    // Noncompliant {{Add a message to this assertion.}}
    org.junit.Assert.assertThat("foo", null);
    org.junit.Assert.assertThat("foo", "bar", null);
    org.junit.Assert.assertThat("foo", new Integer(1), null);
    // Noncompliant
    junit.framework.Assert.assertNotSame("foo", "bar");
    junit.framework.Assert.assertNotSame("foo", "foo", "bar");
    // Noncompliant
    junit.framework.Assert.assertSame("foo", "bar");
    junit.framework.Assert.assertSame("foo", "foo", "bar");
    // Noncompliant
    org.junit.Assert.fail();
    org.junit.Assert.fail("Foo");
    // Noncompliant
    junit.framework.Assert.fail();
    junit.framework.Assert.fail("Foo");
    // Noncompliant
    org.fest.assertions.Fail.fail();
    org.fest.assertions.Fail.fail("foo");
    org.fest.assertions.Fail.fail("foo", null);
    org.fest.assertions.Fail.failure("foo");
}
Example 13
Project: JBossAS51-master  File: PropertyEditorsUnitTestCase.java View source code
/** The mechanism for mapping java.lang.* variants of the primative types
    misses editors for java.lang.Boolean and java.lang.Integer. Here we test
    the java.lang.* variants we expect editors for.
    **/
public void testJavaLangEditors() throws Exception {
    getLog().debug("+++ testJavaLangEditors");
    // The supported java.lang.* types
    Class[] types = { Boolean.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Byte.class, Character.class };
    // The input string data for each type
    String[][] inputData = { { "true", "false", "TRUE", "FALSE", "tRuE", "FaLsE", null }, { "1", "-1", "0", "0x1A" }, { "1", "-1", "0", "0xA0" }, { "1", "-1", "0", "0xA0" }, { "1", "-1", "0", "1000" }, { "1", "-1", "0", "1000.1" }, { "1", "-1", "0", "1000.1" }, { "0x1", "-#1", "0" }, { "A", "a", "Z", "z" } };
    // The expected java.lang.* instance for each inputData value
    Object[][] expectedData = { { Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null }, { Byte.valueOf("1"), Byte.valueOf("-1"), Byte.valueOf("0"), Byte.decode("0x1A") }, { Short.valueOf("1"), Short.valueOf("-1"), Short.valueOf("0"), Short.decode("0xA0") }, { Integer.valueOf("1"), Integer.valueOf("-1"), Integer.valueOf("0"), Integer.decode("0xA0") }, { Long.valueOf("1"), Long.valueOf("-1"), Long.valueOf("0"), Long.valueOf("1000") }, { Float.valueOf("1"), Float.valueOf("-1"), Float.valueOf("0"), Float.valueOf("1000.1") }, { Double.valueOf("1"), Double.valueOf("-1"), Double.valueOf("0"), Double.valueOf("1000.1") }, { Byte.valueOf("1"), Byte.valueOf("-1"), Byte.valueOf("0") }, { new Character('A'), new Character('a'), new Character('Z'), new Character('z') } };
    // The expected string output from getAsText()
    String[][] expectedStringData = { { "true", "false", "true", "false", "true", "false", "null" }, { "1", "-1", "0", "26" }, { "1", "-1", "0", "160" }, { "1", "-1", "0", "160" }, { "1", "-1", "0", "1000" }, { "1.0", "-1.0", "0.0", "1000.1" }, { "1.0", "-1.0", "0.0", "1000.1" }, { "1", "-1", "0" }, { "A", "a", "Z", "z" } };
    Comparator[] comparators = new Comparator[types.length];
    doTests(types, inputData, expectedData, expectedStringData, comparators);
}
Example 14
Project: StreamCruncher-master  File: PreFilterTriggerTest.java View source code
@Override
protected String[] getColumnTypes() {
    /*
         * "country", "state", "city", "item_sku", "item_qty", "order_time",
         * "order_id"
         */
    return new String[] { RowSpec.addInfo(java.lang.String.class.getName(), Info.SIZE, 15), RowSpec.addInfo(java.lang.String.class.getName(), Info.SIZE, 15), RowSpec.addInfo(java.lang.String.class.getName(), Info.SIZE, 15), RowSpec.addInfo(java.lang.String.class.getName(), Info.SIZE, 15), java.lang.Integer.class.getName(), java.sql.Timestamp.class.getName(), java.lang.Long.class.getName() };
}
Example 15
Project: framework-master  File: AbsFieldValueConversionErrorTest.java View source code
@Test
public void testConvertToModelConversionErrorParameters() {
    TextField tf = new TextField();
    tf.setConverter(new StringToIntegerConverter());
    tf.setPropertyDataSource(new MethodProperty<String>(paulaBean, "age"));
    tf.setConversionError("(Type: {0}) Converter exception message: {1}");
    tf.setValue("abc");
    try {
        tf.getConvertedValue();
        fail();
    } catch (ConversionException e) {
        Assert.assertEquals("(Type: Integer) Converter exception message: Could not convert 'abc' to java.lang.Integer", e.getMessage());
    }
}
Example 16
Project: assertj-db-master  File: AssertionsOnColumnOfChangeClass_IsOfClass_Test.java View source code
/**
   * This method should fail because the value at start point have different class.
   */
@Test
public void should_fail_because_value_at_start_point_have_different_type() throws Exception {
    WritableAssertionInfo info = new WritableAssertionInfo();
    info.description("description");
    Table table = new Table();
    TableAssert tableAssert = assertThat(table);
    try {
        AssertionsOnColumnOfChangeClass.isOfClass(tableAssert, info, getValue(null, 8), getValue(null, "test"), String.class, false);
        fail("An exception must be raised");
    } catch (AssertionError e) {
        Assertions.assertThat(e.getMessage()).isEqualTo(String.format("[description] %n" + "Expecting that the value at start point:%n" + "  <8>%n" + "to be of class%n" + "  <java.lang.String>%n" + "but was of class%n" + "  <java.lang.Integer>"));
    }
    try {
        AssertionsOnColumnOfChangeClass.isOfClass(tableAssert, info, getValue(null, null), getValue(null, "test"), String.class, false);
        fail("An exception must be raised");
    } catch (AssertionError e) {
        Assertions.assertThat(e.getMessage()).isEqualTo(String.format("[description] %n" + "Expecting that the value at start point:%n" + "  <null>%n" + "to be of class%n" + "  <java.lang.String>"));
    }
}
Example 17
Project: FireflowEngine20-master  File: CallSubflowTest1.java View source code
/* 
	 * 
	 * 主流程:Start-->Activity1(call subflow)-->End
	 * 
	 * 子流程: Start-->Activity2-->End
	 * 
	 * @see org.fireflow.FireWorkflowJunitEnviroment#createWorkflowProcess()
	 */
@Override
public WorkflowProcess createWorkflowProcess() {
    WorkflowProcessImpl process = new WorkflowProcessImpl(processName, processDisplayName);
    process.setDescription(description);
    //一、创建主流程
    SubProcess mainflow = process.getMainSubProcess();
    //流程变量x
    PropertyImpl property = new PropertyImpl(mainflow, "id");
    property.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.String"));
    property.setInitialValueAsString(bizId);
    mainflow.getProperties().add(property);
    //流程变量x
    property = new PropertyImpl(mainflow, "response1");
    property.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.String"));
    property.setInitialValueAsString("OK");
    mainflow.getProperties().add(property);
    //流程变量x
    property = new PropertyImpl(mainflow, "response2");
    property.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.Integer"));
    property.setInitialValueAsString("1");
    mainflow.getProperties().add(property);
    mainflow.setDuration(new Duration(5, Duration.MINUTE));
    StartNodeImpl startNode = new StartNodeImpl(process.getMainSubProcess(), "Start");
    ActivityImpl activity = new ActivityImpl(process.getMainSubProcess(), "Activity1");
    activity.setDuration(new Duration(6, Duration.DAY));
    //流程变量x
    property = new PropertyImpl(activity, "approveResult");
    property.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.String"));
    property.setInitialValueAsString("This is the result!");
    activity.getProperties().add(property);
    EndNodeImpl endNode = new EndNodeImpl(process.getMainSubProcess(), "End");
    mainflow.setEntry(startNode);
    mainflow.getStartNodes().add(startNode);
    mainflow.getActivities().add(activity);
    mainflow.getEndNodes().add(endNode);
    TransitionImpl transition1 = new TransitionImpl(process.getMainSubProcess(), "start2activity");
    transition1.setFromNode(startNode);
    transition1.setToNode(activity);
    startNode.getLeavingTransitions().add(transition1);
    activity.getEnteringTransitions().add(transition1);
    TransitionImpl transition2 = new TransitionImpl(process.getMainSubProcess(), "activity2end");
    transition2.setFromNode(activity);
    transition2.setToNode(endNode);
    activity.getLeavingTransitions().add(transition2);
    endNode.getEnteringTransitions().add(transition2);
    mainflow.getTransitions().add(transition1);
    mainflow.getTransitions().add(transition2);
    //二、创建子流程
    SubProcess subflow2 = new SubProcessImpl(process, "subflow2");
    process.addSubProcess(subflow2);
    //流程变量x
    PropertyImpl property4Subflow2 = new PropertyImpl(subflow2, "id");
    property4Subflow2.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.String"));
    property4Subflow2.setInitialValueAsString("");
    subflow2.getProperties().add(property4Subflow2);
    //流程变量x
    property4Subflow2 = new PropertyImpl(subflow2, "result");
    property4Subflow2.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.String"));
    property4Subflow2.setInitialValueAsString("OK");
    subflow2.getProperties().add(property4Subflow2);
    //流程变量x
    property4Subflow2 = new PropertyImpl(subflow2, "reply1");
    property4Subflow2.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.String"));
    property4Subflow2.setInitialValueAsString("It is OK");
    subflow2.getProperties().add(property4Subflow2);
    //流程变量x
    property4Subflow2 = new PropertyImpl(subflow2, "reply2");
    property4Subflow2.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.Integer"));
    property4Subflow2.setInitialValueAsString("10");
    subflow2.getProperties().add(property4Subflow2);
    subflow2.setDuration(new Duration(5, Duration.MINUTE));
    StartNodeImpl startNode2 = new StartNodeImpl(subflow2, "Start2");
    ActivityImpl activity2 = new ActivityImpl(subflow2, "Activity2");
    activity2.setDuration(new Duration(6, Duration.DAY));
    EndNodeImpl endNode2 = new EndNodeImpl(subflow2, "End2");
    subflow2.setEntry(startNode2);
    subflow2.getStartNodes().add(startNode2);
    subflow2.getActivities().add(activity2);
    subflow2.getEndNodes().add(endNode2);
    TransitionImpl transition1_subflow2 = new TransitionImpl(subflow2, "start2activity");
    transition1_subflow2.setFromNode(startNode2);
    transition1_subflow2.setToNode(activity2);
    startNode2.getLeavingTransitions().add(transition1_subflow2);
    activity2.getEnteringTransitions().add(transition1_subflow2);
    TransitionImpl transition2_subflow2 = new TransitionImpl(subflow2, "activity2end");
    transition2_subflow2.setFromNode(activity2);
    transition2_subflow2.setToNode(endNode2);
    activity2.getLeavingTransitions().add(transition2_subflow2);
    endNode2.getEnteringTransitions().add(transition2_subflow2);
    subflow2.getTransitions().add(transition1_subflow2);
    subflow2.getTransitions().add(transition2_subflow2);
    //三、创建SubflowService 并绑定到activity1
    CallServiceDef subflowService = new CallServiceDef();
    subflowService.setName("call_subflow2");
    subflowService.setTargetNamespaceUri("http://CallSubflowTest1");
    subflowService.setProcessId(this.processName);
    subflowService.setSubProcessId(subflow2.getId());
    CommonInterfaceDef commonInterface = new CommonInterfaceDef();
    commonInterface.setName("call_subflow2_interface");
    subflowService.setInterface(commonInterface);
    OperationDefImpl op = new OperationDefImpl();
    op.setOperationName("callSubflow");
    commonInterface.getOperations().add(op);
    InputImpl input = new InputImpl();
    input.setName("id");
    input.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.String"));
    op.getInputs().add(input);
    input = new InputImpl();
    input.setName("result");
    input.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.String"));
    op.getInputs().add(input);
    OutputImpl output = new OutputImpl();
    output.setName("reply1");
    output.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.String"));
    op.getOutputs().add(output);
    output = new OutputImpl();
    output.setName("reply2");
    output.setDataType(new QName(NameSpaces.JAVA.getUri(), "java.lang.Integer"));
    op.getOutputs().add(output);
    //绑定
    ServiceBindingImpl svcBinding = new ServiceBindingImpl();
    //		svcBinding.setService(subflowService);
    svcBinding.setServiceId(subflowService.getId());
    //		svcBinding.setOperation(op);
    svcBinding.setOperationName(op.getOperationName());
    //io输入映射
    // processVars.id-->inputs.id
    AssignmentImpl assignment = new AssignmentImpl();
    ExpressionImpl from = new ExpressionImpl();
    from.setBody(ScriptContextVariableNames.PROCESS_VARIABLES + "/id");
    from.setLanguage("XPATH");
    from.getNamespaceMap().put("ns0", subflowService.getTargetNamespaceUri());
    assignment.setFrom(from);
    ExpressionImpl to = new ExpressionImpl();
    to.setBody(ScriptContextVariableNames.INPUTS + "/" + "id");
    to.setLanguage("XPATH");
    to.setName("id");
    assignment.setTo(to);
    svcBinding.getInputAssignments().add(assignment);
    // activityVars.approveResult-->inputs.result
    assignment = new AssignmentImpl();
    from = new ExpressionImpl();
    from.setBody(ScriptContextVariableNames.ACTIVITY_VARIABLES + "/" + "approveResult");
    from.setLanguage("XPATH");
    from.getNamespaceMap().put("ns0", subflowService.getTargetNamespaceUri());
    assignment.setFrom(from);
    to = new ExpressionImpl();
    to.setBody(ScriptContextVariableNames.INPUTS + "/result");
    to.setLanguage("XPATH");
    to.setName("result");
    assignment.setTo(to);
    svcBinding.getInputAssignments().add(assignment);
    //io输出映射
    // output.reply1-->processVars.response1
    assignment = new AssignmentImpl();
    from = new ExpressionImpl();
    from.setBody(ScriptContextVariableNames.OUTPUTS + "/reply1");
    from.setLanguage("XPATH");
    assignment.setFrom(from);
    to = new ExpressionImpl();
    to.setBody(ScriptContextVariableNames.PROCESS_VARIABLES + "/response1");
    to.setName("response1");
    to.setLanguage("XPATH");
    to.getNamespaceMap().put("ns0", subflowService.getTargetNamespaceUri());
    assignment.setTo(to);
    svcBinding.getOutputAssignments().add(assignment);
    // output.reply2-->processVars.response2
    assignment = new AssignmentImpl();
    from = new ExpressionImpl();
    from.setBody(ScriptContextVariableNames.OUTPUTS + "/reply2");
    from.setLanguage("XPATH");
    assignment.setFrom(from);
    to = new ExpressionImpl();
    to.setBody(ScriptContextVariableNames.PROCESS_VARIABLES + "/response2");
    to.setLanguage("XPATH");
    to.setName("response2");
    to.getNamespaceMap().put("ns0", subflowService.getTargetNamespaceUri());
    assignment.setTo(to);
    svcBinding.getOutputAssignments().add(assignment);
    //设置到activity和workflowprocess
    process.addService(subflowService);
    activity.setServiceBinding(svcBinding);
    return process;
}
Example 18
Project: java-string-algorithms-master  File: BoyerMooreTest.java View source code
@Test
@Ignore
public void benchmark() throws Exception {
    File beowulf = new File(getClass().getClassLoader().getResource("anonymous-beowulf-543.txt").getFile());
    final String beowulfText = Files.toString(beowulf, Charsets.UTF_8);
    final String search = "Beowulf finally accepted Hygd's offer of kingdom and hoard";
    final StringFinder stringFinder = searchApi().compileFinder(search);
    TestHelp.Callback<Integer> callback = new TestHelp.Callback<java.lang.Integer>() {

        int garbage;

        @Override
        public void consume(Integer value) {
            garbage |= value;
        }
    };
    Callable<Integer> stringIndexOf = new Callable<Integer>() {

        @SuppressWarnings({ "RedundantStringConstructorCall" })
        @Override
        public Integer call() throws Exception {
            return new String(beowulfText).indexOf(search);
        }
    };
    Callable<Integer> boyerMoore = new Callable<Integer>() {

        @SuppressWarnings({ "RedundantStringConstructorCall" })
        @Override
        public Integer call() throws Exception {
            return stringFinder.indexIn(new String(beowulfText));
        }
    };
    timeMultipleCalls(stringIndexOf, 100, callback, TimeUnit.DAYS);
    timeMultipleCalls(boyerMoore, 100, callback, TimeUnit.DAYS);
    System.gc();
    Thread.sleep(500L);
    System.gc();
    for (int i = 0; i < 10; i++) {
        timeAndLogMultipleCalls("String.indexOf", stringIndexOf, 10000, callback, TimeUnit.MILLISECONDS);
        timeAndLogMultipleCalls("  Boyter-Moore", boyerMoore, 10000, callback, TimeUnit.MILLISECONDS);
    }
}
Example 19
Project: eclipse.jdt.ui-master  File: ChangeTypeRefactoringTests.java View source code
public void testNestedParametricHashtable() throws Exception {
    Collection<String> types = helper1(6, 9, 6, 44, "java.util.Dictionary<java.lang.String,java.util.Vector<java.lang.Integer>>").getValidTypeNames();
    String[] actual = types.toArray(new String[types.size()]);
    String[] expected = { "java.util.Map<java.lang.String,java.util.Vector<java.lang.Integer>>", "java.util.Dictionary<java.lang.String,java.util.Vector<java.lang.Integer>>", "java.lang.Object", "java.lang.Cloneable", "java.io.Serializable" };
    StringAsserts.assertEqualStringsIgnoreOrder(actual, expected);
}
Example 20
Project: powermock-master  File: PrimitiveAndWrapperDemoTest.java View source code
@Test
public void testWhenConstructorCannotBeDetermined() throws Exception {
    try {
        createMockAndExpectNew(PrimitiveAndWrapperDemo.class, 2);
        fail("Should throw TooManyConstructorsFoundException");
    } catch (TooManyConstructorsFoundException e) {
        assertThat(e.getMessage(), containsString("Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to." + "\nMatching constructors in class samples.expectnew.PrimitiveAndWrapperDemo were:\n"));
        assertThat(e.getMessage(), containsString("samples.expectnew.PrimitiveAndWrapperDemo( java.lang.Integer.class )\n"));
        assertThat(e.getMessage(), containsString("samples.expectnew.PrimitiveAndWrapperDemo( int.class )\n"));
    }
}
Example 21
Project: gpu-garbage-collection-master  File: TestClassLoading.java View source code
public static void main(String[] args) {
    doTest("java.lang.String");
    //Can't instantiate abstract classes
    doTest("java.lang.Number");
    //Can't instantiate as no default constructor
    doTest("java.lang.Integer");
    //Can't instantiate arrays
    doTest("[Ljava.lang.String;");
    //Can't instantiate arrays
    doTest("[[Ljava.lang.String;");
    //Can't instantiate arrays
    doTest("[I");
    //Can't instantiate arrays
    doTest("[[I");
    //Can not load classes for primitives
    doTest("I");
    //Non existent class
    doTest("NoExist");
}
Example 22
Project: sisu-guice-master  File: BoundFieldModuleTest.java View source code
public void testBindingIncorrectTypeProviderFails() {
    final Integer testValue = 1024;
    Object instance = new Object() {

        @Bind(to = String.class)
        private Provider<Integer> anIntProvider = new Provider<Integer>() {

            @Override
            public Integer get() {
                return testValue;
            }
        };
    };
    BoundFieldModule module = BoundFieldModule.of(instance);
    try {
        Guice.createInjector(module);
        fail();
    } catch (CreationException e) {
        assertContains(e.getMessage(), "Requested binding type \"java.lang.String\" is not " + "assignable from field binding type \"java.lang.Integer\"");
    }
}
Example 23
Project: jadira-master  File: PortableCloneStrategy.java View source code
@Override
protected <T> void handleTransientField(T copy, FieldModel<T> f) {
    Class<?> clazz = f.getField().getType();
    try {
        if (clazz.isPrimitive()) {
            if (java.lang.Boolean.TYPE == clazz) {
                f.getField().setBoolean(copy, false);
            } else if (java.lang.Byte.TYPE == clazz) {
                f.getField().setByte(copy, (byte) 0);
            } else if (java.lang.Character.TYPE == clazz) {
                f.getField().setChar(copy, CHAR_NULL);
            } else if (java.lang.Short.TYPE == clazz) {
                f.getField().setShort(copy, (short) 0);
            } else if (java.lang.Integer.TYPE == clazz) {
                f.getField().setInt(copy, 0);
            } else if (java.lang.Long.TYPE == clazz) {
                f.getField().setLong(copy, 0L);
            } else if (java.lang.Float.TYPE == clazz) {
                f.getField().setFloat(copy, 0.0F);
            } else if (java.lang.Double.TYPE == clazz) {
                f.getField().setDouble(copy, 0.0D);
            }
        } else {
            f.getField().set(copy, null);
        }
    } catch (IllegalArgumentException e) {
        throw new IllegalStateException("Problem performing clone for field {" + f.getField().getName() + "} of object {" + System.identityHashCode(copy) + "}: " + e.getMessage(), e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Problem performing clone for field {" + f.getField().getName() + "} of object {" + System.identityHashCode(copy) + "}: " + e.getMessage(), e);
    }
}
Example 24
Project: openjdk8-jdk-master  File: NotifExecutorTest.java View source code
public static void main(String[] args) throws Exception {
    System.out.println("Tests to use an executor to send notifications.");
    final MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    final ObjectName mbean = new ObjectName("Default:name=NotificationEmitter");
    final MyListener myLister = new MyListener();
    final NotificationListener nullListener = new NotificationListener() {

        public void handleNotification(Notification n, Object hb) {
        // nothing
        }
    };
    final Object[] params = new Object[] { new Integer(nb) };
    final String[] signatures = new String[] { "java.lang.Integer" };
    // test with null executor
    System.out.println(">>> Test with a null executor.");
    mbs.registerMBean(new NotificationEmitter(null), mbean);
    mbs.addNotificationListener(mbean, myLister, null, null);
    mbs.addNotificationListener(mbean, nullListener, null, null);
    mbs.invoke(mbean, "sendNotifications", params, signatures);
    check(nb, 0);
    mbs.unregisterMBean(mbean);
    // test with an executor
    System.out.println(">>> Test with a executor.");
    mbs.registerMBean(new NotificationEmitter(new NotifExecutorTest.MyExecutor()), mbean);
    mbs.addNotificationListener(mbean, myLister, null, null);
    mbs.addNotificationListener(mbean, nullListener, null, null);
    mbs.invoke(mbean, "sendNotifications", params, signatures);
    check(nb, nb * 2);
    // test without listener
    System.out.println(">>> Test without listener.");
    mbs.removeNotificationListener(mbean, myLister);
    mbs.removeNotificationListener(mbean, nullListener);
    mbs.invoke(mbean, "sendNotifications", params, signatures);
    check(0, 0);
}
Example 25
Project: eclipse.jdt.core-master  File: TypeUtilsProc.java View source code
/**
	 * Test the implementation of primitive types and the getPrimitiveType() method
	 * @return true if tests passed
	 */
private boolean examinePrimitives() {
    TypeElement integerElement = _elementUtils.getTypeElement("java.lang.Integer");
    if (null == integerElement) {
        reportError("Failed to get element java.lang.Integer");
        return false;
    }
    TypeMirror integerType = integerElement.asType();
    if (null == integerType) {
        reportError("Failed to get element java.lang.Integer as a type");
        return false;
    }
    TypeMirror intType = _typeUtils.getPrimitiveType(TypeKind.INT);
    if (null == intType || intType.getKind() != TypeKind.INT) {
        reportError("Failed to get primitive type INT");
        return false;
    }
    TypeMirror floatType = _typeUtils.getPrimitiveType(TypeKind.FLOAT);
    if (null == floatType || floatType.getKind() != TypeKind.FLOAT) {
        reportError("Failed to get primitive type FLOAT");
        return false;
    }
    if (!intType.equals(_typeUtils.unboxedType(integerType))) {
        reportError("unboxedType(java.lang.Integer) is not primitive int");
        return false;
    }
    if (!_typeUtils.isAssignable(intType, floatType)) {
        reportError("isAssignable(int, float) should be true");
        return false;
    }
    if (_typeUtils.isAssignable(floatType, intType)) {
        reportError("isAssignable(float, int) should be false");
        return false;
    }
    // TYPE IDENTITY
    if (_typeUtils.isSameType(intType, floatType)) {
        reportError("Primitive type int is reported to be same as float");
        return false;
    }
    if (!_typeUtils.isSameType(floatType, floatType)) {
        reportError("Primitive type float is reported to not be same as itself");
        return false;
    }
    // SUBTYPES
    if (!_typeUtils.isSubtype(intType, intType)) {
        reportError("Primitive type int is not a subtype of itself");
        return false;
    }
    if (!_typeUtils.isSubtype(intType, floatType)) {
        reportError("Primitive type int is not a subtype of float");
        return false;
    }
    if (_typeUtils.isSubtype(floatType, intType)) {
        reportError("Primitive type float is a subtype of int");
        return false;
    }
    // BOXING
    if (!_typeUtils.isAssignable(intType, integerType)) {
        reportError("isAssignable(int, java.lang.Integer) should be true");
        return false;
    }
    if (!_typeUtils.isAssignable(integerType, intType)) {
        reportError("isAssignable(java.lang.Integer, int) should be true");
        return false;
    }
    if (!_typeUtils.isAssignable(integerType, floatType)) {
        reportError("isAssignable(java.lang.Integer, float) should be true");
        return false;
    }
    if (_typeUtils.isAssignable(floatType, integerType)) {
        reportError("isAssignable(float, java.lang.Integer) should be false");
        return false;
    }
    TypeMirror erasureOfInt = _typeUtils.erasure(intType);
    if (erasureOfInt != intType) {
        reportError("erasure of a primitive type is the type itself");
        return false;
    }
    return true;
}
Example 26
Project: Strata-master  File: ResultsTest.java View source code
public void nonEmpty() {
    Results test = Results.of(ImmutableList.of(HEADER1, HEADER2, HEADER3), results("1", "2", "3", "4", "5", "6"));
    assertEquals(test.getColumns(), ImmutableList.of(HEADER1, HEADER2, HEADER3));
    assertEquals(test.getRowCount(), 2);
    assertEquals(test.getColumnCount(), 3);
    assertEquals(test.get(0, 0).getValue(), "1");
    assertEquals(test.get(0, 0, String.class).getValue(), "1");
    assertEquals(test.get(0, NAME_A).getValue(), "1");
    assertEquals(test.get(0, NAME_A, String.class).getValue(), "1");
    assertEquals(test.get(0, NAME_B).getValue(), "2");
    assertEquals(test.get(0, NAME_B, String.class).getValue(), "2");
    assertEquals(test.get(1, 2).getValue(), "6");
    assertThrows(() -> test.get(-1, 0), IllegalArgumentException.class, "Row index must be greater than or.*");
    assertThrows(() -> test.get(2, 0), IllegalArgumentException.class, "Row index must be greater than or.*");
    assertThrows(() -> test.get(0, -1), IllegalArgumentException.class, "Column index must be greater than or.*");
    assertThrows(() -> test.get(0, 3), IllegalArgumentException.class, "Column index must be greater than or.*");
    assertThrows(() -> test.get(0, 0, Integer.class), ClassCastException.class, "Result queried with type 'java.lang.Integer' but was 'java.lang.String'");
    assertThrows(() -> test.get(0, NAME_A, Integer.class), ClassCastException.class, "Result queried with type 'java.lang.Integer' but was 'java.lang.String'");
}
Example 27
Project: MyFramework-master  File: DatabaseDataTypesUtils.java View source code
public static String getPreferredJavaType(int sqlType, int size, int decimalDigits) {
    if ((sqlType == Types.DECIMAL || sqlType == Types.NUMERIC) && decimalDigits == 0) {
        if (size == 1) {
            // https://sourceforge.net/tracker/?func=detail&atid=415993&aid=662953&group_id=36044
            return "java.lang.Boolean";
        } else if (//[2,2]
        size < 3) {
            return "java.lang.Byte";
        } else if (//[3,4]
        size < 5) {
            return "java.lang.Short";
        } else if (//[5,9]
        size < //[5,9]
        10) {
            return "java.lang.Integer";
        } else if (size < 19) {
            return "java.lang.Long";
        } else {
            return "java.math.BigDecimal";
        }
    }
    String result = _preferredJavaTypeForSqlType.getString(sqlType);
    if (result == null) {
        result = "java.lang.Object";
    }
    return result;
}
Example 28
Project: powerunit-master  File: AssumeThatTests.java View source code
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
    AllTests.testNoException("testAssumeThatIsObjectOKWithoutMessage", () -> TestSuite.DSL.assumeThat("x").is("x"));
    AllTests.testException("testAssumeThatIsObjectKOWithoutMessage", () -> TestSuite.DSL.assumeThat("x").is("xy"), "expecting \"xy\" but was \"x\"");
    AllTests.testNoException("testAssumeThatIsObjectOKWithMessage", () -> TestSuite.DSL.assumeThat("msg", "x").is("x"));
    AllTests.testException("testAssumeThatIsObjectKOWithMessage", () -> TestSuite.DSL.assumeThat("msg", "x").is("xy"), "msg\nexpecting \"xy\" but was \"x\"");
    AllTests.testNoException("testAssumeThatIsNotObjectOKWithoutMessage", () -> TestSuite.DSL.assumeThat("x").isNot("y"));
    AllTests.testException("testAssumeThatIsNotObjectKOWithoutMessage", () -> TestSuite.DSL.assumeThat("x").isNot("x"), "expecting not \"x\" but was \"x\"");
    AllTests.testNoException("testAssumeThatIsNotObjectOKWithMessage", () -> TestSuite.DSL.assumeThat("msg", "x").isNot("y"));
    AllTests.testException("testAssumeThatIsNotObjectKOWithMessage", () -> TestSuite.DSL.assumeThat("msg", "x").isNot("x"), "msg\nexpecting not \"x\" but was \"x\"");
    AllTests.testNoException("testAssumeThatIsNullOKWithoutMesage", () -> TestSuite.DSL.assumeThat((Object) null).isNull());
    AllTests.testException("testAssumeThatIsNullKOWithoutMesage", () -> TestSuite.DSL.assumeThat("x").isNull(), "expecting null but was \"x\"");
    AllTests.testNoException("testAssumeThatIsNullOKWithMesage", () -> TestSuite.DSL.assumeThat("msg", (Object) null).isNull());
    AllTests.testException("testAssumeThatIsNullKOWithMesage", () -> TestSuite.DSL.assumeThat("msg", "x").isNull(), "msg\nexpecting null but was \"x\"");
    AllTests.testNoException("testAssumeThatIsNotNullOKWithoutMesage", () -> TestSuite.DSL.assumeThat("x").isNotNull());
    AllTests.testException("testAssumeThatIsNotNullKOWithoutMesage", () -> TestSuite.DSL.assumeThat((Object) null).isNotNull(), "expecting not null but was null");
    AllTests.testNoException("testAssumeThatIsNotNullOKWithMesage", () -> TestSuite.DSL.assumeThat("msg", "x").isNotNull());
    AllTests.testException("testAssumeThatIsNotNullKOWithMesage", () -> TestSuite.DSL.assumeThat("msg", (Object) null).isNotNull(), "msg\nexpecting not null but was null");
    //
    AllTests.testNoException("testAssumeThatIsAOKWithoutMesage", () -> TestSuite.DSL.assumeThat("x").isA(String.class));
    AllTests.testException("testAssumeThatIsAKOWithoutMesage", () -> TestSuite.DSL.assumeThat("x").isA((Class) Integer.class), "expecting is an instance of java.lang.Integer but \"x\" is a java.lang.String");
    AllTests.testNoException("testAssumeThatIsAOKWithMesage", () -> TestSuite.DSL.assumeThat("msg", "x").isA(String.class));
    AllTests.testException("testAssumeThatIIsAKOWithMesage", () -> TestSuite.DSL.assumeThat("msg", "x").isA((Class) Integer.class), "msg\nexpecting is an instance of java.lang.Integer but \"x\" is a java.lang.String");
    AllTests.testNoException("testAssumeThatAsOK", () -> {
        TestSuite.DSL.assumeThat((Number) Integer.valueOf(0)).as(Integer.class).is(0);
    });
    AllTests.testException("testAssumeThatAsKONull", () -> {
        TestSuite.DSL.assumeThat((Number) Integer.valueOf(0)).as(null);
    }, "clazz argument can't be null");
    AllTests.testException("testAssumeThatAsKOType", () -> {
        TestSuite.DSL.assumeThat((Number) Integer.valueOf(0)).as(Double.class).is(0d);
    }, "The value 0 can't be casted to java.lang.Double");
}
Example 29
Project: gluu-opendj-master  File: PSearch.java View source code
public static void main(String[] args) {
    String usage = "Usage: psearch -h <hostname> -p <port> -b <suffix>" + "[-D bindDN] [-w bindPW]" + "-f <fileURL+file name>" + "-s" + "-n <number of thread>" + " -o <add,modify,delete,moddn>" + " -l";
    String hostname = "localhost";
    //LDAPv3.DEFAULT_PORT;
    int portnumber = 1389;
    //number of thread by default
    int nbThreads = 1;
    // Check for these options. -H means to print out a usage message.
    GetOpt options = new GetOpt("h:p:b:D:w:H:f:n:o:s:l", args);
    // Get the arguments specified for each option.
    String host = options.getOptionParam('h');
    // host
    if (options.hasOption('h')) {
        if (host == null) {
            // usage
            System.out.println(usage);
            System.exit(1);
        } else {
            hostname = host;
        }
    }
    String port = options.getOptionParam('p');
    // to an integer.
    if (port != null) {
        try {
            portnumber = java.lang.Integer.parseInt(port);
        } catch (java.lang.Exception e) {
            System.out.println("Invalid port number: " + port);
            System.out.println(usage);
            System.exit(1);
        }
    }
    //number of thread
    String nbT = options.getOptionParam('n');
    if (nbT != null) {
        try {
            nbThreads = java.lang.Integer.parseInt(nbT);
        } catch (java.lang.Exception e) {
            System.out.println("Invalid Thread number: " + nbT);
            System.out.println(usage);
            System.exit(1);
        }
    }
    // PSearch suffix
    String suffix = options.getOptionParam('b');
    String bindDN = options.getOptionParam('D');
    String bindPW = options.getOptionParam('w');
    //operations all by default
    String operation = PSearchOperations.ALL;
    if (options.hasOption('o')) {
        String opParam = options.getOptionParam('o');
        if (opParam.equals("add")) {
            operation = PSearchOperations.ADD;
        } else if (opParam.equals("modify")) {
            operation = PSearchOperations.MODIFY;
        } else if (opParam.equals("delete")) {
            operation = PSearchOperations.DELETE;
        } else if (opParam.equals("moddn")) {
            operation = PSearchOperations.MODDN;
        } else if (opParam.equals("all")) {
            operation = PSearchOperations.ALL;
            ;
        } else {
            System.out.println("Invalid operation type: " + opParam);
            System.out.println(usage);
            System.exit(1);
        }
    }
    // to disable the log files
    boolean useFile = false;
    String fileName = "logLile";
    if (options.hasOption('f')) {
        useFile = options.hasOption('f');
        fileName = options.getOptionParam('f');
    }
    // to enable diff format
    boolean ldifFormat = options.hasOption('l');
    // to enable system out logs
    boolean output = options.hasOption('s');
    System.out.println("Connecting to " + hostname + ":" + portnumber + " as \"" + bindDN + "\"" + " on suffix \"" + suffix + "\"" + " on operation \"" + operation + "\"" + " use file: \"" + useFile + "\" output: \"" + output + "\"");
    for (int i = 0; i < nbThreads; i++) {
        PSearchOperations ps = new PSearchOperations(i, hostname, portnumber, bindDN, bindPW, suffix);
        if (useFile) {
            ps.useLogFile(useFile);
            ps.setLogFile(fileName);
        }
        ps.setOutput(output);
        ps.setLdifFormat(ldifFormat);
        ps.setOperation(operation);
        ps.start();
    }
    try {
        STAFHandle handle = new STAFHandle("PSearch listener");
        handle.submit2(hostname, "SEM", "PULSE EVENT PSearch/Ready");
        handle.submit2(hostname, "SEM", "WAIT EVENT PSearch tests/Completed");
        handle.submit2(hostname, "SEM", "DELETE EVENT PSearch tests/Completed");
        System.exit(0);
    } catch (Exception e) {
        System.out.println("STAF Handle fail");
    }
}
Example 30
Project: castor-master  File: AddressJDODescriptor.java View source code
/**
     * @param choice
     * @return jdo field descriptor for id
     */
private FieldDescriptor initId(final ClassChoice choice) {
    String idFieldName = "id";
    FieldDescriptorImpl idFieldDescr;
    FieldMapping idFM = new FieldMapping();
    TypeInfo idType = new TypeInfo(java.lang.Integer.class);
    // Set columns required (=not null)
    idType.setRequired(true);
    FieldHandler idHandler;
    try {
        idHandler = new FieldHandlerImpl(idFieldName, null, null, Address.class.getMethod("getId"), Address.class.getMethod("setId", new Class[] { int.class }), idType);
    } catch (SecurityException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1.getMessage());
    } catch (MappingException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1.getMessage());
    } catch (NoSuchMethodException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1.getMessage());
    }
    // Instantiate title field descriptor
    idFieldDescr = new FieldDescriptorImpl(idFieldName, idType, idHandler, false);
    idFieldDescr.addNature(FieldDescriptorJDONature.class.getName());
    FieldDescriptorJDONature idJdoNature = new FieldDescriptorJDONature(idFieldDescr);
    idJdoNature.setSQLName(new String[] { idFieldName });
    idJdoNature.setSQLType(new int[] { SQLTypeInfos.javaType2sqlTypeNum(java.lang.Integer.class) });
    idJdoNature.setManyKey(null);
    idJdoNature.setDirtyCheck(false);
    idJdoNature.setReadOnly(false);
    // Set parent class descriptor
    idFieldDescr.setContainingClassDescriptor(this);
    idFieldDescr.setClassDescriptor(this);
    idFieldDescr.setIdentity(true);
    idFM.setIdentity(true);
    idFM.setDirect(false);
    idFM.setName("id");
    idFM.setRequired(true);
    idFM.setSetMethod("setId");
    idFM.setGetMethod("getId");
    idFM.setType("integer");
    Sql idSql = new Sql();
    idSql.addName("id");
    idSql.setType("integer");
    idFM.setSql(idSql);
    // Add field mappings
    choice.addFieldMapping(idFM);
    return idFieldDescr;
}
Example 31
Project: eGov-master  File: DepositCodeService.java View source code
/*
     * (non-Javadoc)
     * @see org.egov.commons.service.EntityTypeService#filterActiveEntities(java. lang.String, int, java.lang.Integer)
     */
@Override
public List<DepositCode> filterActiveEntities(final String filterKey, final int maxRecords, final Integer accountDetailTypeId) {
    final Integer pageSize = maxRecords > 0 ? maxRecords : null;
    final String param = "%" + filterKey.toUpperCase() + "%";
    final Page page = findPageByNamedQuery(WorksConstants.QUERY_GETACTIVEDEPOSITCODES_BY_CODE_OR_DESC, 1, pageSize, param, param);
    return page.getList();
}
Example 32
Project: android_platform_libcore-master  File: ClassCastExceptionTest.java View source code
public void testCastOperatorWithArrays() throws Exception {
    try {
        Object o = (E) makeArray(String.class);
        fail();
    } catch (ClassCastException ex) {
        assertEquals("java.lang.String[] cannot be cast to " + "libcore.java.lang.ClassCastExceptionTest$E", ex.getMessage());
    }
    try {
        Object o = (E) makeArray(float.class);
        fail();
    } catch (ClassCastException ex) {
        assertEquals("float[] cannot be cast to libcore.java.lang.ClassCastExceptionTest$E", ex.getMessage());
    }
    try {
        Object o = (E) makeArray(char[].class);
        fail();
    } catch (ClassCastException ex) {
        assertEquals("char[][] cannot be cast to libcore.java.lang.ClassCastExceptionTest$E", ex.getMessage());
    }
    try {
        Object o = (Object[][][]) makeInteger();
        fail();
    } catch (ClassCastException ex) {
        assertEquals("java.lang.Integer cannot be cast to java.lang.Object[][][]", ex.getMessage());
    }
}
Example 33
Project: parkandrideAPI-master  File: Time.java View source code
public static int parseTime(String time) {
    if (isNullOrEmpty(time)) {
        throw new IllegalArgumentException("time should not be null or empty");
    }
    Matcher m = PATTERN.matcher(time);
    if (m.matches()) {
        int hour = Integer.parseInt(m.group(1));
        int minute = 0;
        String optionalMinute = m.group(2);
        if (optionalMinute != null) {
            minute = Integer.parseInt(optionalMinute);
        }
        if (hour > 24) {
            throw new IllegalArgumentException("hour should be <= 24");
        }
        if (minute > 59) {
            throw new IllegalArgumentException("minute should be <= 59");
        }
        return 60 * hour + minute;
    } else {
        throw new IllegalArgumentException("expected time in 24-h format, e.g.  9, 09, 24, 9:59, 23:01");
    }
}
Example 34
Project: rascal-master  File: IUPTRAstToSymbolConstructor.java View source code
@Override
public IConstructor visitExpressionCallOrTree(CallOrTree x) {
    Expression namePart = x.getExpression();
    if (!namePart.isQualifiedName()) {
        throw new ImplementationError("weird AST");
    }
    String name = ((org.rascalmpl.semantics.dynamic.QualifiedName.Default) namePart.getQualifiedName()).lastName();
    if (name.equals("lit")) {
        StringConstant.Lexical arg = (org.rascalmpl.ast.StringConstant.Lexical) x.getArguments().get(0).getLiteral().getStringLiteral().getConstant();
        // TODO: escaping etc.
        String str = arg.getString();
        str = str.substring(1, str.length() - 1);
        return vf.constructor(RascalValueFactory.Symbol_Lit, vf.string(str));
    }
    if (name.equals("cilit")) {
        StringConstant.Lexical arg = (org.rascalmpl.ast.StringConstant.Lexical) x.getArguments().get(0).getLiteral().getStringLiteral().getConstant();
        // TODO: escaping etc.
        String str = arg.getString();
        str = str.substring(1, str.length() - 1);
        return vf.constructor(RascalValueFactory.Symbol_CiLit, vf.string(str));
    }
    if (name.equals("empty")) {
        return vf.constructor(RascalValueFactory.Symbol_Empty);
    }
    if (name.equals("seq")) {
        IList list = vf.list(RascalValueFactory.Symbol);
        Expression.List arg = (List) x.getArguments().get(0);
        for (Expression y : arg.getElements()) {
            list = list.append(y.accept(this));
        }
        return vf.constructor(RascalValueFactory.Symbol_Seq, list);
    }
    if (name.equals("opt")) {
        IConstructor arg = x.getArguments().get(0).accept(this);
        return vf.constructor(RascalValueFactory.Symbol_Opt, arg);
    }
    if (name.equals("alt")) {
        ISet set = vf.set(RascalValueFactory.Symbol);
        Expression.Set arg = (Set) x.getArguments().get(0);
        for (Expression y : arg.getElements()) {
            set = set.insert(y.accept(this));
        }
        return vf.constructor(RascalValueFactory.Symbol_Alt, set);
    }
    if (name.equals("tuple")) {
        java.util.List<Expression> args = x.getArguments();
        IConstructor head = args.get(0).accept(this);
        IList rest = vf.list(RascalValueFactory.Symbol);
        for (Expression arg : ((Expression.List) args.get(1)).getElements()) {
            rest = rest.append(arg.accept(this));
        }
        return vf.constructor(RascalValueFactory.Symbol_Tuple, head, rest);
    }
    if (name.equals("sort")) {
        StringConstant.Lexical arg = (org.rascalmpl.ast.StringConstant.Lexical) x.getArguments().get(0).getLiteral().getStringLiteral().getConstant();
        String str = arg.getString();
        str = str.substring(1, str.length() - 1);
        return vf.constructor(RascalValueFactory.Symbol_Sort, vf.string(str));
    }
    if (name.equals("layouts")) {
        StringConstant.Lexical arg = (org.rascalmpl.ast.StringConstant.Lexical) x.getArguments().get(0).getLiteral().getStringLiteral().getConstant();
        String str = arg.getString();
        str = str.substring(1, str.length() - 1);
        return vf.constructor(RascalValueFactory.Symbol_LayoutX, vf.string(str));
    }
    if (name.equals("iter")) {
        IConstructor arg = x.getArguments().get(0).accept(this);
        return vf.constructor(RascalValueFactory.Symbol_IterPlus, arg);
    }
    if (name.equals("iter-star")) {
        IConstructor arg = x.getArguments().get(0).accept(this);
        return vf.constructor(RascalValueFactory.Symbol_IterStar, arg);
    }
    if (name.equals("iter-star-seps")) {
        IConstructor arg = x.getArguments().get(0).accept(this);
        Expression.List args = (Expression.List) x.getArguments().get(1);
        IList seps = vf.list(RascalValueFactory.Args);
        for (Expression elem : args.getElements()) {
            seps = seps.append(elem.accept(this));
        }
        return vf.constructor(RascalValueFactory.Symbol_IterStarSepX, arg, seps);
    }
    if (name.equals("iter-seps")) {
        IConstructor arg = x.getArguments().get(0).accept(this);
        Expression.List args = (Expression.List) x.getArguments().get(1);
        IList seps = vf.list(RascalValueFactory.Args);
        for (Expression elem : args.getElements()) {
            seps = seps.append(elem.accept(this));
        }
        return vf.constructor(RascalValueFactory.Symbol_IterSepX, arg, seps);
    }
    if (name.equals("parameterized-sort")) {
        java.util.List<Expression> args = x.getArguments();
        StringConstant.Lexical sort = (org.rascalmpl.ast.StringConstant.Lexical) x.getArguments().get(0).getLiteral().getStringLiteral().getConstant();
        IList rest = vf.list(RascalValueFactory.Symbol);
        for (Expression arg : ((Expression.List) args.get(1)).getElements()) {
            rest = rest.append(arg.accept(this));
        }
        return vf.constructor(RascalValueFactory.Symbol_ParameterizedSort, vf.string(sort.getString()), rest);
    }
    if (name.equals("lit")) {
        StringConstant.Lexical arg = (org.rascalmpl.ast.StringConstant.Lexical) x.getArguments().get(0).getLiteral().getStringLiteral().getConstant();
        // TODO: escaping etc.
        return vf.constructor(RascalValueFactory.Symbol_Lit, vf.string(arg.getString()));
    }
    if (name.equals("char-class")) {
        java.util.List<Expression> args = x.getArguments();
        IList ranges = vf.list(RascalValueFactory.CharRange);
        for (Expression arg : ((Expression.List) args.get(0)).getElements()) {
            ranges = ranges.append(arg.accept(this));
        }
        return vf.constructor(RascalValueFactory.Symbol_CharClass, ranges);
    }
    if (name.equals("single")) {
        org.rascalmpl.ast.DecimalIntegerLiteral.Lexical arg1 = (org.rascalmpl.ast.DecimalIntegerLiteral.Lexical) x.getArguments().get(0).getLiteral().getIntegerLiteral().getDecimal();
        IInteger num = vf.integer(java.lang.Integer.parseInt(arg1.getString()));
        return vf.constructor(RascalValueFactory.CharRange_Single, num);
    }
    if (name.equals("range")) {
        org.rascalmpl.ast.DecimalIntegerLiteral.Lexical arg1 = (org.rascalmpl.ast.DecimalIntegerLiteral.Lexical) x.getArguments().get(0).getLiteral().getIntegerLiteral().getDecimal();
        IInteger num1 = vf.integer(java.lang.Integer.parseInt(arg1.getString()));
        org.rascalmpl.ast.DecimalIntegerLiteral.Lexical arg2 = (org.rascalmpl.ast.DecimalIntegerLiteral.Lexical) x.getArguments().get(1).getLiteral().getIntegerLiteral().getDecimal();
        IInteger num2 = vf.integer(java.lang.Integer.parseInt(arg2.getString()));
        return vf.constructor(RascalValueFactory.CharRange_Range, num1, num2);
    }
    throw new ImplementationError("Non-IUPTR AST expression: " + name + ", " + x);
}
Example 35
Project: hadoop-20-master  File: MetricsDynamicMBeanBase.java View source code
private void createMBeanInfo() {
    metricsRateAttributeMod = new ConcurrentHashMap<String, MetricsBase>();
    boolean needsMinMaxResetOperation = false;
    List<MBeanAttributeInfo> attributesInfo = new ArrayList<MBeanAttributeInfo>();
    MBeanOperationInfo[] operationsInfo = null;
    numEntriesInRegistry = metricsRegistry.size();
    for (MetricsBase o : metricsRegistry.getMetricsList()) {
        if (MetricsTimeVaryingRate.class.isInstance(o)) {
            // For each of the metrics there are 3 different attributes
            attributesInfo.add(new MBeanAttributeInfo(o.getName() + NUM_OPS, "java.lang.Integer", o.getDescription(), true, false, false));
            attributesInfo.add(new MBeanAttributeInfo(o.getName() + NUM_OPS_CURRENT, "java.lang.Integer", o.getDescription(), true, false, false));
            attributesInfo.add(new MBeanAttributeInfo(o.getName() + AVG_TIME, "java.lang.Long", o.getDescription(), true, false, false));
            attributesInfo.add(new MBeanAttributeInfo(o.getName() + MIN_TIME, "java.lang.Long", o.getDescription(), true, false, false));
            attributesInfo.add(new MBeanAttributeInfo(o.getName() + MAX_TIME, "java.lang.Long", o.getDescription(), true, false, false));
            // the min and max can be reset.
            needsMinMaxResetOperation = true;
            // Note the special attributes (AVG_TIME, MIN_TIME, ..) are derived from metrics 
            // Rather than check for the suffix we store them in a map.
            metricsRateAttributeMod.put(o.getName() + NUM_OPS, o);
            metricsRateAttributeMod.put(o.getName() + NUM_OPS_CURRENT, o);
            metricsRateAttributeMod.put(o.getName() + AVG_TIME, o);
            metricsRateAttributeMod.put(o.getName() + MIN_TIME, o);
            metricsRateAttributeMod.put(o.getName() + MAX_TIME, o);
        } else if (MetricsIntValue.class.isInstance(o) || MetricsTimeVaryingInt.class.isInstance(o)) {
            attributesInfo.add(new MBeanAttributeInfo(o.getName(), "java.lang.Integer", o.getDescription(), true, false, false));
        } else if (MetricsLongValue.class.isInstance(o) || MetricsTimeVaryingLong.class.isInstance(o)) {
            attributesInfo.add(new MBeanAttributeInfo(o.getName(), "java.lang.Long", o.getDescription(), true, false, false));
        } else {
            MetricsUtil.LOG.error("unknown metrics type: " + o.getClass().getName());
        }
        if (needsMinMaxResetOperation) {
            operationsInfo = new MBeanOperationInfo[] { new MBeanOperationInfo(RESET_ALL_MIN_MAX_OP, "Reset (zero) All Min Max", null, "void", MBeanOperationInfo.ACTION) };
        }
    }
    MBeanAttributeInfo[] attrArray = new MBeanAttributeInfo[attributesInfo.size()];
    mbeanInfo = new MBeanInfo(this.getClass().getName(), mbeanDescription, attributesInfo.toArray(attrArray), null, operationsInfo, null);
}
Example 36
Project: cloudtm-data-platform-master  File: DomainModel.java View source code
protected void initializeBuiltinValueTypes() {
    for (String[] valueType : builtinValueTypes) {
        newValueType(valueType[1], valueType[0]);
    }
// // primitive types
// newValueType("boolean", "boolean");
// newValueType("byte", "byte");
// newValueType("char", "char");
// newValueType("short", "short");
// newValueType("int", "int");
// newValueType("float", "float");
// newValueType("long", "long");
// newValueType("double", "double");
// // their wrappers
// newValueType("Boolean", "java.lang.Boolean");
// newValueType("Byte", "java.lang.Byte");
// newValueType("Character", "java.lang.Character");
// newValueType("Short", "java.lang.Short");
// newValueType("Integer", "java.lang.Integer");
// newValueType("Float", "java.lang.Float");
// newValueType("Long", "java.lang.Long");
// newValueType("Double", "java.lang.Double");
// // String is, of course, essential
// newValueType("String", "java.lang.String");
// // we need something binary, also
// newValueType("bytearray", "byte[]");
// // JodaTime types
// newValueType("DateTime", "org.joda.time.DateTime");
// newValueType("LocalDate", "org.joda.time.LocalDate");
// newValueType("LocalTime", "org.joda.time.LocalTime");
// newValueType("Partial", "org.joda.time.Partial");
// // also anything Serializable is acceptable
// newValueType("Serializable", "java.io.Serializable");
}
Example 37
Project: flare-spork-master  File: TestInvokerGenerator.java View source code
@Test
public void testValueOf() throws Exception {
    Data data = resetData(pigServer);
    Set<Tuple> inputs = Sets.newHashSet();
    while (inputs.size() < 1000) {
        inputs.add(tuple(Integer.toString(r.nextInt())));
    }
    Set<Tuple> expected = Sets.newHashSet();
    for (Tuple t : inputs) {
        String str = (String) t.get(0);
        expected.add(tuple(Integer.valueOf(str)));
    }
    data.set("foo", Utils.getSchemaFromString("x:chararray"), inputs);
    pigServer.registerQuery("define valueOf InvokerGenerator('java.lang.Integer','valueOf','String');");
    pigServer.registerQuery("a = load 'foo' using mock.Storage();");
    pigServer.registerQuery("b = foreach @ generate valueOf($0);");
    pigServer.registerQuery("store b into 'bar' using mock.Storage();");
    List<Tuple> results = data.get("bar");
    assertEquals(expected.size(), results.size());
    for (Tuple t : results) {
        assertTrue(expected.remove(t));
    }
    assertEquals(0, expected.size());
}
Example 38
Project: revapi-master  File: MethodChecksTest.java View source code
@Test
public void testOverloadsResolution() throws Exception {
    List<Report> reports = new ArrayList<>();
    SimpleReporter reporter = new SimpleReporter() {

        @Override
        public void report(@Nonnull Report report) {
            reports.add(report);
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("Reports");
            sb.append(reports);
            return sb.toString();
        }
    };
    runAnalysis(reporter, "v1/methods/Overloads.java", "v2/methods/Overloads.java");
    Assert.assertEquals(7, reports.size());
    Assert.assertTrue(reports.stream().anyMatch(reportCheck("method int Overloads::a(int)", "method double Overloads::a(int)", Code.METHOD_RETURN_TYPE_CHANGED)));
    Assert.assertTrue(reports.stream().anyMatch(reportCheck("method void Overloads::a()", "method double Overloads::a()", Code.METHOD_RETURN_TYPE_CHANGED)));
    Assert.assertTrue(reports.stream().anyMatch(reportCheck("method void Overloads::a(int, long)", "method void Overloads::a(int, long, float)", Code.METHOD_NUMBER_OF_PARAMETERS_CHANGED)));
    Assert.assertTrue(reports.stream().anyMatch(reportCheck("method void Overloads::a(int, long, double, float)", "method void Overloads::a(long, int)", Code.METHOD_NUMBER_OF_PARAMETERS_CHANGED)));
    Assert.assertTrue(reports.stream().anyMatch(reportCheck("method parameter void Overloads::b(===java.lang.Class<? extends java.lang.Integer>===, java.lang.Object)", "method parameter void Overloads::b(===java.lang.Class<?>===, java.lang.Object)", Code.METHOD_PARAMETER_TYPE_PARAMETER_CHANGED)));
    Assert.assertTrue(reports.stream().anyMatch(reportCheck("method parameter void Overloads::c(java.lang.Class<java.lang.Long>, ===java.lang.Class<? extends java.lang.Integer>===, float)", "method parameter void Overloads::c(java.lang.Class<java.lang.Long>, ===int===, float)", Code.METHOD_PARAMETER_TYPE_CHANGED)));
    Assert.assertTrue(reports.stream().anyMatch(reportCheck("method parameter void Overloads::c(java.lang.Class<? extends java.lang.Integer>, ===java.lang.Class<java.lang.Long>===, int)", "method parameter void Overloads::c(java.lang.Class<? extends java.lang.Integer>, ===java.lang.Class<?>===, int)", Code.METHOD_PARAMETER_TYPE_PARAMETER_CHANGED)));
}
Example 39
Project: property-db-master  File: ObjectFormat.java View source code
private static Class getBoxedClass(Class type) {
    // Check if type is primitive
    if (type.isPrimitive()) {
        // Yes -> box it
        if (type == boolean.class) {
            return java.lang.Boolean.class;
        } else if (type == byte.class) {
            return java.lang.Byte.class;
        } else if (type == char.class) {
            return java.lang.Character.class;
        } else if (type == short.class) {
            return java.lang.Short.class;
        } else if (type == int.class) {
            return java.lang.Integer.class;
        } else if (type == long.class) {
            return java.lang.Long.class;
        } else if (type == float.class) {
            return java.lang.Float.class;
        } else if (type == double.class) {
            return java.lang.Double.class;
        } else {
            throw new IllegalArgumentException("Unknown primitive type: " + type.getSimpleName() + "!");
        }
    } else {
        // No -> return it
        return type;
    }
}
Example 40
Project: h2-bitmap-master  File: TestUtils.java View source code
private void testGetNonPrimitiveClass() throws Exception {
    testGetNonPrimitiveClass(BigInteger.class, BigInteger.class);
    testGetNonPrimitiveClass(Boolean.class, boolean.class);
    testGetNonPrimitiveClass(Byte.class, byte.class);
    testGetNonPrimitiveClass(Character.class, char.class);
    testGetNonPrimitiveClass(Byte.class, byte.class);
    testGetNonPrimitiveClass(Double.class, double.class);
    testGetNonPrimitiveClass(Float.class, float.class);
    testGetNonPrimitiveClass(Integer.class, int.class);
    testGetNonPrimitiveClass(Long.class, long.class);
    testGetNonPrimitiveClass(Short.class, short.class);
    testGetNonPrimitiveClass(Void.class, void.class);
}
Example 41
Project: spring-android-master  File: GenericTypeResolverTests.java View source code
public void testMethodReturnTypes() {
    assertEquals(Integer.class, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "integer"), MyInterfaceType.class));
    assertEquals(String.class, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "string"), MyInterfaceType.class));
    assertEquals(null, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "raw"), MyInterfaceType.class));
    assertEquals(null, resolveReturnTypeArgument(findMethod(MyTypeWithMethods.class, "object"), MyInterfaceType.class));
}
Example 42
Project: seasar2-master  File: AbstGeneratorTest.java View source code
/**
     * @throws Exception
     */
public void testToObject() throws Exception {
    assertEquals("1", "new java.lang.Boolean(var)", AbstractGenerator.toObject(boolean.class, "var"));
    assertEquals("1", "new java.lang.Character(var)", AbstractGenerator.toObject(char.class, "var"));
    assertEquals("1", "new java.lang.Byte(var)", AbstractGenerator.toObject(byte.class, "var"));
    assertEquals("1", "new java.lang.Short(var)", AbstractGenerator.toObject(short.class, "var"));
    assertEquals("1", "new java.lang.Integer(var)", AbstractGenerator.toObject(int.class, "var"));
    assertEquals("1", "new java.lang.Long(var)", AbstractGenerator.toObject(long.class, "var"));
    assertEquals("1", "new java.lang.Float(var)", AbstractGenerator.toObject(float.class, "var"));
    assertEquals("1", "new java.lang.Double(var)", AbstractGenerator.toObject(double.class, "var"));
    assertEquals("2", "var", AbstractGenerator.toObject(int[].class, "var"));
    assertEquals("3", "var", AbstractGenerator.toObject(Object.class, "var"));
    assertEquals("4", "var", AbstractGenerator.toObject(Object[].class, "var"));
    assertEquals("5", "var", AbstractGenerator.toObject(String.class, "var"));
    assertEquals("6", "var", AbstractGenerator.toObject(String[].class, "var"));
}
Example 43
Project: Payara-master  File: EnvEntry.java View source code
/**
         * Validates the specified value string against the indicated type.  The
         * recognized types are (from the spec):
         * <ul>
         * <li>java.lang.Boolean
         * <li>java.lang.Byte
         * <li>java.lang.Character
         * <li>java.lang.Double
         * <li>java.lang.Float
         * <li>java.lang.Integer
         * <li>java.lang.Long
         * <li>java.lang.Short
         * <li>java.lang.String
         * </ul>
         *
         * @param type valid type for env-entry-type (from the spec)
         * @param value value to be checked
         * @throws IllegalArgumentException if the type does not match one of the legal ones
         * @throws NumberFormatException if the value cannot be parsed according to the type
         */
public static void validateValue(final String type, final String value) {
    if (type == null) {
        throw new IllegalArgumentException("type");
    }
    if (value == null) {
        throw new IllegalArgumentException("value");
    }
    if (type.equals("java.lang.Boolean")) {
        Boolean.parseBoolean(value);
    } else if (type.equals("java.lang.Byte")) {
        Byte.parseByte(value);
    } else if (type.equals("java.lang.Character")) {
        if (value.length() > 1) {
            throw new IllegalArgumentException("length(\"" + value + "\") > 1");
        }
    } else if (type.equals("java.lang.Double")) {
        Double.parseDouble(value);
    } else if (type.equals("java.lang.Float")) {
        Float.parseFloat(value);
    } else if (type.equals("java.lang.Integer")) {
        Integer.parseInt(value);
    } else if (type.equals("java.lang.Long")) {
        Long.parseLong(value);
    } else if (type.equals("java.lang.Short")) {
        Short.parseShort(value);
    } else if (type.equals("java.lang.String")) {
    // no-op
    } else {
        throw new IllegalArgumentException(type);
    }
}
Example 44
Project: adc-wildner-master  File: SparseTriangularMatrix.java View source code
/* (non-Javadoc)
	 * @see ca.pfv.spmf.datastructures.triangularmatrix.AbstractTriangularMatrix#incrementCount(int, int)
	 */
public void incrementCount(int i, int j) {
    if (i < j) {
        // First get the map of i
        Map<Integer, Integer> mapCount = matrix.get(i);
        if (mapCount == null) {
            mapCount = new HashMap<Integer, Integer>();
            matrix.put(i, mapCount);
            mapCount.put(j, 1);
        } else {
            // Second, get the count of i,j
            Integer count = mapCount.get(j);
            if (count == null) {
                mapCount.put(j, 1);
            } else {
                mapCount.put(j, ++count);
            }
        }
    } else {
        // First get the map of j
        Map<Integer, Integer> mapCount = matrix.get(j);
        if (mapCount == null) {
            mapCount = new HashMap<Integer, Integer>();
            matrix.put(j, mapCount);
            mapCount.put(i, 1);
        } else {
            // Second, get the count of i,j
            Integer count = mapCount.get(i);
            if (count == null) {
                mapCount.put(i, 1);
            } else {
                mapCount.put(i, ++count);
            }
        }
    }
}
Example 45
Project: Katari-master  File: ParameterDefinition.java View source code
/** Converts the given String value to the correct type.
   *
   * The valid accepted types are: String, Integer, Long, Float, Double,
   * Boolean and date.
   *
   * @param value the String value to be converted. It cannot be null.
   *
   * @return the value converted to the correct type. If it cannot convert the
   * value it returns null. If the type to be converted to is a Date and there
   * is an error while converting the value, it throws a RuntimeException.
   *
   * @throws ParseException in case a parameter could not be parsed according
   * to the expected type.
   *
   * TODO This method hardcodes the format to mm/MM/yyyy. Provide a way to
   * configure this.
   */
public Object convertValue(final String value) throws ParseException {
    Validate.notNull(value, "The value cannot be null.");
    Class<?> classType;
    Object result = null;
    try {
        classType = Class.forName(type);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Error obtaining class", e);
    }
    if (String.class.equals(classType)) {
        result = value;
    } else if (Integer.class.equals(classType)) {
        result = Integer.valueOf(value);
    } else if (Long.class.equals(classType)) {
        result = Long.valueOf(value);
    } else if (Float.class.equals(classType)) {
        result = Float.valueOf(value);
    } else if (Double.class.equals(classType)) {
        result = Double.valueOf(value);
    } else if (Boolean.class.equals(classType)) {
        result = Boolean.valueOf(value);
    } else if (Date.class.equals(classType)) {
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        df.setLenient(false);
        result = df.parse(value);
    } else if (Time.class.equals(classType)) {
        DateFormat df = new SimpleDateFormat("HH:mm:ss");
        Date time = (Date) df.parseObject(value);
        result = new Time(time.getTime());
    } else {
        throw new RuntimeException("Type not supported: " + classType);
    }
    return result;
}
Example 46
Project: org.openntf.domino-master  File: FactoryHelper.java View source code
/**
     * Loads a class file by a given class loader.
     *
     * @param domain        if it is null, a default domain is used.
     * @since 3.3
     */
public static Class toClass(ClassFile cf, ClassLoader loader, ProtectionDomain domain) throws CannotCompileException {
    try {
        byte[] b = toBytecode(cf);
        Method method;
        Object[] args;
        if (domain == null) {
            method = defineClass1;
            args = new Object[] { cf.getName(), b, new Integer(0), new Integer(b.length) };
        } else {
            method = defineClass2;
            args = new Object[] { cf.getName(), b, new Integer(0), new Integer(b.length), domain };
        }
        return toClass2(method, loader, args);
    } catch (RuntimeException e) {
        throw e;
    } catch (java.lang.reflect.InvocationTargetException e) {
        throw new CannotCompileException(e.getTargetException());
    } catch (Exception e) {
        throw new CannotCompileException(e);
    }
}
Example 47
Project: yarn-comment-master  File: TestConfiguration.java View source code
public void testGetRangeIterator() throws Exception {
    Configuration config = new Configuration(false);
    IntegerRanges ranges = config.getRange("Test", "");
    assertFalse("Empty range has values", ranges.iterator().hasNext());
    ranges = config.getRange("Test", "5");
    Set<Integer> expected = new HashSet<Integer>(Arrays.asList(5));
    Set<Integer> found = new HashSet<Integer>();
    for (Integer i : ranges) {
        found.add(i);
    }
    assertEquals(expected, found);
    ranges = config.getRange("Test", "5-10,13-14");
    expected = new HashSet<Integer>(Arrays.asList(5, 6, 7, 8, 9, 10, 13, 14));
    found = new HashSet<Integer>();
    for (Integer i : ranges) {
        found.add(i);
    }
    assertEquals(expected, found);
    ranges = config.getRange("Test", "8-12, 5- 7");
    expected = new HashSet<Integer>(Arrays.asList(5, 6, 7, 8, 9, 10, 11, 12));
    found = new HashSet<Integer>();
    for (Integer i : ranges) {
        found.add(i);
    }
    assertEquals(expected, found);
}
Example 48
Project: ikvm-openjdk-master  File: RMIConnectionImpl_Stub.java View source code
// implementation of addNotificationListeners(ObjectName[], MarshalledObject[], Subject[])
public java.lang.Integer[] addNotificationListeners(javax.management.ObjectName[] $param_arrayOf_ObjectName_1, java.rmi.MarshalledObject[] $param_arrayOf_MarshalledObject_2, javax.security.auth.Subject[] $param_arrayOf_Subject_3) throws java.io.IOException, javax.management.InstanceNotFoundException {
    try {
        Object $result = ref.invoke(this, $method_addNotificationListeners_1, new java.lang.Object[] { $param_arrayOf_ObjectName_1, $param_arrayOf_MarshalledObject_2, $param_arrayOf_Subject_3 }, -5321691879380783377L);
        return ((java.lang.Integer[]) $result);
    } catch (java.lang.RuntimeException e) {
        throw e;
    } catch (java.io.IOException e) {
        throw e;
    } catch (javax.management.InstanceNotFoundException e) {
        throw e;
    } catch (java.lang.Exception e) {
        throw new java.rmi.UnexpectedException("undeclared checked exception", e);
    }
}
Example 49
Project: jdk7u-jdk-master  File: Callback_Stub.java View source code
// methods from remote interfaces
// implementation of getNumDeactivated()
public int getNumDeactivated() throws java.rmi.RemoteException {
    try {
        if (useNewInvoke) {
            Object $result = ref.invoke(this, $method_getNumDeactivated_0, null, -761062487639949912L);
            return ((java.lang.Integer) $result).intValue();
        } else {
            java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash);
            ref.invoke(call);
            int $result;
            try {
                java.io.ObjectInput in = call.getInputStream();
                $result = in.readInt();
            } catch (java.io.IOException e) {
                throw new java.rmi.UnmarshalException("error unmarshalling return", e);
            } finally {
                ref.done(call);
            }
            return $result;
        }
    } catch (java.lang.RuntimeException e) {
        throw e;
    } catch (java.rmi.RemoteException e) {
        throw e;
    } catch (java.lang.Exception e) {
        throw new java.rmi.UnexpectedException("undeclared checked exception", e);
    }
}
Example 50
Project: jgit-master  File: GcConcurrentTest.java View source code
@Test
public void concurrentRepack() throws Exception {
    final CyclicBarrier syncPoint = new CyclicBarrier(2);
    class DoRepack extends EmptyProgressMonitor implements Callable<Integer> {

        public void beginTask(String title, int totalWork) {
            if (title.equals(JGitText.get().writingObjects)) {
                try {
                    syncPoint.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (BrokenBarrierException ignored) {
                }
            }
        }

        /** @return 0 for success, 1 in case of error when writing pack */
        public Integer call() throws Exception {
            try {
                gc.setProgressMonitor(this);
                gc.repack();
                return valueOf(0);
            } catch (IOException e) {
                Thread.currentThread().interrupt();
                try {
                    syncPoint.await();
                } catch (InterruptedException ignored) {
                }
                return valueOf(1);
            }
        }
    }
    RevBlob a = tr.blob("a");
    tr.lightweightTag("t", a);
    ExecutorService pool = Executors.newFixedThreadPool(2);
    try {
        DoRepack repack1 = new DoRepack();
        DoRepack repack2 = new DoRepack();
        Future<Integer> result1 = pool.submit(repack1);
        Future<Integer> result2 = pool.submit(repack2);
        assertEquals(0, result1.get().intValue() + result2.get().intValue());
    } finally {
        pool.shutdown();
        pool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
    }
}
Example 51
Project: Eclipse-Postfix-Code-Completion-master  File: StringFormatGenerator.java View source code
@Override
protected Expression createMemberAccessExpression(Object member, boolean ignoreArraysCollections, boolean ignoreNulls) {
    ITypeBinding type = getMemberType(member);
    if (!getContext().is50orHigher() && type.isPrimitive()) {
        String nonPrimitiveType = null;
        String typeName = type.getName();
        //$NON-NLS-1$ //$NON-NLS-2$
        if (typeName.equals("byte"))
            nonPrimitiveType = "java.lang.Byte";
        //$NON-NLS-1$ //$NON-NLS-2$
        if (typeName.equals("short"))
            nonPrimitiveType = "java.lang.Short";
        //$NON-NLS-1$ //$NON-NLS-2$
        if (typeName.equals("char"))
            nonPrimitiveType = "java.lang.Character";
        //$NON-NLS-1$ //$NON-NLS-2$
        if (typeName.equals("int"))
            nonPrimitiveType = "java.lang.Integer";
        //$NON-NLS-1$ //$NON-NLS-2$
        if (typeName.equals("long"))
            nonPrimitiveType = "java.lang.Long";
        //$NON-NLS-1$ //$NON-NLS-2$
        if (typeName.equals("float"))
            nonPrimitiveType = "java.lang.Float";
        //$NON-NLS-1$ //$NON-NLS-2$
        if (typeName.equals("double"))
            nonPrimitiveType = "java.lang.Double";
        //$NON-NLS-1$ //$NON-NLS-2$
        if (typeName.equals("boolean"))
            nonPrimitiveType = "java.lang.Boolean";
        ClassInstanceCreation classInstance = fAst.newClassInstanceCreation();
        classInstance.setType(fAst.newSimpleType(addImport(nonPrimitiveType)));
        classInstance.arguments().add(super.createMemberAccessExpression(member, true, true));
        return classInstance;
    }
    return super.createMemberAccessExpression(member, ignoreArraysCollections, ignoreNulls);
}