repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/templates/TemplateCompiler.java | package org.mvel2.templates;
public class TemplateCompiler {
public TemplateCompiler(String template) {}
public static CompiledTemplate compileTemplate(String template) { return null; }
public CompiledTemplate compile() { return null; }
} | 245 | 34.142857 | 82 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/templates/CompiledTemplate.java | package org.mvel2.templates;
public class CompiledTemplate {} | 62 | 20 | 32 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/templates/TemplateRuntime.java | package org.mvel2.templates;
import java.util.Map;
public class TemplateRuntime {
public static Object eval(String template, Map vars) { return null; }
public static Object execute(CompiledTemplate compiled, Map vars) { return null; }
} | 242 | 29.375 | 84 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/integration/VariableResolverFactory.java | package org.mvel2.integration;
import java.io.Serializable;
public interface VariableResolverFactory extends Serializable {} | 126 | 24.4 | 64 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/integration/impl/ImmutableDefaultFactory.java | package org.mvel2.integration.impl;
import org.mvel2.integration.VariableResolverFactory;
public class ImmutableDefaultFactory implements VariableResolverFactory {} | 166 | 32.4 | 74 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/compiler/Accessor.java | package org.mvel2.compiler;
import org.mvel2.integration.VariableResolverFactory;
public interface Accessor {
public Object getValue(Object ctx, Object elCtx, VariableResolverFactory factory);
} | 198 | 27.428571 | 84 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/compiler/ExecutableStatement.java | package org.mvel2.compiler;
import java.io.Serializable;
import org.mvel2.integration.VariableResolverFactory;
public interface ExecutableStatement extends Accessor, Serializable {
public Object getValue(Object staticContext, VariableResolverFactory factory);
} | 265 | 32.25 | 80 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/compiler/CompiledExpression.java | package org.mvel2.compiler;
import org.mvel2.integration.VariableResolverFactory;
public class CompiledExpression implements ExecutableStatement {
public Object getDirectValue(Object staticContext, VariableResolverFactory factory) { return null; }
public Object getValue(Object staticContext, VariableResolverFactory factory) { return null; }
public Object getValue(Object ctx, Object elCtx, VariableResolverFactory factory) { return null; }
} | 451 | 49.222222 | 102 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/compiler/ExpressionCompiler.java | package org.mvel2.compiler;
public class ExpressionCompiler {
public ExpressionCompiler(String expression) {}
public CompiledExpression compile() { return null; }
} | 169 | 27.333333 | 54 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/compiler/CompiledAccExpression.java | package org.mvel2.compiler;
import org.mvel2.ParserContext;
import org.mvel2.integration.VariableResolverFactory;
public class CompiledAccExpression implements ExecutableStatement {
public CompiledAccExpression(char[] expression, Class ingressType, ParserContext context) {}
public Object getValue(Object staticContext, VariableResolverFactory factory) { return null; }
public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) { return null; }
}
| 487 | 43.363636 | 108 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/jsr223/MvelScriptEngine.java | package org.mvel2.jsr223;
import java.io.Serializable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptException;
public class MvelScriptEngine {
public CompiledScript compile(String script) throws ScriptException { return null; }
public Serializable compiledScript(String script) throws ScriptException { return null; }
public Object evaluate(Serializable expression, ScriptContext context) throws ScriptException { return null; }
} | 490 | 39.916667 | 112 | java |
codeql | codeql-master/java/ql/test/stubs/mvel2-2.4.7/org/mvel2/jsr223/MvelCompiledScript.java | package org.mvel2.jsr223;
import java.io.Serializable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptException;
public class MvelCompiledScript extends CompiledScript {
public MvelCompiledScript(MvelScriptEngine engine, Serializable compiledScript) {}
public Object eval(ScriptContext context) throws ScriptException { return null; }
} | 392 | 34.727273 | 84 | java |
codeql | codeql-master/java/ql/test/stubs/javamail-api-1.6.2/javax/mail/Authenticator.java | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2017 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://oss.oracle.com/licenses/CDDL+GPL-1.1
* or LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package javax.mail;
import java.net.InetAddress;
/**
* The class Authenticator represents an object that knows how to obtain
* authentication for a network connection. Usually, it will do this by
* prompting the user for information.
* <p>
* Applications use this class by creating a subclass, and registering an
* instance of that subclass with the session when it is created. When
* authentication is required, the system will invoke a method on the subclass
* (like getPasswordAuthentication). The subclass's method can query about the
* authentication being requested with a number of inherited methods
* (getRequestingXXX()), and form an appropriate message for the user.
* <p>
* All methods that request authentication have a default implementation that
* fails.
*
* @see java.net.Authenticator
* @see javax.mail.Session#getInstance(java.util.Properties,
* javax.mail.Authenticator)
* @see javax.mail.Session#getDefaultInstance(java.util.Properties,
* javax.mail.Authenticator)
* @see javax.mail.Session#requestPasswordAuthentication
* @see javax.mail.PasswordAuthentication
*
* @author Bill Foote
* @author Bill Shannon
*/
// There are no abstract methods, but to be useful the user must
// subclass.
public abstract class Authenticator {
/**
* Ask the authenticator for a password.
* <p>
*
* @param addr The InetAddress of the site requesting authorization, or null
* if not known.
* @param port the port for the requested connection
* @param protocol The protocol that's requesting the connection (@see
* java.net.Authenticator.getProtocol())
* @param prompt A prompt string for the user
*
* @return The username/password, or null if one can't be gotten.
*/
final synchronized PasswordAuthentication requestPasswordAuthentication(InetAddress addr, int port, String protocol,
String prompt, String defaultUserName) {
return null;
}
/**
* @return the InetAddress of the site requesting authorization, or null if it's
* not available.
*/
protected final InetAddress getRequestingSite() {
return null;
}
/**
* @return the port for the requested connection
*/
protected final int getRequestingPort() {
return -1;
}
/**
* Give the protocol that's requesting the connection. Often this will be based
* on a URLName.
*
* @return the protcol
*
* @see javax.mail.URLName#getProtocol
*/
protected final String getRequestingProtocol() {
return null;
}
/**
* @return the prompt string given by the requestor
*/
protected final String getRequestingPrompt() {
return null;
}
/**
* @return the default user name given by the requestor
*/
protected final String getDefaultUserName() {
return null;
}
/**
* Called when password authentication is needed. Subclasses should override the
* default implementation, which returns null.
* <p>
*
* Note that if this method uses a dialog to prompt the user for this
* information, the dialog needs to block until the user supplies the
* information. This method can not simply return after showing the dialog.
*
* @return The PasswordAuthentication collected from the user, or null if none
* is provided.
*/
protected PasswordAuthentication getPasswordAuthentication() {
return null;
}
}
| 5,517 | 35.543046 | 120 | java |
codeql | codeql-master/java/ql/test/stubs/javamail-api-1.6.2/javax/mail/PasswordAuthentication.java | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2017 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://oss.oracle.com/licenses/CDDL+GPL-1.1
* or LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package javax.mail;
/**
* The class PasswordAuthentication is a data holder that is used by
* Authenticator. It is simply a repository for a user name and a password.
*
* @see java.net.PasswordAuthentication
* @see javax.mail.Authenticator
* @see javax.mail.Authenticator#getPasswordAuthentication()
*
* @author Bill Foote
*/
public final class PasswordAuthentication {
/**
* Initialize a new PasswordAuthentication
*
* @param userName the user name
* @param password The user's password
*/
public PasswordAuthentication(String userName, String password) {
}
/**
* @return the user name
*/
public String getUserName() {
return null;
}
/**
* @return the password
*/
public String getPassword() {
return null;
}
}
| 2,768 | 34.5 | 78 | java |
codeql | codeql-master/java/ql/test/stubs/javamail-api-1.6.2/javax/mail/Session.java | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://oss.oracle.com/licenses/CDDL+GPL-1.1
* or LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package javax.mail;
import java.lang.reflect.*;
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.concurrent.Executor;
/**
* The Session class represents a mail session and is not subclassed. It
* collects together properties and defaults used by the mail API's. A single
* default session can be shared by multiple applications on the desktop.
* Unshared sessions can also be created.
* <p>
*
* The Session class provides access to the protocol providers that implement
* the <code>Store</code>, <code>Transport</code>, and related classes. The
* protocol providers are configured using the following files:
* <ul>
* <li><code>javamail.providers</code> and
* <code>javamail.default.providers</code></li>
* <li><code>javamail.address.map</code> and
* <code>javamail.default.address.map</code></li>
* </ul>
* <p>
* Each <code>javamail.</code><i>X</i> resource file is searched for using three
* methods in the following order:
* <ol>
* <li><code><i>java.home</i>/<i>conf</i>/javamail.</code><i>X</i></li>
* <li><code>META-INF/javamail.</code><i>X</i></li>
* <li><code>META-INF/javamail.default.</code><i>X</i></li>
* </ol>
* <p>
* (Where <i>java.home</i> is the value of the "java.home" System property and
* <i>conf</i> is the directory named "conf" if it exists, otherwise the
* directory named "lib"; the "conf" directory was introduced in JDK 1.9.)
* <p>
* The first method allows the user to include their own version of the resource
* file by placing it in the <i>conf</i> directory where the
* <code>java.home</code> property points. The second method allows an
* application that uses the JavaMail APIs to include their own resource files
* in their application's or jar file's <code>META-INF</code> directory. The
* <code>javamail.default.</code><i>X</i> default files are part of the JavaMail
* <code>mail.jar</code> file and should not be supplied by users.
* <p>
*
* File location depends upon how the <code>ClassLoader</code> method
* <code>getResource</code> is implemented. Usually, the
* <code>getResource</code> method searches through CLASSPATH until it finds the
* requested file and then stops.
* <p>
*
* The ordering of entries in the resource files matters. If multiple entries
* exist, the first entries take precedence over the later entries. For example,
* the first IMAP provider found will be set as the default IMAP implementation
* until explicitly changed by the application. The user- or system-supplied
* resource files augment, they do not override, the default files included with
* the JavaMail APIs. This means that all entries in all files loaded will be
* available.
* <p>
*
* <b><code>javamail.providers</code></b> and
* <b><code>javamail.default.providers</code></b>
* <p>
*
* These resource files specify the stores and transports that are available on
* the system, allowing an application to "discover" what store and transport
* implementations are available. The protocol implementations are listed one
* per line. The file format defines four attributes that describe a protocol
* implementation. Each attribute is an "="-separated name-value pair with the
* name in lowercase. Each name-value pair is semi-colon (";") separated. The
* following names are defined.
*
* <table border=1>
* <caption> Attribute Names in Providers Files </caption>
* <tr>
* <th>Name</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>protocol</td>
* <td>Name assigned to protocol. For example, <code>smtp</code> for
* Transport.</td>
* </tr>
* <tr>
* <td>type</td>
* <td>Valid entries are <code>store</code> and <code>transport</code>.</td>
* </tr>
* <tr>
* <td>class</td>
* <td>Class name that implements this protocol.</td>
* </tr>
* <tr>
* <td>vendor</td>
* <td>Optional string identifying the vendor.</td>
* </tr>
* <tr>
* <td>version</td>
* <td>Optional string identifying the version.</td>
* </tr>
* </table>
* <p>
*
* Here's an example of <code>META-INF/javamail.default.providers</code> file
* contents:
*
* <pre>
* protocol=imap; type=store; class=com.sun.mail.imap.IMAPStore; vendor=Oracle;
* protocol=smtp; type=transport; class=com.sun.mail.smtp.SMTPTransport; vendor=Oracle;
* </pre>
* <p>
*
* The current implementation also supports configuring providers using the Java
* SE {@link java.util.ServiceLoader ServiceLoader} mechanism. When creating
* your own provider, create a {@link Provider} subclass, for example:
*
* <pre>
* package com.example;
*
* import javax.mail.Provider;
*
* public class MyProvider extends Provider {
* public MyProvider() {
* super(Provider.Type.STORE, "myprot", MyStore.class.getName(), "Example", null);
* }
* }
* </pre>
*
* Then include a file named <code>META-INF/services/javax.mail.Provider</code>
* in your jar file that lists the name of your Provider class:
*
* <pre>
* com.example.MyProvider
* </pre>
* <p>
*
* <b><code>javamail.address.map</code></b> and
* <b><code>javamail.default.address.map</code></b>
* <p>
*
* These resource files map transport address types to the transport protocol.
* The <code>getType</code> method of <code>javax.mail.Address</code> returns
* the address type. The <code>javamail.address.map</code> file maps the
* transport type to the protocol. The file format is a series of name-value
* pairs. Each key name should correspond to an address type that is currently
* installed on the system; there should also be an entry for each
* <code>javax.mail.Address</code> implementation that is present if it is to be
* used. For example, the <code>javax.mail.internet.InternetAddress</code>
* method <code>getType</code> returns "rfc822". Each referenced protocol should
* be installed on the system. For the case of <code>news</code>, below, the
* client should install a Transport provider supporting the nntp protocol.
* <p>
*
* Here are the typical contents of a <code>javamail.address.map</code> file:
*
* <pre>
* rfc822=smtp
* news=nntp
* </pre>
*
* @author John Mani
* @author Bill Shannon
* @author Max Spivak
*/
public final class Session {
/**
* Get a new Session object.
*
* @param props Properties object that hold relevant properties.<br>
* It is expected that the client supplies values for the
* properties listed in Appendix A of the JavaMail spec
* (particularly mail.store.protocol,
* mail.transport.protocol, mail.host, mail.user, and
* mail.from) as the defaults are unlikely to work in all
* cases.
* @param authenticator Authenticator object used to call back to the
* application when a user name and password is needed.
* @return a new Session object
* @see javax.mail.Authenticator
*/
public static Session getInstance(Properties props, Authenticator authenticator) {
return null;
}
/**
* Get a new Session object.
*
* @param props Properties object that hold relevant properties.<br>
* It is expected that the client supplies values for the
* properties listed in Appendix A of the JavaMail spec
* (particularly mail.store.protocol, mail.transport.protocol,
* mail.host, mail.user, and mail.from) as the defaults are
* unlikely to work in all cases.
* @return a new Session object
* @since JavaMail 1.2
*/
public static Session getInstance(Properties props) {
return null;
}
/**
* Get the default Session object. If a default has not yet been setup, a new
* Session object is created and installed as the default.
* <p>
*
* Since the default session is potentially available to all code executing in
* the same Java virtual machine, and the session can contain security sensitive
* information such as user names and passwords, access to the default session
* is restricted. The Authenticator object, which must be created by the caller,
* is used indirectly to check access permission. The Authenticator object
* passed in when the session is created is compared with the Authenticator
* object passed in to subsequent requests to get the default session. If both
* objects are the same, or are from the same ClassLoader, the request is
* allowed. Otherwise, it is denied.
* <p>
*
* Note that if the Authenticator object used to create the session is null,
* anyone can get the default session by passing in null.
* <p>
*
* Note also that the Properties object is used only the first time this method
* is called, when a new Session object is created. Subsequent calls return the
* Session object that was created by the first call, and ignore the passed
* Properties object. Use the <code>getInstance</code> method to get a new
* Session object every time the method is called.
* <p>
*
* Additional security Permission objects may be used to control access to the
* default session.
* <p>
*
* In the current implementation, if a SecurityManager is set, the caller must
* have the <code>RuntimePermission("setFactory")</code> permission.
*
* @param props Properties object. Used only if a new Session object is
* created.<br>
* It is expected that the client supplies values for the
* properties listed in Appendix A of the JavaMail spec
* (particularly mail.store.protocol,
* mail.transport.protocol, mail.host, mail.user, and
* mail.from) as the defaults are unlikely to work in all
* cases.
* @param authenticator Authenticator object. Used only if a new Session object
* is created. Otherwise, it must match the Authenticator
* used to create the Session.
* @return the default Session object
*/
public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator) {
return null;
}
/**
* Get the default Session object. If a default has not yet been setup, a new
* Session object is created and installed as the default.
* <p>
*
* Note that a default session created with no Authenticator is available to all
* code executing in the same Java virtual machine, and the session can contain
* security sensitive information such as user names and passwords.
*
* @param props Properties object. Used only if a new Session object is
* created.<br>
* It is expected that the client supplies values for the
* properties listed in Appendix A of the JavaMail spec
* (particularly mail.store.protocol, mail.transport.protocol,
* mail.host, mail.user, and mail.from) as the defaults are
* unlikely to work in all cases.
* @return the default Session object
* @since JavaMail 1.2
*/
public static Session getDefaultInstance(Properties props) {
return null;
}
}
| 13,332 | 39.898773 | 103 | java |
codeql | codeql-master/java/ql/test/stubs/commons-exec-1.3/org/apache/commons/exec/CommandLine.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* Adapted from Apache Commons Exec version 1.3 as available at
* https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-exec/1.3/commons-exec-1.3-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package org.apache.commons.exec;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
public class CommandLine {
public static CommandLine parse(final String line) {
return null;
}
public static CommandLine parse(final String line, final Map<String, ?> substitutionMap) {
return null;
}
public CommandLine(final String executable) {
}
public CommandLine(final File executable) {
}
public CommandLine(final CommandLine other)
{
}
public CommandLine addArguments(final String[] addArguments) {
return this.addArguments(addArguments, true);
}
public CommandLine addArguments(final String[] addArguments, final boolean handleQuoting) {
return this;
}
public CommandLine addArguments(final String addArguments) {
return this.addArguments(addArguments, true);
}
public CommandLine addArguments(final String addArguments, final boolean handleQuoting) {
return this;
}
public CommandLine addArgument(final String argument) {
return this.addArgument(argument, true);
}
public CommandLine addArgument(final String argument, final boolean handleQuoting) {
return this;
}
} | 2,325 | 28.443038 | 117 | java |
codeql | codeql-master/java/ql/test/stubs/commons-exec-1.3/org/apache/commons/exec/DefaultExecutor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from Apache Commons Exec version 1.3 as available at
* https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-exec/1.3/commons-exec-1.3-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package org.apache.commons.exec;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class DefaultExecutor {
public int execute(final CommandLine command) throws
IOException {
return execute(command, (Map<String, String>) null);
}
public int execute(final CommandLine command, final Map<String, String> environment)
throws IOException {
return -1;
}
} | 1,505 | 34.857143 | 117 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/Servlet.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet;
import java.io.IOException;
public interface Servlet {
public void init(ServletConfig config) throws ServletException;
public ServletConfig getServletConfig();
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
public String getServletInfo();
public void destroy();
}
| 1,262 | 34.083333 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/ServletException.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet;
public class ServletException extends Exception {
}
| 965 | 33.5 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/RequestDispatcher.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet;
import java.io.IOException;
public interface RequestDispatcher {
public void forward(ServletRequest request, ServletResponse response)
throws ServletException, IOException;
public void include(ServletRequest request, ServletResponse response)
throws ServletException, IOException;
}
| 1,229 | 35.176471 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/ServletContext.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Set;
public interface ServletContext {
public ServletContext getContext(String uripath);
public int getMajorVersion();
public int getMinorVersion();
public String getMimeType(String file);
public Set getResourcePaths(String path);
public URL getResource(String path) throws MalformedURLException;
public InputStream getResourceAsStream(String path);
public RequestDispatcher getRequestDispatcher(String path);
public RequestDispatcher getNamedDispatcher(String name);
public Servlet getServlet(String name) throws ServletException;
public Enumeration getServlets();
public Enumeration getServletNames();
public void log(String msg);
public void log(Exception exception, String msg);
public void log(String message, Throwable throwable);
public String getRealPath(String path);
public String getServerInfo();
public String getInitParameter(String name);
public Enumeration getInitParameterNames();
public Object getAttribute(String name);
public Enumeration getAttributeNames();
public void setAttribute(String name, Object object);
public void removeAttribute(String name);
public String getServletContextName();
}
| 2,260 | 37.982759 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/ServletConfig.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet;
import java.util.Enumeration;
public interface ServletConfig {
public String getServletName();
public ServletContext getServletContext();
public String getInitParameter(String name);
public Enumeration getInitParameterNames();
}
| 1,159 | 33.117647 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/ServletResponse.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
public interface ServletResponse {
public String getCharacterEncoding();
public String getContentType();
public ServletOutputStream getOutputStream() throws IOException;
public PrintWriter getWriter() throws IOException;
public void setCharacterEncoding(String charset);
public void setContentLength(int len);
public void setContentType(String type);
public void setBufferSize(int size);
public int getBufferSize();
public void flushBuffer() throws IOException;
public void resetBuffer();
public boolean isCommitted();
public void reset();
public void setLocale(Locale loc);
public Locale getLocale();
}
| 1,659 | 34.319149 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/ServletOutputStream.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet;
import java.io.IOException;
import java.io.OutputStream;
public abstract class ServletOutputStream extends OutputStream {
protected ServletOutputStream() {
}
public void print(String s) throws IOException {
}
public void print(boolean b) throws IOException {
}
public void print(char c) throws IOException {
}
public void print(int i) throws IOException {
}
public void print(long l) throws IOException {
}
public void print(float f) throws IOException {
}
public void print(double d) throws IOException {
}
public void println() throws IOException {
}
public void println(String s) throws IOException {
}
public void println(boolean b) throws IOException {
}
public void println(char c) throws IOException {
}
public void println(int i) throws IOException {
}
public void println(long l) throws IOException {
}
public void println(float f) throws IOException {
}
public void println(double d) throws IOException {
}
}
| 1,961 | 30.142857 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/ServletRequest.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
public interface ServletRequest {
public Object getAttribute(String name);
public Enumeration getAttributeNames();
public String getCharacterEncoding();
public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException;
public int getContentLength();
public String getContentType();
public ServletInputStream getInputStream() throws IOException;
public String getParameter(String name);
public Enumeration getParameterNames();
public String[] getParameterValues(String name);
public Map getParameterMap();
public String getProtocol();
public String getScheme();
public String getServerName();
public int getServerPort();
public BufferedReader getReader() throws IOException;
public String getRemoteAddr();
public String getRemoteHost();
public void setAttribute(String name, Object o);
public void removeAttribute(String name);
public Locale getLocale();
public Enumeration getLocales();
public boolean isSecure();
public RequestDispatcher getRequestDispatcher(String path);
public String getRealPath(String path);
public int getRemotePort();
public String getLocalName();
public String getLocalAddr();
public int getLocalPort();
}
| 2,321 | 35.857143 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/ServletInputStream.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet;
import java.io.IOException;
import java.io.InputStream;
public abstract class ServletInputStream extends InputStream {
protected ServletInputStream() {
}
public int readLine(byte[] b, int off, int len) throws IOException {
}
}
| 1,157 | 32.085714 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/http/HttpSession.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet.http;
import java.util.Enumeration;
import javax.servlet.ServletContext;
public interface HttpSession {
public long getCreationTime();
public String getId();
public long getLastAccessedTime();
public ServletContext getServletContext();
public void setMaxInactiveInterval(int interval);
public int getMaxInactiveInterval();
public HttpSessionContext getSessionContext();
public Object getAttribute(String name);
public Object getValue(String name);
public Enumeration getAttributeNames();
public String[] getValueNames();
public void setAttribute(String name, Object value);
public void putValue(String name, Object value);
public void removeAttribute(String name);
public void removeValue(String name);
public void invalidate();
public boolean isNew();
}
| 1,736 | 35.1875 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/http/HttpServletRequest.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet.http;
import java.util.Enumeration;
import javax.servlet.ServletRequest;
public interface HttpServletRequest extends ServletRequest {
public String getAuthType();
public Cookie[] getCookies();
public long getDateHeader(String name);
public String getHeader(String name);
public Enumeration getHeaders(String name);
public Enumeration getHeaderNames();
public int getIntHeader(String name);
public String getMethod();
public String getPathInfo();
public String getPathTranslated();
public String getContextPath();
public String getQueryString();
public String getRemoteUser();
public boolean isUserInRole(String role);
public java.security.Principal getUserPrincipal();
public String getRequestedSessionId();
public String getRequestURI();
public StringBuffer getRequestURL();
public String getServletPath();
public HttpSession getSession(boolean create);
public HttpSession getSession();
public boolean isRequestedSessionIdValid();
public boolean isRequestedSessionIdFromCookie();
public boolean isRequestedSessionIdFromURL();
public boolean isRequestedSessionIdFromUrl();
}
| 2,088 | 36.303571 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/http/HttpSessionContext.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet.http;
import java.util.Enumeration;
/**
* @deprecated
*/
public interface HttpSessionContext {
public HttpSession getSession(String sessionId);
public Enumeration getIds();
}
| 1,098 | 30.4 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/http/HttpServletResponse.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet.http;
import java.io.IOException;
import javax.servlet.ServletResponse;
public interface HttpServletResponse extends ServletResponse {
public void addCookie(Cookie cookie);
public boolean containsHeader(String name);
public String encodeURL(String url);
public String encodeRedirectURL(String url);
public String encodeUrl(String url);
public String encodeRedirectUrl(String url);
public void sendError(int sc, String msg) throws IOException;
public void sendError(int sc) throws IOException;
public void sendRedirect(String location) throws IOException;
public void setDateHeader(String name, long date);
public void addDateHeader(String name, long date);
public void setHeader(String name, String value);
public void addHeader(String name, String value);
public void setIntHeader(String name, int value);
public void addIntHeader(String name, int value);
public void setStatus(int sc);
public void setStatus(int sc, String sm);
public static final int SC_CONTINUE = 100;
public static final int SC_SWITCHING_PROTOCOLS = 101;
public static final int SC_OK = 200;
public static final int SC_CREATED = 201;
public static final int SC_ACCEPTED = 202;
public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
public static final int SC_NO_CONTENT = 204;
public static final int SC_RESET_CONTENT = 205;
public static final int SC_PARTIAL_CONTENT = 206;
public static final int SC_MULTIPLE_CHOICES = 300;
public static final int SC_MOVED_PERMANENTLY = 301;
public static final int SC_MOVED_TEMPORARILY = 302;
public static final int SC_FOUND = 302;
public static final int SC_SEE_OTHER = 303;
public static final int SC_NOT_MODIFIED = 304;
public static final int SC_USE_PROXY = 305;
public static final int SC_TEMPORARY_REDIRECT = 307;
public static final int SC_BAD_REQUEST = 400;
public static final int SC_UNAUTHORIZED = 401;
public static final int SC_PAYMENT_REQUIRED = 402;
public static final int SC_FORBIDDEN = 403;
public static final int SC_NOT_FOUND = 404;
public static final int SC_METHOD_NOT_ALLOWED = 405;
public static final int SC_NOT_ACCEPTABLE = 406;
public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
public static final int SC_REQUEST_TIMEOUT = 408;
public static final int SC_CONFLICT = 409;
public static final int SC_GONE = 410;
public static final int SC_LENGTH_REQUIRED = 411;
public static final int SC_PRECONDITION_FAILED = 412;
public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;
public static final int SC_REQUEST_URI_TOO_LONG = 414;
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
public static final int SC_EXPECTATION_FAILED = 417;
public static final int SC_INTERNAL_SERVER_ERROR = 500;
public static final int SC_NOT_IMPLEMENTED = 501;
public static final int SC_BAD_GATEWAY = 502;
public static final int SC_SERVICE_UNAVAILABLE = 503;
public static final int SC_GATEWAY_TIMEOUT = 504;
public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
}
| 4,128 | 44.877778 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/http/Cookie.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet.http;
public class Cookie implements Cloneable {
private String name; // NAME= ... "$Name" style is reserved
private String value; // value of NAME
private String comment; // ;Comment=VALUE ... describes cookie's use
private String domain; // ;Domain=VALUE ... domain that sees cookie
private int maxAge = -1; // ;Max-Age=VALUE ... cookies auto-expire
private String path; // ;Path=VALUE ... URLs that see the cookie
private boolean secure; // ;Secure ... e.g. use SSL
private int version = 0; // ;Version=1 ... means RFC 2109++ style
public Cookie(String name, String value) {
this.name = name;
this.value = value;
}
public void setComment(String purpose) {
comment = purpose;
}
public String getComment() {
return comment;
}
public void setDomain(String pattern) {
domain = pattern.toLowerCase(); // IE allegedly needs this
}
public String getDomain() {
return domain;
}
public void setMaxAge(int expiry) {
maxAge = expiry;
}
public int getMaxAge() {
return maxAge;
}
public void setPath(String uri) {
path = uri;
}
public String getPath() {
return path;
}
public void setSecure(boolean flag) {
secure = flag;
}
public boolean getSecure() {
return secure;
}
public String getName() {
return name;
}
public void setValue(String newValue) {
value = newValue;
}
public String getValue() {
return value;
}
public int getVersion() {
return version;
}
public void setVersion(int v) {
}
}
| 2,585 | 29.423529 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/servlet-api-2.4/javax/servlet/http/HttpServlet.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Adapted from the Java Servlet API version 2.4 as available at
* http://search.maven.org/remotecontent?filepath=javax/servlet/servlet-api/2.4/servlet-api-2.4-sources.jar
* Only relevant stubs of this file have been retained for test purposes.
*/
package javax.servlet.http;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public abstract class HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
protected long getLastModified(HttpServletRequest req) {
return -1;
}
protected void doHead(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
}
}
| 2,376 | 36.730159 | 109 | java |
codeql | codeql-master/java/ql/test/stubs/apache-commons-codec-1.14/org/apache/commons/codec/BinaryEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Defines common encoding methods for byte array encoders.
*
*/
public interface BinaryEncoder extends Encoder {
/**
* Encodes a byte array and return the encoded data as a byte array.
*
* @param source
* Data to be encoded
* @return A byte array containing the encoded data
* @throws EncoderException
* thrown if the Encoder encounters a failure condition during the encoding process.
*/
byte[] encode(byte[] source) throws EncoderException;
}
| 1,364 | 34.921053 | 100 | java |
codeql | codeql-master/java/ql/test/stubs/apache-commons-codec-1.14/org/apache/commons/codec/EncoderException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Thrown when there is a failure condition during the encoding process. This exception is thrown when an
* {@link Encoder} encounters a encoding specific exception such as invalid data, inability to calculate a checksum,
* characters outside of the expected range.
*
*/
public class EncoderException extends Exception {
/**
* Declares the Serial Version Uid.
*
* @see <a href="http://c2.com/cgi/wiki?AlwaysDeclareSerialVersionUid">Always Declare Serial Version Uid</a>
*/
private static final long serialVersionUID = 1L;
/**
* Constructs a new exception with {@code null} as its detail message. The cause is not initialized, and may
* subsequently be initialized by a call to {@link #initCause}.
*
* @since 1.4
*/
public EncoderException() {
super();
}
/**
* Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently
* be initialized by a call to {@link #initCause}.
*
* @param message
* a useful message relating to the encoder specific error.
*/
public EncoderException(final String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* <p>
* Note that the detail message associated with {@code cause} is not automatically incorporated into this
* exception's detail message.
* </p>
*
* @param message
* The detail message which is saved for later retrieval by the {@link #getMessage()} method.
* @param cause
* The cause which is saved for later retrieval by the {@link #getCause()} method. A {@code null}
* value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public EncoderException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause and a detail message of <code>(cause==null ?
* null : cause.toString())</code> (which typically contains the class and detail message of {@code cause}).
* This constructor is useful for exceptions that are little more than wrappers for other throwables.
*
* @param cause
* The cause which is saved for later retrieval by the {@link #getCause()} method. A {@code null}
* value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public EncoderException(final Throwable cause) {
super(cause);
}
}
| 3,495 | 38.280899 | 119 | java |
codeql | codeql-master/java/ql/test/stubs/apache-commons-codec-1.14/org/apache/commons/codec/DecoderException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Thrown when there is a failure condition during the decoding process. This exception is thrown when a {@link Decoder}
* encounters a decoding specific exception such as invalid data, or characters outside of the expected range.
*
*/
public class DecoderException extends Exception {
/**
* Declares the Serial Version Uid.
*
* @see <a href="http://c2.com/cgi/wiki?AlwaysDeclareSerialVersionUid">Always Declare Serial Version Uid</a>
*/
private static final long serialVersionUID = 1L;
/**
* Constructs a new exception with {@code null} as its detail message. The cause is not initialized, and may
* subsequently be initialized by a call to {@link #initCause}.
*
* @since 1.4
*/
public DecoderException() {
super();
}
/**
* Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently
* be initialized by a call to {@link #initCause}.
*
* @param message
* The detail message which is saved for later retrieval by the {@link #getMessage()} method.
*/
public DecoderException(final String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
* <p>
* Note that the detail message associated with {@code cause} is not automatically incorporated into this
* exception's detail message.
*
* @param message
* The detail message which is saved for later retrieval by the {@link #getMessage()} method.
* @param cause
* The cause which is saved for later retrieval by the {@link #getCause()} method. A {@code null}
* value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public DecoderException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause and a detail message of <code>(cause==null ?
* null : cause.toString())</code> (which typically contains the class and detail message of {@code cause}).
* This constructor is useful for exceptions that are little more than wrappers for other throwables.
*
* @param cause
* The cause which is saved for later retrieval by the {@link #getCause()} method. A {@code null}
* value is permitted, and indicates that the cause is nonexistent or unknown.
* @since 1.4
*/
public DecoderException(final Throwable cause) {
super(cause);
}
}
| 3,474 | 39.406977 | 120 | java |
codeql | codeql-master/java/ql/test/stubs/apache-commons-codec-1.14/org/apache/commons/codec/BinaryDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Defines common decoding methods for byte array decoders.
*
*/
public interface BinaryDecoder extends Decoder {
/**
* Decodes a byte array and returns the results as a byte array.
*
* @param source
* A byte array which has been encoded with the appropriate encoder
* @return a byte array that contains decoded content
* @throws DecoderException
* A decoder exception is thrown if a Decoder encounters a failure condition during the decode process.
*/
byte[] decode(byte[] source) throws DecoderException;
}
| 1,427 | 36.578947 | 119 | java |
codeql | codeql-master/java/ql/test/stubs/apache-commons-codec-1.14/org/apache/commons/codec/StringDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Defines common decoding methods for String decoders.
*
*/
public interface StringDecoder extends Decoder {
/**
* Decodes a String and returns a String.
*
* @param source
* the String to decode
* @return the encoded String
* @throws DecoderException
* thrown if there is an error condition during the Encoding process.
*/
String decode(String source) throws DecoderException;
}
| 1,298 | 33.184211 | 85 | java |
codeql | codeql-master/java/ql/test/stubs/apache-commons-codec-1.14/org/apache/commons/codec/Decoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Provides the highest level of abstraction for Decoders.
* <p>
* This is the sister interface of {@link Encoder}. All Decoders implement this common generic interface.
* Allows a user to pass a generic Object to any Decoder implementation in the codec package.
* <p>
* One of the two interfaces at the center of the codec package.
*
*/
public interface Decoder {
/**
* Decodes an "encoded" Object and returns a "decoded" Object. Note that the implementation of this interface will
* try to cast the Object parameter to the specific type expected by a particular Decoder implementation. If a
* {@link ClassCastException} occurs this decode method will throw a DecoderException.
*
* @param source
* the object to decode
* @return a 'decoded" object
* @throws DecoderException
* a decoder exception can be thrown for any number of reasons. Some good candidates are that the
* parameter passed to this method is null, a param cannot be cast to the appropriate type for a
* specific encoder.
*/
Object decode(Object source) throws DecoderException;
}
| 2,015 | 41.893617 | 118 | java |
codeql | codeql-master/java/ql/test/stubs/apache-commons-codec-1.14/org/apache/commons/codec/StringEncoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Defines common encoding methods for String encoders.
*
*/
public interface StringEncoder extends Encoder {
/**
* Encodes a String and returns a String.
*
* @param source
* the String to encode
* @return the encoded String
* @throws EncoderException
* thrown if there is an error condition during the encoding process.
*/
String encode(String source) throws EncoderException;
}
| 1,298 | 33.184211 | 85 | java |
codeql | codeql-master/java/ql/test/stubs/apache-commons-codec-1.14/org/apache/commons/codec/Encoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* Provides the highest level of abstraction for Encoders.
* <p>
* This is the sister interface of {@link Decoder}. Every implementation of Encoder provides this
* common generic interface which allows a user to pass a generic Object to any Encoder implementation
* in the codec package.
*
*/
public interface Encoder {
/**
* Encodes an "Object" and returns the encoded content as an Object. The Objects here may just be
* {@code byte[]} or {@code String}s depending on the implementation used.
*
* @param source
* An object to encode
* @return An "encoded" Object
* @throws EncoderException
* An encoder exception is thrown if the encoder experiences a failure condition during the encoding
* process.
*/
Object encode(Object source) throws EncoderException;
}
| 1,707 | 37.818182 | 116 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/core/AttributesMapper.java | package org.springframework.ldap.core;
public interface AttributesMapper<T> {} | 79 | 25.666667 | 39 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/core/LdapOperations.java | package org.springframework.ldap.core;
public interface LdapOperations {} | 74 | 24 | 38 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/core/DirContextProcessor.java | package org.springframework.ldap.core;
public interface DirContextProcessor {} | 79 | 25.666667 | 39 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/core/LdapTemplate.java | package org.springframework.ldap.core;
import org.springframework.beans.factory.InitializingBean;
import java.util.*;
import javax.naming.Name;
import javax.naming.directory.SearchControls;
import org.springframework.ldap.filter.Filter;
import org.springframework.ldap.query.LdapQuery;
public class LdapTemplate implements LdapOperations, InitializingBean {
public void authenticate(LdapQuery query, String password) { }
public boolean authenticate(Name base, String filter, String password) { return true; }
public <T> List<T> find(Name base, Filter filter, SearchControls searchControls, final Class<T> clazz) { return null; }
public <T> List<T> find(LdapQuery query, Class<T> clazz) { return null; }
public <T> T findOne(LdapQuery query, Class<T> clazz) { return null; }
public void search(String base, String filter, int searchScope, boolean returningObjFlag, NameClassPairCallbackHandler handler) { }
public void search(final String base, final String filter, final SearchControls controls, NameClassPairCallbackHandler handler) {}
public void search(final String base, final String filter, final SearchControls controls, NameClassPairCallbackHandler handler, DirContextProcessor processor) {}
public void search(String base, String filter, NameClassPairCallbackHandler handler) {}
public <T> List<T> search(String base, String filter, int searchScope, String[] attrs, AttributesMapper<T> mapper) { return null; }
public <T> List<T> search(String base, String filter, int searchScope, AttributesMapper<T> mapper) { return null; }
public <T> List<T> search(String base, String filter, AttributesMapper<T> mapper) { return null; }
public <T> List<T> search(String base, String filter, int searchScope, String[] attrs, ContextMapper<T> mapper) { return null; }
public <T> List<T> search(String base, String filter, int searchScope, ContextMapper<T> mapper) { return null; }
public <T> List<T> search(String base, String filter, ContextMapper<T> mapper) { return null; }
public <T> List<T> search(String base, String filter, SearchControls controls, ContextMapper<T> mapper) { return null; }
public <T> List<T> search(String base, String filter, SearchControls controls, AttributesMapper<T> mapper) { return null; }
public <T> List<T> search(String base, String filter, SearchControls controls, AttributesMapper<T> mapper, DirContextProcessor processor) { return null; }
public <T> List<T> search(String base, String filter, SearchControls controls, ContextMapper<T> mapper, DirContextProcessor processor) { return null; }
public DirContextOperations searchForContext(LdapQuery query) { return null; }
public <T> T searchForObject(Name base, String filter, ContextMapper<T> mapper) { return null; }
public <T> T searchForObject(String base, String filter, ContextMapper<T> mapper) { return null; }
public <T> T searchForObject(String base, String filter, SearchControls searchControls, ContextMapper<T> mapper) { return null; }
public Object lookup(final String dn) { return new Object(); }
public DirContextOperations lookupContext(String dn) { return null; }
public <T> T findByDn(Name dn, final Class<T> clazz) { return null; }
public void rename(final Name oldDn, final Name newDn) {}
public List<String> list(final Name base) { return null; }
public List<String> listBindings(final Name base) { return null; }
public void unbind(final String dn) {}
public void unbind(final String dn, boolean recursive) {}
}
| 3,513 | 44.636364 | 163 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/core/DirContextOperations.java | package org.springframework.ldap.core;
public interface DirContextOperations {
}
| 82 | 15.6 | 39 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/core/ContextMapper.java | package org.springframework.ldap.core;
public interface ContextMapper<T> {
}
| 78 | 14.8 | 38 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/core/NameClassPairCallbackHandler.java | package org.springframework.ldap.core;
public interface NameClassPairCallbackHandler { }
| 90 | 21.75 | 49 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/filter/EqualsFilter.java | package org.springframework.ldap.filter;
public class EqualsFilter implements Filter {
public EqualsFilter(String attribute, String value) { }
}
| 148 | 23.833333 | 57 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/filter/HardcodedFilter.java | package org.springframework.ldap.filter;
public class HardcodedFilter implements Filter {
public HardcodedFilter(String filter) { }
public StringBuffer encode(StringBuffer buff) { return buff; }
public String toString() { return ""; }
}
| 244 | 29.625 | 64 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/filter/Filter.java | package org.springframework.ldap.filter;
public interface Filter {
}
| 70 | 13.2 | 40 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/support/LdapUtils.java | package org.springframework.ldap.support;
import javax.naming.ldap.LdapName;
public class LdapUtils {
public static LdapName newLdapName(String distinguishedName) { return null; }
}
| 186 | 22.375 | 79 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/support/LdapNameBuilder.java | package org.springframework.ldap.support;
import javax.naming.ldap.LdapName;
public class LdapNameBuilder {
public static LdapNameBuilder newInstance() { return null; }
public static LdapNameBuilder newInstance(String name) { return null; }
public LdapNameBuilder add(String name) { return null; }
public LdapNameBuilder add(String key, Object value) { return null; }
public LdapName build() { return null; }
}
| 424 | 31.692308 | 73 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/support/LdapEncoder.java | package org.springframework.ldap.support;
public class LdapEncoder {
public static String filterEncode(String value) { return null; }
}
| 139 | 22.333333 | 66 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/query/ContainerCriteria.java | package org.springframework.ldap.query;
public interface ContainerCriteria extends LdapQuery {
}
| 98 | 18.8 | 54 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/query/ConditionCriteria.java | package org.springframework.ldap.query;
public interface ConditionCriteria {
ContainerCriteria is(String value);
}
| 118 | 18.833333 | 39 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/query/LdapQuery.java | package org.springframework.ldap.query;
public interface LdapQuery {
}
| 72 | 13.6 | 39 | java |
codeql | codeql-master/java/ql/test/stubs/spring-ldap-2.3.2/org/springframework/ldap/query/LdapQueryBuilder.java | package org.springframework.ldap.query;
import javax.naming.Name;
import org.springframework.ldap.filter.Filter;
public class LdapQueryBuilder {
public static LdapQueryBuilder query() { return null; }
public LdapQuery filter(String hardcodedFilter) { return null; }
public LdapQuery filter(Filter filter) { return null; }
public LdapQuery filter(String filterFormat, Object... params) { return null; }
public LdapQueryBuilder base(String baseDn) { return this; }
public Name base() { return null; }
public ConditionCriteria where(String attribute) { return null; }
}
| 583 | 37.933333 | 81 | java |
codeql | codeql-master/java/ql/test/stubs/junit-4.11/org/junit/Assert.java | package org.junit;
//BSD License
//
//Copyright (c) 2000-2006, www.hamcrest.org
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
//
//Redistributions of source code must retain the above copyright notice, this list of
//conditions and the following disclaimer. Redistributions in binary form must reproduce
//the above copyright notice, this list of conditions and the following disclaimer in
//the documentation and/or other materials provided with the distribution.
//
//Neither the name of Hamcrest nor the names of its contributors may be used to endorse
//or promote products derived from this software without specific prior written
//permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
//SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
//TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
//BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
//CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
//WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
//DAMAGE.
/*
* MODIFIED version of JUnit 4.11 as available at
* https://search.maven.org/remotecontent?filepath=junit/junit/4.11/junit-4.11-sources.jar
* Only parts of this file have been retained for test purposes.
*/
public class Assert {
/**
* Asserts that a condition is true. If it isn't it throws an
* {@link AssertionError} with the given message.
*
* @param message the identifying message for the {@link AssertionError} (<code>null</code>
* okay)
* @param condition condition to be checked
*/
static public void assertTrue(String message, boolean condition) {
if (!condition) {
fail(message);
}
}
/**
* Asserts that a condition is true. If it isn't it throws an
* {@link AssertionError} without a message.
*
* @param condition condition to be checked
*/
static public void assertTrue(boolean condition) {
assertTrue(null, condition);
}
/**
* Asserts that a condition is false. If it isn't it throws an
* {@link AssertionError} with the given message.
*
* @param message the identifying message for the {@link AssertionError} (<code>null</code>
* okay)
* @param condition condition to be checked
*/
static public void assertFalse(String message, boolean condition) {
assertTrue(message, !condition);
}
/**
* Asserts that a condition is false. If it isn't it throws an
* {@link AssertionError} without a message.
*
* @param condition condition to be checked
*/
static public void assertFalse(boolean condition) {
assertFalse(null, condition);
}
/**
* Fails a test with the given message.
*
* @param message the identifying message for the {@link AssertionError} (<code>null</code>
* okay)
* @see AssertionError
*/
static public void fail(String message) {
if (message == null) {
throw new AssertionError();
}
throw new AssertionError(message);
}
/**
* Asserts that an object isn't null. If it is an {@link AssertionError} is
* thrown with the given message.
*
* @param message the identifying message for the {@link AssertionError} (<code>null</code>
* okay)
* @param object Object to check or <code>null</code>
*/
static public void assertNotNull(String message, Object object) {
assertTrue(message, object != null);
}
/**
* Asserts that an object isn't null. If it is an {@link AssertionError} is
* thrown.
*
* @param object Object to check or <code>null</code>
*/
static public void assertNotNull(Object object) {
assertNotNull(null, object);
}
/**
* Asserts that an object is null. If it is not, an {@link AssertionError}
* is thrown with the given message.
*
* @param message the identifying message for the {@link AssertionError} (<code>null</code>
* okay)
* @param object Object to check or <code>null</code>
*/
static public void assertNull(String message, Object object) {
if (object == null) {
return;
}
failNotNull(message, object);
}
/**
* Asserts that an object is null. If it isn't an {@link AssertionError} is
* thrown.
*
* @param object Object to check or <code>null</code>
*/
static public void assertNull(Object object) {
assertNull(null, object);
}
static private void failNotNull(String message, Object actual) {
String formatted = "";
if (message != null) {
formatted = message + " ";
}
fail(formatted + "expected null, but was:<" + actual + ">");
}
}
| 5,322 | 33.564935 | 95 | java |
hipster-shop | hipster-shop-master/src/adservice/src/main/java/hipstershop/AdServiceClient.java | /*
* Copyright 2018, Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hipstershop;
import hipstershop.Demo.Ad;
import hipstershop.Demo.AdRequest;
import hipstershop.Demo.AdResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import io.opencensus.common.Duration;
import io.opencensus.common.Scope;
import io.opencensus.contrib.grpc.metrics.RpcViews;
import io.opencensus.contrib.grpc.util.StatusConverter;
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration;
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsExporter;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceConfiguration;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceExporter;
import io.opencensus.trace.Span;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.Tracing;
import io.opencensus.trace.samplers.Samplers;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/** A simple client that requests ads from the Ads Service. */
public class AdServiceClient {
private static final Logger logger = LogManager.getLogger(AdServiceClient.class);
private static final Tracer tracer = Tracing.getTracer();
private final ManagedChannel channel;
private final hipstershop.AdServiceGrpc.AdServiceBlockingStub blockingStub;
/** Construct client connecting to Ad Service at {@code host:port}. */
private AdServiceClient(String host, int port) {
this(
ManagedChannelBuilder.forAddress(host, port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext()
.build());
}
/** Construct client for accessing RouteGuide server using the existing channel. */
private AdServiceClient(ManagedChannel channel) {
this.channel = channel;
blockingStub = hipstershop.AdServiceGrpc.newBlockingStub(channel);
}
private void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
/** Get Ads from Server. */
public void getAds(String contextKey) {
logger.info("Get Ads with context " + contextKey + " ...");
AdRequest request = AdRequest.newBuilder().addContextKeys(contextKey).build();
AdResponse response;
Span span =
tracer
.spanBuilder("AdsClient")
.setRecordEvents(true)
.setSampler(Samplers.alwaysSample())
.startSpan();
try (Scope ignored = tracer.withSpan(span)) {
tracer.getCurrentSpan().addAnnotation("Getting Ads");
response = blockingStub.getAds(request);
tracer.getCurrentSpan().addAnnotation("Received response from Ads Service.");
} catch (StatusRuntimeException e) {
tracer.getCurrentSpan().setStatus(StatusConverter.fromGrpcStatus(e.getStatus()));
logger.log(Level.WARN, "RPC failed: " + e.getStatus());
return;
} finally {
span.end();
}
for (Ad ads : response.getAdsList()) {
logger.info("Ads: " + ads.getText());
}
}
private static int getPortOrDefaultFromArgs(String[] args) {
int portNumber = 9555;
if (2 < args.length) {
try {
portNumber = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
logger.warn(String.format("Port %s is invalid, use default port %d.", args[2], 9555));
}
}
return portNumber;
}
private static String getStringOrDefaultFromArgs(
String[] args, int index, @Nullable String defaultString) {
String s = defaultString;
if (index < args.length) {
s = args[index];
}
return s;
}
/**
* Ads Service Client main. If provided, the first element of {@code args} is the context key to
* get the ads from the Ads Service
*/
public static void main(String[] args) throws InterruptedException {
// Add final keyword to pass checkStyle.
final String contextKeys = getStringOrDefaultFromArgs(args, 0, "camera");
final String host = getStringOrDefaultFromArgs(args, 1, "localhost");
final int serverPort = getPortOrDefaultFromArgs(args);
// Registers all RPC views.
RpcViews.registerAllGrpcViews();
// Registers Stackdriver exporters.
long sleepTime = 10; /* seconds */
int maxAttempts = 3;
for (int i = 0; i < maxAttempts; i++) {
try {
StackdriverTraceExporter.createAndRegister(StackdriverTraceConfiguration.builder().build());
StackdriverStatsExporter.createAndRegister(
StackdriverStatsConfiguration.builder()
.setExportInterval(Duration.create(15, 0))
.build());
} catch (Exception e) {
if (i == (maxAttempts - 1)) {
logger.log(
Level.WARN,
"Failed to register Stackdriver Exporter."
+ " Tracing and Stats data will not reported to Stackdriver. Error message: "
+ e.toString());
} else {
logger.info("Attempt to register Stackdriver Exporter in " + sleepTime + " seconds");
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(sleepTime));
} catch (Exception se) {
logger.log(Level.WARN, "Exception while sleeping" + e.toString());
}
}
}
}
// Register Prometheus exporters and export metrics to a Prometheus HTTPServer.
// PrometheusStatsCollector.createAndRegister();
AdServiceClient client = new AdServiceClient(host, serverPort);
try {
client.getAds(contextKeys);
} finally {
client.shutdown();
}
logger.info("Exiting AdServiceClient...");
}
}
| 6,353 | 35.102273 | 100 | java |
hipster-shop | hipster-shop-master/src/adservice/src/main/java/hipstershop/AdService.java | /*
* Copyright 2018, Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hipstershop;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import hipstershop.Demo.Ad;
import hipstershop.Demo.AdRequest;
import hipstershop.Demo.AdResponse;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.StatusRuntimeException;
import io.grpc.health.v1.HealthCheckResponse.ServingStatus;
import io.grpc.services.*;
import io.grpc.stub.StreamObserver;
import io.opencensus.common.Duration;
import io.opencensus.contrib.grpc.metrics.RpcViews;
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration;
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsExporter;
import io.opencensus.exporter.trace.jaeger.JaegerExporterConfiguration;
import io.opencensus.exporter.trace.jaeger.JaegerTraceExporter;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceConfiguration;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceExporter;
import io.opencensus.trace.AttributeValue;
import io.opencensus.trace.Span;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.Tracing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public final class AdService {
private static final Logger logger = LogManager.getLogger(AdService.class);
private static final Tracer tracer = Tracing.getTracer();
@SuppressWarnings("FieldCanBeLocal")
private static int MAX_ADS_TO_SERVE = 2;
private Server server;
private HealthStatusManager healthMgr;
private static final AdService service = new AdService();
private void start() throws IOException {
int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "9555"));
healthMgr = new HealthStatusManager();
server =
ServerBuilder.forPort(port)
.addService(new AdServiceImpl())
.addService(healthMgr.getHealthService())
.build()
.start();
logger.info("Ad Service started, listening on " + port);
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println(
"*** shutting down gRPC ads server since JVM is shutting down");
AdService.this.stop();
System.err.println("*** server shut down");
}));
healthMgr.setStatus("", ServingStatus.SERVING);
}
private void stop() {
if (server != null) {
healthMgr.clearStatus("");
server.shutdown();
}
}
private static class AdServiceImpl extends hipstershop.AdServiceGrpc.AdServiceImplBase {
/**
* Retrieves ads based on context provided in the request {@code AdRequest}.
*
* @param req the request containing context.
* @param responseObserver the stream observer which gets notified with the value of {@code
* AdResponse}
*/
@Override
public void getAds(AdRequest req, StreamObserver<AdResponse> responseObserver) {
AdService service = AdService.getInstance();
Span span = tracer.getCurrentSpan();
try {
span.putAttribute("method", AttributeValue.stringAttributeValue("getAds"));
List<Ad> allAds = new ArrayList<>();
logger.info("received ad request (context_words=" + req.getContextKeysList() + ")");
if (req.getContextKeysCount() > 0) {
span.addAnnotation(
"Constructing Ads using context",
ImmutableMap.of(
"Context Keys",
AttributeValue.stringAttributeValue(req.getContextKeysList().toString()),
"Context Keys length",
AttributeValue.longAttributeValue(req.getContextKeysCount())));
for (int i = 0; i < req.getContextKeysCount(); i++) {
Collection<Ad> ads = service.getAdsByCategory(req.getContextKeys(i));
allAds.addAll(ads);
}
} else {
span.addAnnotation("No Context provided. Constructing random Ads.");
allAds = service.getRandomAds();
}
if (allAds.isEmpty()) {
// Serve random ads.
span.addAnnotation("No Ads found based on context. Constructing random Ads.");
allAds = service.getRandomAds();
}
AdResponse reply = AdResponse.newBuilder().addAllAds(allAds).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
} catch (StatusRuntimeException e) {
logger.log(Level.WARN, "GetAds Failed with status {}", e.getStatus());
responseObserver.onError(e);
}
}
}
private static final ImmutableListMultimap<String, Ad> adsMap = createAdsMap();
private Collection<Ad> getAdsByCategory(String category) {
return adsMap.get(category);
}
private static final Random random = new Random();
private List<Ad> getRandomAds() {
List<Ad> ads = new ArrayList<>(MAX_ADS_TO_SERVE);
Collection<Ad> allAds = adsMap.values();
for (int i = 0; i < MAX_ADS_TO_SERVE; i++) {
ads.add(Iterables.get(allAds, random.nextInt(allAds.size())));
}
return ads;
}
private static AdService getInstance() {
return service;
}
/** Await termination on the main thread since the grpc library uses daemon threads. */
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
private static ImmutableListMultimap<String, Ad> createAdsMap() {
Ad camera =
Ad.newBuilder()
.setRedirectUrl("/product/2ZYFJ3GM2N")
.setText("Film camera for sale. 50% off.")
.build();
Ad lens =
Ad.newBuilder()
.setRedirectUrl("/product/66VCHSJNUP")
.setText("Vintage camera lens for sale. 20% off.")
.build();
Ad recordPlayer =
Ad.newBuilder()
.setRedirectUrl("/product/0PUK6V6EV0")
.setText("Vintage record player for sale. 30% off.")
.build();
Ad bike =
Ad.newBuilder()
.setRedirectUrl("/product/9SIQT8TOJO")
.setText("City Bike for sale. 10% off.")
.build();
Ad baristaKit =
Ad.newBuilder()
.setRedirectUrl("/product/1YMWWN1N4O")
.setText("Home Barista kitchen kit for sale. Buy one, get second kit for free")
.build();
Ad airPlant =
Ad.newBuilder()
.setRedirectUrl("/product/6E92ZMYYFZ")
.setText("Air plants for sale. Buy two, get third one for free")
.build();
Ad terrarium =
Ad.newBuilder()
.setRedirectUrl("/product/L9ECAV7KIM")
.setText("Terrarium for sale. Buy one, get second one for free")
.build();
return ImmutableListMultimap.<String, Ad>builder()
.putAll("photography", camera, lens)
.putAll("vintage", camera, lens, recordPlayer)
.put("cycling", bike)
.put("cookware", baristaKit)
.putAll("gardening", airPlant, terrarium)
.build();
}
private static void initStats() {
if (System.getenv("DISABLE_STATS") != null) {
logger.info("Stats disabled.");
return;
}
logger.info("Stats enabled");
long sleepTime = 10; /* seconds */
int maxAttempts = 5;
boolean statsExporterRegistered = false;
for (int i = 0; i < maxAttempts; i++) {
try {
if (!statsExporterRegistered) {
StackdriverStatsExporter.createAndRegister(
StackdriverStatsConfiguration.builder()
.setExportInterval(Duration.create(60, 0))
.build());
statsExporterRegistered = true;
}
} catch (Exception e) {
if (i == (maxAttempts - 1)) {
logger.log(
Level.WARN,
"Failed to register Stackdriver Exporter."
+ " Stats data will not reported to Stackdriver. Error message: "
+ e.toString());
} else {
logger.info("Attempt to register Stackdriver Exporter in " + sleepTime + " seconds ");
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(sleepTime));
} catch (Exception se) {
logger.log(Level.WARN, "Exception while sleeping" + se.toString());
}
}
}
}
logger.info("Stats enabled - Stackdriver Exporter initialized.");
}
private static void initTracing() {
if (System.getenv("DISABLE_TRACING") != null) {
logger.info("Tracing disabled.");
return;
}
logger.info("Tracing enabled");
long sleepTime = 10; /* seconds */
int maxAttempts = 5;
boolean traceExporterRegistered = false;
for (int i = 0; i < maxAttempts; i++) {
try {
if (!traceExporterRegistered) {
StackdriverTraceExporter.createAndRegister(
StackdriverTraceConfiguration.builder().build());
traceExporterRegistered = true;
}
} catch (Exception e) {
if (i == (maxAttempts - 1)) {
logger.log(
Level.WARN,
"Failed to register Stackdriver Exporter."
+ " Tracing data will not reported to Stackdriver. Error message: "
+ e.toString());
} else {
logger.info("Attempt to register Stackdriver Exporter in " + sleepTime + " seconds ");
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(sleepTime));
} catch (Exception se) {
logger.log(Level.WARN, "Exception while sleeping" + se.toString());
}
}
}
}
logger.info("Tracing enabled - Stackdriver exporter initialized.");
}
private static void initJaeger() {
String jaegerAddr = System.getenv("JAEGER_SERVICE_ADDR");
if (jaegerAddr != null && !jaegerAddr.isEmpty()) {
String jaegerUrl = String.format("http://%s/api/traces", jaegerAddr);
// Register Jaeger Tracing.
JaegerTraceExporter.createAndRegister(
JaegerExporterConfiguration.builder()
.setThriftEndpoint(jaegerUrl)
.setServiceName("adservice")
.build());
logger.info("Jaeger initialization complete.");
} else {
logger.info("Jaeger initialization disabled.");
}
}
/** Main launches the server from the command line. */
public static void main(String[] args) throws IOException, InterruptedException {
// Registers all RPC views.
/*
[TODO:rghetia] replace registerAllViews with registerAllGrpcViews. registerAllGrpcViews
registers new views using new measures however current grpc version records against old
measures. When new version of grpc (0.19) is release revert back to new. After reverting back
to new the new measure will not provide any tags (like method). This will create some
discrepencies when compared grpc measurements in Go services.
*/
RpcViews.registerAllViews();
new Thread(
() -> {
initStats();
initTracing();
})
.start();
// Register Jaeger
initJaeger();
// Start the RPC server. You shouldn't see any output from gRPC before this.
logger.info("AdService starting.");
final AdService service = AdService.getInstance();
service.start();
service.blockUntilShutdown();
}
}
| 12,309 | 34.889213 | 99 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/Main.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import columbus.CsiHeader;
import columbus.StrTable;
import columbus.java.asg.Factory;
import columbus.java.asg.algorithms.AlgorithmPreorder;
import columbus.logger.LoggerHandler;
import columbus.revision.Revision;
import com.lexicalscope.jewel.cli.ArgumentValidationException;
import com.lexicalscope.jewel.cli.CliFactory;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.tools.javac.parser.JavadocTokenizer;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.Context;
public class Main {
private static final LoggerHandler logger = new LoggerHandler(Main.class, OptionParser.getLoggerPropertyFile());
// max memory usage in MB
private static long maxTotalMem = 0;
private static long maxUsedMem = 0;
public static void updateMemoryUsage() {
final int mb = 1024 * 1024;
Runtime runtime = Runtime.getRuntime();
long total = runtime.totalMemory() / mb;
long free = runtime.freeMemory() / mb;
long used = total - free;
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.Main.usedMemory", used, total);
}
if (total > maxTotalMem) {
maxTotalMem = total;
}
if (used > maxUsedMem) {
maxUsedMem = used;
}
}
public static void main(String[] args) {
logger.info("info.jan.Main.janInfo", Revision.getBranchNumber(), Revision.getRevision());
Timer phaseTimer, totalTimer;
ArrayList<Timer> timers = new ArrayList<>();
totalTimer = new Timer(logger.formatMessage("info.jan.Main.statTotalTime"));
totalTimer.start();
timers.add(totalTimer);
String baseDir = null;
try {
baseDir = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
} catch (URISyntaxException e) {
logger.error("error.jan.Main.determineLocationOfExecutableEx", e);
System.exit(1);
}
Main.updateMemoryUsage();
OptionParser.setConfigFileDir(baseDir);
processArguments(args);
List<File> fileNames = FileCollector.collectFiles(OptionParser.getInputs());
Factory fact = new Factory(new StrTable());
fact.turnFilterOff();
if (OptionParser.getAnalyzedSourceList() != null) {
FileCollector.writeSourceFileList(fileNames, OptionParser.getAnalyzedSourceList());
}
int inputsBeforeHardFiltering = fileNames.size();
boolean fillFactory = true;
if (fileNames.isEmpty()) { // if there is no input -> create empty jsi
fillFactory = false;
logger.warn("error.jan.Main.inputMustBeGiven");
}
if (OptionParser.hardFilter != null) {
Filter.filterList(fileNames, OptionParser.hardFilter);
}
if (fileNames.isEmpty()) { // if there is no input after filtering -> create empty jsi
fillFactory = false;
if (inputsBeforeHardFiltering > 0) {
logger.warn("warn.jan.Main.allInputFiltered");
}
}
Main.updateMemoryUsage();
if (fillFactory) {
// JAVAC Build
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statJDKCompileTime"));
timers.add(phaseTimer);
phaseTimer.start();
List<CompilationUnitTree> trees = null;
JDKTreeMaker jdkTreeMaker = null;
try {
jdkTreeMaker = new JDKTreeMaker();
trees = jdkTreeMaker.build(fileNames, OptionParser.getJavacOptions());
} catch (Exception e) {
logger.error("error.jan.Main.JDKTreeMakerEx", e);
System.exit(1);
}
phaseTimer.stop();
Main.updateMemoryUsage();
// JAN Build
logger.info("info.jan.Main.rebuildTrees");
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statTreeRebuildingTime"));
timers.add(phaseTimer);
phaseTimer.start();
SymbolMaps symMaps = new SymbolMaps();
TreeBuilder builder = new TreeBuilder(fact, symMaps, jdkTreeMaker.getContext());
FileProcessor fprocessor = new FileProcessor();
TreeSet<Integer> resultSet = new TreeSet<>();
for (CompilationUnitTree t : trees) {
try {
builder.visit((JCCompilationUnit) t);
//Set the LLOC value on type declaration and method declaration nodes.
resultSet = fprocessor.processFile(t.getSourceFile().getName());
builder.setLLOCToSubTree(resultSet);
} catch (Exception e) {
logger.error("error.jan.Main.TreeBuilderEx", e);
System.exit(1);
}
}
phaseTimer.stop();
Main.updateMemoryUsage();
// Build comments
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statCommentBuilding"));
timers.add(phaseTimer);
phaseTimer.start();
if (OptionParser.isKeepComments()) {
logger.info("info.jan.Main.buildComments");
CommentBuilder commentBuilder = new CommentBuilder(fact, JavadocTokenizer.commentMap);
try {
commentBuilder.build();
} catch (Exception e) {
logger.error("error.jan.Main.commentBuilderEx", e);
System.exit(1);
}
}
phaseTimer.stop();
Main.updateMemoryUsage();
// Build external classes
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statExternalClassBuildingTime"));
timers.add(phaseTimer);
phaseTimer.start();
int nodesBeforeExternalClasses = fact.size();
logger.info("info.jan.Main.createExtClasses");
try {
ExternalClassBuilder extClassBuilder = new ExternalClassBuilder(fact, builder, symMaps,
jdkTreeMaker.getContext());
extClassBuilder.build();
} catch (Exception e) {
logger.error("error.jan.Main.extClassBuildEx", e);
System.exit(1);
}
phaseTimer.stop();
Main.updateMemoryUsage();
// release
builder = null;
// Set crossedges
logger.info("info.jan.Main.setCrossEdges");
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statCrossedgeSettingTime"));
timers.add(phaseTimer);
phaseTimer.start();
int nodesAfterExternalClasses = fact.size();
try {
CrossEdges crossEdges = new CrossEdges(fact, symMaps, jdkTreeMaker.getContext());
crossEdges.setCrossEdges();
} catch (Exception e) {
logger.error("error.jan.Main.crossEdgeEx", e);
System.exit(1);
}
phaseTimer.stop();
Main.updateMemoryUsage();
// Build types
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statTypeBuildingTime"));
timers.add(phaseTimer);
phaseTimer.start();
logger.info("info.jan.Main.buildTypes");
try {
TypeBuilder typeBuilder = new TypeBuilder(fact, symMaps);
typeBuilder.build();
} catch (Exception e) {
logger.error("error.jan.Main.typeBuilderEx", e);
System.exit(1);
}
phaseTimer.stop();
Main.updateMemoryUsage();
// release
symMaps = null;
// Check ASG
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statASGCheckingTime"));
timers.add(phaseTimer);
phaseTimer.start();
if (OptionParser.isNeedCheck()) {
logger.info("info.jan.Main.CheckAsg");
check(fact, jdkTreeMaker.getContext());
}
phaseTimer.stop();
Main.updateMemoryUsage();
// release
jdkTreeMaker = null;
trees = null;
// Create filter
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statFilterGeneratingTime"));
timers.add(phaseTimer);
phaseTimer.start();
if (OptionParser.getCommonJsi() != null) { // create filter only if normal jsi is required
logger.info("info.jan.Main.filter");
Filter filter = new Filter(fact, nodesBeforeExternalClasses, nodesAfterExternalClasses);
try {
fact.turnFilterOn();
filter.run();
fact.turnFilterOff();
} catch (Exception e) {
logger.error("error.jan.Main.filterEx", e);
System.exit(1);
}
}
phaseTimer.stop();
Main.updateMemoryUsage();
}
CsiHeader header = new CsiHeader();
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("linux")) {
header.add("platform", "linux");
} else if (os.contains("windows")) {
header.add("platform", "windows");
} else {
header.add("platform", os);
}
// Create one jsi output file
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statCommonJsiSavingTime"));
timers.add(phaseTimer);
phaseTimer.start();
if (OptionParser.getCommonJsi() != null) {
logger.info("info.jan.Main.saveJsi");
ClassSaver.saveToJsi(fact, OptionParser.getCommonJsi(), header);
}
phaseTimer.stop();
// Create one jml output file
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statCommonJmlSavingTime"));
timers.add(phaseTimer);
phaseTimer.start();
if (OptionParser.getCommonXml() != null) {
logger.info("info.jan.Main.saveJml");
if (OptionParser.isMinXml())
ClassSaver.saveMinXml(fact, OptionParser.getCommonXml());
else
ClassSaver.saveToXml(fact, OptionParser.getCommonXml());
}
phaseTimer.stop();
// Create one jsi for each input source files
phaseTimer = new Timer(logger.formatMessage("info.jan.Main.statSmallJsiSavingTime"));
timers.add(phaseTimer);
phaseTimer.start();
if (OptionParser.getOutputDir() != null || OptionParser.wrappedMode) {
logger.info("info.jan.Main.saveJsiByClasses");
ClassSaver.saveClasses(fact, OptionParser.getOutputDir(), OptionParser.getExtraJsiDir(), header);
}
phaseTimer.stop();
totalTimer.stop();
Main.updateMemoryUsage();
logger.info("info.jan.Main.cpuTimes");
for (Timer t : timers) {
logger.infoMsg(" " + t.getInfo() + ": {}", (t.getTotalCpuTime() / 1000.0));
}
logger.info("info.jan.Main.userTimes");
for (Timer t : timers) {
logger.infoMsg(" " + t.getInfo() + ": {}", (t.getTotalUserTime() / 1000.0));
}
logger.info("info.jan.Main.memoryStatistics");
logger.info("info.jan.Main.maxTotalMemory", maxTotalMem);
logger.info("info.jan.Main.maxUsedMemory", maxUsedMem);
logger.info("info.jan.Main.otherStatistics");
logger.info("info.jan.Main.analyzedFiles", fileNames.size());
logger.info("info.jan.Main.numOfWarnings", logger.getWarnMessages());
logger.info("info.jan.Main.numOfErrors", logger.getErrorMessages());
String statisticFileName = OptionParser.getStatisticFile();
if (statisticFileName != null) {
saveStatistics(statisticFileName, timers, args, fileNames);
}
}
private static void processArguments(String[] args) {
JANCmdLine cmd = null;
args = OptionParser.preProcessArgs(args);
if (args.length == 0) {
logger.error("error.jan.Main.cliFactError", CliFactory.createCli(JANCmdLine.class).getHelpMessage());
System.exit(1);
}
try {
cmd = CliFactory.parseArguments(JANCmdLine.class, args);
} catch (ArgumentValidationException e) {
logger.error("error.jan.Main.cannotParseArgs", e);
System.exit(1);
}
if (cmd.isVersion()) {
System.exit(0);
}
try {
OptionParser.processCmdLine(cmd);
} catch (Exception e) {
logger.error("error.jan.Main.cannotProcessCmdArgs", e);
System.exit(1);
}
}
private static void check(Factory fact, Context context) {
Checker checker = new Checker(fact, context);
AlgorithmPreorder algPre = new AlgorithmPreorder();
algPre.run(fact, checker);
}
private static void saveStatistics(String fileName, ArrayList<Timer> timers, String[] args, List<File> fileNames) {
final String delimiter = ";";
File file = new File(fileName);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
boolean writer_header = !file.exists();
int i, size = timers.size();
Timer timer;
// header
if (writer_header) {
timer = timers.get(0);
writer.write(timer.getInfo() + "(total cpu)" + delimiter + "Memory usage(MB)" + delimiter
+ timer.getInfo() + "(user)");
writer.write(delimiter);
for (i = 1; i < size; i++) {
timer = timers.get(i);
writer.write(timer.getInfo() + "(total cpu)" + delimiter + timer.getInfo() + "(user)");
writer.write(delimiter);
}
writer.write("Number of sources" + delimiter + "Number of errors" + delimiter + "Number of warnings"
+ delimiter + "args");
writer.newLine();
}
// data
timer = timers.get(0);
writer.write((timer.getTotalCpuTime() / 1000.0) + delimiter + maxUsedMem + delimiter
+ (timer.getTotalUserTime() / 1000.0));
writer.write(delimiter);
for (i = 1; i < size; i++) {
timer = timers.get(i);
writer.write((timer.getTotalCpuTime() / 1000.0) + delimiter + (timer.getTotalUserTime() / 1000.0));
writer.write(delimiter);
}
writer.write(fileNames.size() + delimiter);
writer.write(logger.getErrorMessages() + delimiter);
writer.write(logger.getWarnMessages() + delimiter);
for (String str : args) {
writer.write("\"" + str + "\" ");
}
writer.newLine();
} catch (IOException e) {
logger.error("error.jan.Main.savingStatisticsEx", e);
}
}
}
| 13,404 | 30.690307 | 116 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/SymbolMaps.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.lang.model.type.TypeKind;
import columbus.logger.LoggerHandler;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
public class SymbolMaps {
private static final LoggerHandler logger = new LoggerHandler(SymbolMaps.class,
OptionParser.getLoggerPropertyFile());
// declarations
private Map<Symbol, Integer> methodDeclarationMap = new LinkedHashMap<>();
private Map<Symbol, Integer> packageMap = new LinkedHashMap<>();
private Map<String, Integer> packageNameMap = new LinkedHashMap<>();
private Map<Symbol, Integer> externalTypeDeclarationMap = new LinkedHashMap<>();
private Map<Symbol, Integer> innerTypeDeclarationMap = new LinkedHashMap<>();
private Map<Symbol, Integer> variableDeclarationMap = new LinkedHashMap<>();
//Java 9: maps for modules
private Map<Symbol, Integer> moduleMap = new LinkedHashMap<>();
private Map<String, Integer> moduleNameMap = new LinkedHashMap<>();
private Map<Integer, HashSet<Integer>> packagesOfModulesMap = new LinkedHashMap<>();
// types
private Map<Type, List<Integer>> usedTypesMap = new LinkedHashMap<>();
private Map<Type, List<Integer>> methodTypeMap = new LinkedHashMap<>();
private Map<Type, List<Integer>> funcExprTargetMap = new LinkedHashMap<>();
private Map<Type, Integer> typeParameterMap = new LinkedHashMap<>();
private Map<Type, Integer> moduleTypeMap = new LinkedHashMap<>();
// references
private Map<Integer, Symbol> idMap = new LinkedHashMap<>();
private Map<Integer, Symbol> methodInvMap = new LinkedHashMap<>();
private Map<Integer, Symbol> newClassConstructorMap = new LinkedHashMap<>();
//Java 8: member reference map
private Map<Integer, Symbol> memberReferenceMap = new LinkedHashMap<>();
private Set<Symbol> symbolsToFullBuild = new LinkedHashSet<>();
private Set<Symbol> visitedParents = new LinkedHashSet<>();
private Set<Symbol> memberSet = new LinkedHashSet<>();
private Set<Symbol> retTypeSet = new LinkedHashSet<>();
private Set<Symbol> varTypeSet = new LinkedHashSet<>();
private Set<Symbol> classAndInterfaceUsageSet = new LinkedHashSet<>();
private Map<MethodSymbol, Integer> enumFunctionMap = new LinkedHashMap<>();
public Map<Type, List<Integer>> getUsedTypesMap() {
return usedTypesMap;
}
public Map<Type, List<Integer>> getMethodTypeMap() {
return methodTypeMap;
}
public Map<Type, List<Integer>> getFuncExprTargetMap() {
return funcExprTargetMap;
}
public Map<Symbol, Integer> getVariableDeclarationMap() {
return variableDeclarationMap;
}
public Map<Integer, Symbol> getNewClassConstructorMap() {
return newClassConstructorMap;
}
public Map<Symbol, Integer> getExternalTypeDeclarationMap() {
return externalTypeDeclarationMap;
}
public Map<Symbol, Integer> getPackageMap() {
return packageMap;
}
public Map<String, Integer> getPackageNameMap() {
return packageNameMap;
}
public Map<Symbol, Integer> getModuleMap() {
return moduleMap;
}
public Map<String, Integer> getModuleNameMap() {
return moduleNameMap;
}
public Map<Integer, HashSet<Integer>> getPackagesOfModulesMap() {
return packagesOfModulesMap;
}
public Map<Integer, Symbol> getMemberReferenceMap() {
return memberReferenceMap;
}
public Map<Type, Integer> getModuleTypeMap() {
return moduleTypeMap;
}
public Integer findPackage(PackageSymbol sym) {
Integer id = packageMap.get(sym);
if (id == null) {
id = packageNameMap.get(sym.toString());
}
return id;
}
public Integer findModule(String s) {
return moduleNameMap.get(s);
}
public Set<Symbol> getExternalClassAndInterfaceSet() {
Set<Symbol> set = new LinkedHashSet<Symbol>(classAndInterfaceUsageSet);
set.addAll(memberSet);
set.addAll(retTypeSet);
set.addAll(varTypeSet);
set.removeAll(innerTypeDeclarationMap.keySet());
Iterator<Symbol> it = set.iterator();
while (it.hasNext()) {
if (it.next().type.getKind() == TypeKind.ERROR) {
it.remove();
}
}
return set;
}
public Map<Type, Integer> getTypeParameterMap() {
return typeParameterMap;
}
public Map<Symbol, Integer> getMethodDeclarationMap() {
return methodDeclarationMap;
}
public Map<Integer, Symbol> getMethodInvMap() {
return methodInvMap;
}
public Map<Symbol, Integer> getInnerTypeDeclarationMap() {
return innerTypeDeclarationMap;
}
public void addNodeType(Type type, int id) {
addNodeType(type, id, usedTypesMap);
}
public void addMethodType(Type type, int id) {
addNodeType(type, id, methodTypeMap);
}
public void addFuncExprTarget(Type type, int id) {
addNodeType(type, id, funcExprTargetMap);
}
private void addNodeType(Type type, int id, Map<Type, List<Integer>> typeMap) {
List<Integer> ids = null;
ids = TypeBuilder.getValueFromTypeMap(type, typeMap);
if (ids == null) {
ids = new LinkedList<>();
typeMap.put(type, ids);
}
ids.add(Integer.valueOf(id));
}
public Iterator<Entry<Integer, Symbol>> getIdMapIterator() {
return idMap.entrySet().iterator();
}
public void addToIdMap(Integer id, Symbol sym) {
if (sym instanceof ClassSymbol || sym instanceof VarSymbol || sym instanceof MethodSymbol
|| sym instanceof PackageSymbol) {
idMap.put(id, sym);
} else {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.SymbolMaps.notExpectedIdType", sym.getKind());
}
}
}
public void addVarType(Symbol sym) {
if (sym != null && sym.type != null && !sym.type.isPrimitive() && sym.type.getKind() != TypeKind.ARRAY) {
if ((sym.type.tsym instanceof ClassSymbol) && !sym.type.tsym.isAnonymous()) {
varTypeSet.add(sym.type.tsym);
}
}
}
public void addMethodReturnType(Symbol sym) {
if (sym != null && sym.type != null && !sym.type.isPrimitive()) {
if ((sym instanceof ClassSymbol) && !sym.isAnonymous()) {
retTypeSet.add(sym);
}
}
}
public void addClassAndInterfaceUsageSet(Symbol sym) {
if (sym != null) {
if (sym instanceof ClassSymbol) {
classAndInterfaceUsageSet.add(sym);
}
}
}
public void addMemberToTypeSymbolSet(Symbol sym) {
if (sym != null) {
if ((sym instanceof ClassSymbol) && !sym.isAnonymous()) {
memberSet.add(sym);
}
}
}
public void addClassAndInterfaceToFullBuildSet(Symbol sym) {
if (sym != null) {
if (sym instanceof ClassSymbol) {
symbolsToFullBuild.add(sym);
}
}
}
public void addAllParentToFullBuild(ClassSymbol sym) {
if (sym != null && visitedParents.add(sym)) {
Type parent = sym.getSuperclass();
if (parent.tsym != null) {
addClassAndInterfaceToFullBuildSet(parent.tsym);
addAllParentToFullBuild((ClassSymbol) parent.tsym);
}
for (Type interf : sym.getInterfaces()) {
addClassAndInterfaceToFullBuildSet(interf.tsym);
addAllParentToFullBuild((ClassSymbol) interf.tsym);
}
}
}
public void clearInnerClassesFromFullBuildSet() {
symbolsToFullBuild.removeAll(innerTypeDeclarationMap.keySet());
}
public boolean containsSymbolsToFullBuild(Symbol sym) {
return symbolsToFullBuild.contains(sym);
}
public Map<MethodSymbol, Integer> getEnumFunctions() {
return enumFunctionMap;
}
enum EdgeType {
METHOD, NEWCLASS, ID, MEMBER_REF
}
enum TypeKinds {
EXPR_TYPE, METHOD_TYPE, FUNC_EXPR_TARGET
}
}
| 8,392 | 27.259259 | 107 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/OptionParser.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import columbus.logger.LoggerHandler;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.main.Option;
public class OptionParser {
private static final String loggerPropertyFile = "JanMessages";
private static final String logbackXmlFile = "logback.xml";
private static final LoggerHandler logger = new LoggerHandler(OptionParser.class, loggerPropertyFile);
private static final String delim = "|";
private static final String equal = "=";
private static boolean buildAllExternal = false;
private static boolean buildExtFromSource = true;
// build super classes and interfaces for method override edges
public static boolean buildAllParentForOverrides = true;
private static boolean keepComments = true;
private static List<String> inputs = new ArrayList<>();
private static String outputDir = null;
private static String columbusResultDir = null;
private static String extraJsiDir = null;
private static boolean xmlToEveryClass = false;
private static String commonJsi = null;
private static String commonXml = null;
public static boolean minXml = false;
private static String generatedJsiListFile = null;
private static String analyzedSourceList = null;
private static boolean needCheck = true;
private static List<String> javacOptions = new ArrayList<>();
private static String configFile;
private static String statisticFile = null;
public static String encoding;
public static boolean wrappedMode = false;
public static boolean dirAnalyze = false;
public static String hardFilter = null;
private static String usedClasspathList = null;
private static int messageLevel;
private static String componentId;
private static String changesetID;
public static String getLoggerPropertyFile() {
return loggerPropertyFile;
}
public static String getLogbackXml() {
return logbackXmlFile;
}
public static String getConfigFile() {
return configFile;
}
public static String getStatisticFile() {
return statisticFile;
}
public static void setConfigFileDir(String configFile) {
OptionParser.configFile = configFile;
}
public static boolean isBuildAllExternal() {
return buildAllExternal;
}
public static boolean isBuildExtFromSource() {
return buildExtFromSource;
}
public static boolean isKeepComments() {
return keepComments;
}
public static List<String> getInputs() {
return inputs;
}
public static String getOutputDir() {
return outputDir;
}
public static String getColumbusResultDir() {
return columbusResultDir;
}
public static String getExtraJsiDir() {
return extraJsiDir;
}
public static boolean isXmlToEveryClass() {
return xmlToEveryClass;
}
public static String getCommonJsi() {
return commonJsi;
}
public static String getCommonXml() {
return commonXml;
}
public static boolean isMinXml() {
return minXml;
}
public static String getGeneratedJsiListFile() {
return generatedJsiListFile;
}
public static String getAnalyzedSourceList() {
return analyzedSourceList;
}
public static boolean isNeedCheck() {
return needCheck;
}
public static List<String> getJavacOptions() {
return javacOptions;
}
public static String getComponentId() {
return componentId;
}
public static String getChangesetID() {
return changesetID;
}
private static void parseJavacOptions(String str) {
String[] array = str.split("[|]");
List<String> list = new ArrayList<>();
for (String s : array) {
if (!s.equals("")) {
list.add(s);
}
}
javacOptions.addAll(list);
}
public static void processCmdLine(JANCmdLine cmd) {
String config = null;
if (cmd.isConfigfile()) {
String configFileFromCmd = cmd.getConfigfile();
// search as an absolute path
if ((new File(configFileFromCmd).exists())) {
config = configFileFromCmd;
} else { // search near the JAN.jar with the given name
config = OptionParser.configFile.replace("\\", "/") + "/" + configFileFromCmd;
}
} else { // search near the JAN.jar with a default name
config = OptionParser.configFile.replace("\\", "/") + "/" + "toolchain.ini";
}
try {
if (new File(config).exists()) {
parseOptionsFromConfig(config);
} else {
config = null;
logger.warn("warn.jan.OptionParser.noConfigFile");
}
} catch (Exception e) {
logger.error("error.jan.OptionParser.configParseError", e);
}
if (cmd.isMessagelevel()) {
messageLevel = cmd.getMessagelevel();
}
if (messageLevel < 0 || messageLevel > 6) {
logger.warn("warn.jan.OptionParser.badLogLevel", messageLevel);
messageLevel = 3;
}
logger.info("info.jan.OptionParser.setLogLevel", messageLevel);
LoggerHandler.setMessageLevel(messageLevel);
if (cmd.isJanoptions()) {
parseOptionsFromCmd(cmd.getJanoptions());
}
if (cmd.isConfigfile() && cmd.isJanoptions()) {
logger.warn("warn.jan.OptionParser.overrideValuesFromConfigFile");
}
if (cmd.isInput()) {
inputs = cmd.getInput();
}
if (cmd.isOutputdir()) {
outputDir = cmd.getOutputdir();
}
if (cmd.isJavacargumentfiles()) {
for (String s : cmd.getJavacargumentfiles()) {
if (!s.isEmpty()) {
if (s.charAt(0) == '@')
s = s.substring(1);
try (BufferedReader br = new BufferedReader(new FileReader(new File(s)))) {
processArgFile(br);
} catch (Exception e) {
logger.error("error.jan.OptionParser.cantOpenArgFile", s, e);
}
}
}
}
if (cmd.isExtrajsidir()) {
extraJsiDir = cmd.getExtrajsidir();
}
if (cmd.isOutputjsi()) {
commonJsi = cmd.getOutputjsi();
}
if (cmd.isOutputxml()) {
commonXml = cmd.getOutputxml();
}
minXml = cmd.isMinXml();
if (cmd.isJsilistfile()) {
generatedJsiListFile = cmd.getJsilistfile();
}
if (cmd.isAnalyzedsourcelist()) {
analyzedSourceList = cmd.getAnalyzedsourcelist();
}
if (cmd.isUsedclasspathlist()) {
usedClasspathList = cmd.getUsedclasspathlist();
}
if (cmd.isJavacoptions()) {
parseJavacOptions(cmd.getJavacoptions());
}
wrappedMode = cmd.isWrappedmode();
dirAnalyze = cmd.isDirecotryAnalyzeMode();
if (cmd.isHardfilter()) {
hardFilter = cmd.getHardfilter();
}
if (cmd.isJavacargumentfiles() && cmd.isJavacoptions()) {
logger.warn("warn.jan.OptionParser.overrideValuesFromArgFile");
}
if (cmd.isStatisticfile()) {
statisticFile = cmd.getStatisticfile();
}
if (cmd.isJavacoptions() && cmd.isJavacargumentfiles()) {
logger.warn("warn.jan.OptionParser.overrideValuesFromTheListFile");
}
postProcessJavacOptions(config);
}
private static void postProcessJavacOptions(String config) {
if (config != null && !config.isEmpty()) {
List<String> forcedSingleOpts = ConfigReader.getValues(config, "JAVAC", "FORCE_SINGLE_OPT");
List<String> forcedMultiOpts = ConfigReader.getValues(config, "JAVAC", "FORCE_MULTI_OPT");
addForcedJavacOptions(forcedSingleOpts, forcedMultiOpts, true);
List<String> defaultSingleOpts = ConfigReader.getValues(config, "JAVAC", "DEFAULT_SINGLE_OPT");
List<String> defaultMultiOpts = ConfigReader.getValues(config, "JAVAC", "DEFAULT_MULTI_OPT");
addForcedJavacOptions(defaultSingleOpts, defaultMultiOpts, false);
}
for (int i = 0; i < javacOptions.size(); ++i) {
if (Option.ENCODING.matches(javacOptions.get(i)) && i + 1 < javacOptions.size()) {
OptionParser.encoding = javacOptions.get(i + 1);
logger.info("info.jan.OptionParser.javacOptionFound", javacOptions.get(i), OptionParser.encoding);
}
}
checkJavacOptions();
}
private static void addForcedJavacOptions(List<String> singleOpts, List<String> multiOpts, boolean force) {
for (int i = 0; i < javacOptions.size(); i++) {
String act = javacOptions.get(i);
if (multiOpts.contains(act) && act.startsWith("-")) {
int pos = multiOpts.indexOf(act);
multiOpts.remove(pos);
if (force) {
javacOptions.set(i + 1, multiOpts.get(pos));
}
multiOpts.remove(pos);
}
if (singleOpts.contains(act)) {
singleOpts.remove(act);
}
}
javacOptions.addAll(singleOpts);
javacOptions.addAll(multiOpts);
}
private static void checkJavacOptions() {
List<String> newList = new ArrayList<>();
// collapse multiple cp/classpath options into a single one, if there are more than one
String cp = "";
for (int i = 0; i < javacOptions.size(); i++) {
String o = javacOptions.get(i);
if (o.startsWith("-classpath") || o.startsWith("-cp")) {
if (!cp.isEmpty()) {
cp += File.pathSeparator;
}
cp += javacOptions.get(i + 1);
++i;
} else {
newList.add(o);
}
}
if (cp.isEmpty()) {
cp = ".";
}
newList.add("-cp");
newList.add(cp);
createClasspathListFile(cp);
javacOptions = newList;
newList = new ArrayList<>();
for (int i = 0; i < javacOptions.size(); i++) {
String o = javacOptions.get(i);
if (o.startsWith("-J") && !o.startsWith("-JAN_")) // keep the spec JAN options of javac
continue;
if (o.equals("-version"))
continue;
if (o.equals("-help"))
continue;
if (o.equals("-Xprint"))
continue;
if (o.equals("-Xstdout")) {
i++;
continue;
}
if (o.equals("-target")) {
if (i + 1 < javacOptions.size()) {
String targetValue = javacOptions.get(i + 1);
// these target options have been removed in JDK 8
if ("jsr14".equals(targetValue) || "1.4.1".equals(targetValue) || "1.4.2".equals(targetValue)) {
logger.error("error.jan.OptionParser.removedUndocumentedTargetOption", targetValue);
i++;
continue;
}
}
}
// TODO JDK 9+ doesn't support source/target before 1.6/6
if (i + 1 < javacOptions.size()) {
if ("-source".equals(o)) {
String value = javacOptions.get(i + 1);
Source source = Source.lookup(value);
if (source != null && source.compareTo(Source.MIN) < 0) {
logger.error("error.jan.OptionParser.unsupportedSourceOption", value);
i++;
continue;
}
}
if ("-target".equals(o)) {
String value = javacOptions.get(i + 1);
Target target = Target.lookup(value);
if (target != null && target.compareTo(Target.MIN) < 0) {
logger.error("error.jan.OptionParser.unsupportedTargetOption", value);
i++;
continue;
}
}
}
if (o.startsWith("-g")) {
newList.add("-g");
continue;
}
newList.add(o);
}
javacOptions = newList;
}
private static void createClasspathListFile(String fullCp) {
if (usedClasspathList != null) {
try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(new File(usedClasspathList))))) {
String[] splittedCp = fullCp.split(File.pathSeparator);
StringBuilder pathPrefix = new StringBuilder();
for (String cpFragment : splittedCp) {
pathPrefix.append(cpFragment);
if (new File(pathPrefix.toString()).exists()) {
pw.println(pathPrefix);
pathPrefix = new StringBuilder();
} else {
// because ; is a valid character in directory names in windows
pathPrefix.append(File.pathSeparator);
}
}
} catch (IOException e) {
logger.error("error.jan.OptionParser.cpListWriteError", e);
}
}
}
private static void processArgFile(BufferedReader br) throws IOException {
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " ");
boolean storeDestDir = false;
while (st.hasMoreTokens()) {
String token = st.nextToken();
boolean pars = false;
if (token.startsWith("\"")) {
pars = true;
while (!token.endsWith("\"")) {
String next = st.nextToken();
token += " " + next;
}
}
if (pars) {
token = token.substring(1, token.length() - 1);
}
if (storeDestDir) {
storeDestDir = false;
outputDir = token;
}
if (token.equals("-d")) {
storeDestDir = true;
}
if (token.endsWith(".java")) {
File f = new File(token);
if (f.getAbsoluteFile().isFile() || token.contains("*")) {
inputs.add(token);
continue;
}
}
javacOptions.add(token);
}
}
}
private static void parseOptionsFromConfig(String fileName) throws Exception {
Map<String, String> options = ConfigReader.readSection(fileName, "JAN");
String optionsLikeCmd = "";
if (options != null) {
if (options.size() > 0) {
for (Entry<String, String> e : options.entrySet()) {
optionsLikeCmd += "|" + e.getKey() + "=" + e.getValue();
}
}
}
if (!optionsLikeCmd.isEmpty()) {
parseOptionsFromCmd(optionsLikeCmd);
}
}
private static void parseOptionsFromCmd(String str) {
Field f;
StringTokenizer t = new StringTokenizer(str, delim);
logger.info("info.jan.OptionParser.janOptions");
while (t.hasMoreTokens()) {
String token = t.nextToken();
try {
String[] parts = token.split(equal);
logger.info("info.jan.OptionParser.janOption", token);
f = OptionParser.class.getDeclaredField(parts[0]);
if (f.getType() == Integer.TYPE) {
f.setInt(null, Integer.parseInt(parts[1]));
} else if (f.getType() == Boolean.TYPE) {
try {
f.setBoolean(null, Integer.parseInt(parts[1]) == 1 ? true : false);
} catch (NumberFormatException e) {
if (parts[1].equals("true")) {
f.setBoolean(null, true);
} else if (parts[1].equals("false")) {
f.setBoolean(null, false);
} else {
throw e;
}
}
} else if (f.getType().equals(String.class)) {
if (parts.length == 1) {
f.set(null, null);
} else {
f.set(null, parts[1]);
}
} else {
throw new Exception(logger.formatMessage("ex.jan.OptionParser.unexpectedOptionType"));
}
} catch (Exception e) {
logger.error("error.jan.OptionParser.errorParsingJANArgs", token, e);
System.exit(1);
}
}
}
public static String changePath(String params, String workingDir) {
String result = "";
if (workingDir.isEmpty())
return params;
String[] array = params.split("[|]");
for (int i = 0; i < array.length; i++) {
String s = array[i];
if (!s.equals("")) {
result += "|" + s;
if (s.equals("-cp") || s.equals("-classpath") || s.equals("-sourcepath") || s.equals("-bootclasspath")
|| s.equals("-processorpath")) {
String path = array[++i];
String delim = ":";
if (path.contains(";")) {
delim = ";";
} else if (path.contains(":")) {
delim = ":";
}
String[] paths = path.split("[;:]");
String tmp = "";
for (String p : paths) {
if (p.equals(".")) {
tmp += delim + workingDir;
} else {
tmp += delim + workingDir + p;
}
}
result += "|" + tmp.substring(1);
}
}
}
return result;
}
public static String[] preProcessArgs(String[] args) {
List<String> ret = new ArrayList<>();
String janOptsWithDelims = "";
String javacOptsWithDelims = "";
String workingDir = "";
// find working directory
try {
for (int i = 0; i < args.length; i++) {
String s = args[i];
if (s.startsWith("--workingDirectory:")) {
workingDir = s.substring(18);
} else if (s.startsWith("-w:")) {
workingDir = s.substring(3);
} else if (s.equals("--workingDirectory") || s.equals("-w")) {
workingDir = args[i + 1];
}
}
} catch (Exception e) {
// Cannot find working directory
workingDir = "";
}
for (int i = 0; i < args.length; i++) {
String s = args[i];
if (s.isEmpty()) {
continue;
}
if (s.startsWith("--javacoptions") || s.startsWith("-j")) {
if (s.startsWith("-j:|")) {
StringTokenizer st = new StringTokenizer(s.substring(4));
while (st.hasMoreTokens()) {
javacOptsWithDelims += "|" + st.nextToken();
}
continue;
} else if (s.startsWith("-j:")) {
javacOptsWithDelims += "|" + s.substring(3);
continue;
} else if (s.startsWith("--javacoptions:")) {
javacOptsWithDelims += "|" + s.substring(15);
continue;
} else {
javacOptsWithDelims += "|" + args[++i];
continue;
}
}
if (s.startsWith("--janoptions") || s.startsWith("-a")) {
if (s.startsWith("-a:")) {
janOptsWithDelims += "|" + s.substring(3);
continue;
} else if (s.startsWith("--janoptions:")) {
janOptsWithDelims += "|" + s.substring(13);
continue;
} else {
janOptsWithDelims += "|" + args[++i];
continue;
}
}
ret.add(s);
}
if (javacOptsWithDelims != "") {
ret.add("-j");
javacOptsWithDelims = changePath(javacOptsWithDelims, workingDir);
ret.add(javacOptsWithDelims);
}
if (janOptsWithDelims != "") {
ret.add("-a");
ret.add(janOptsWithDelims);
}
return ret.toArray(new String[ret.size()]);
}
}
| 17,791 | 25.634731 | 108 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/Checker.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Names;
import columbus.java.asg.Common;
import columbus.java.asg.Factory;
import columbus.java.asg.Range;
import columbus.java.asg.base.Base;
import columbus.java.asg.base.Named;
import columbus.java.asg.base.Positioned;
import columbus.java.asg.enums.MethodKind;
import columbus.java.asg.expr.AnnotatedTypeExpression;
import columbus.java.asg.expr.Expression;
import columbus.java.asg.expr.FieldAccess;
import columbus.java.asg.expr.FunctionalExpression;
import columbus.java.asg.expr.Identifier;
import columbus.java.asg.expr.Lambda;
import columbus.java.asg.expr.MemberReference;
import columbus.java.asg.expr.MethodInvocation;
import columbus.java.asg.expr.NewClass;
import columbus.java.asg.expr.TypeIntersectionExpression;
import columbus.java.asg.module.ModuleDirective;
import columbus.java.asg.statm.Jump;
import columbus.java.asg.struc.CompilationUnit;
import columbus.java.asg.struc.Import;
import columbus.java.asg.struc.MethodDeclaration;
import columbus.java.asg.struc.ModuleDeclaration;
import columbus.java.asg.struc.NormalMethod;
import columbus.java.asg.struc.PackageDeclaration;
import columbus.java.asg.struc.TypeDeclaration;
import columbus.java.asg.struc.TypeParameter;
import columbus.java.asg.type.ArrayType;
import columbus.java.asg.type.ClassType;
import columbus.java.asg.type.MethodType;
import columbus.java.asg.type.PackageType;
import columbus.java.asg.type.ParameterizedType;
import columbus.java.asg.type.ScopedType;
import columbus.java.asg.type.TypeVariable;
import columbus.java.asg.type.UnionType;
import columbus.java.asg.type.WildcardType;
import columbus.java.asg.visitors.VisitorAbstractNodes;
import columbus.logger.LoggerHandler;
public class Checker extends VisitorAbstractNodes {
private static final LoggerHandler logger = new LoggerHandler(Checker.class, OptionParser.getLoggerPropertyFile());
private Factory fact;
private boolean checkDuplicatedTypeDeclarations = true;
private Map<Integer, Set<Integer>> typeDeclarations = new HashMap<>();
private Names names;
public Checker(Factory fact, Context context) {
this.fact = fact;
this.names = Names.instance(context);
}
@Override
public void finishVisit() {
if (checkDuplicatedTypeDeclarations) {
for (Entry<Integer, Set<Integer>> e : typeDeclarations.entrySet()) {
Set<Integer> tds = e.getValue();
if (tds.size() > 1) {
logger.warn("warn.jan.Checker.duplicatedTypeDecl", fact.getStringTable().get(e.getKey()),
tds.size());
for (int td : tds) {
logger.warn("warn.jan.Checker.printTypeDecl", getNodeInfo(fact.getRef(td)));
}
}
}
}
}
private static String getNodeInfo(Base node) {
String str = "id" + node.getId() + " kind: " + node.getNodeKind();
if (node instanceof Positioned) {
Range p = ((Positioned) node).getPosition();
str += ": " + p.getPath() + ": " + p.getLine() + ": " + p.getCol() + ": ";
}
if (node instanceof Named) {
str += ": " + ((Named) node).getName();
}
return str;
}
@Override
public void visit(Base node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getParent() == null && node != fact.getRoot() && !Common.getIsType(node) && !Common.getIsComment(node)
&& !(node instanceof columbus.java.asg.struc.Module) && !(node instanceof CompilationUnit)) {
logger.warn("warn.jan.Checker.missingParent", getNodeInfo(node));
}
}
@Override
public void visit(Named node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getNameKey() == 0) {
if (!Common.getIsAnonymousClass(node) && !(Common.getIsMethodDeclaration(node)
&& ((NormalMethod) node).getMethodKind() == MethodKind.mekGeneratedAnonymousClassConstructor)) {
logger.warn("warn.jan.Checker.missingName", getNodeInfo(node));
}
}
}
@Override
public void visit(columbus.java.asg.struc.Package node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getQualifiedNameKey() == 0) {
logger.warn("warn.jan.Checker.missingQualifiedName", getNodeInfo(node));
}
}
@Override
public void visit(PackageDeclaration node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getRefersTo() == null) {
logger.warn("warn.jan.Checker.missingRefersTo", getNodeInfo(node));
}
}
@Override
public void visit(TypeDeclaration node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
Range range = node.getPosition();
if (range.getPathKey() != 0) {
if (node.getIsInCompilationUnit() == null) {
logger.warn("warn.jan.Checker.missingIsCompUnit", getNodeInfo(node));
}
}
if (checkDuplicatedTypeDeclarations) {
int binaryNameKey = node.getBinaryNameKey();
Set<Integer> tds = typeDeclarations.get(binaryNameKey);
if (tds == null) {
tds = new HashSet<Integer>();
typeDeclarations.put(binaryNameKey, tds);
}
tds.add(node.getId());
}
}
@Override
public void visit(TypeParameter node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getBoundsIsEmpty()) {
logger.warn("warn.jan.Checker.missingBound", getNodeInfo(node));
}
}
@Override
public void visit(Positioned node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
Base parent = node.getParent();
if (parent != null) {
if (Common.getIsPositioned(parent)) {
if (!node.getIsCompilerGenerated() && ((Positioned) parent).getIsCompilerGenerated()) {
if (Common.getIsNewClass(parent) && Common.getIsEnumConstant(parent.getParent())) {
// A("asdf) -> = new <enum name>("asdf")
// here the StringLiteral is not compiler generated but the NewClass is
} else {
logger.warn("warn.jan.Checker.nonCompGenNodeHasCompGenParent", getNodeInfo(node),
getNodeInfo(parent));
}
}
}
}
if (node.getIsCompilerGenerated() || node.getPosition().getPathKey() == 0)
return;
Range range = node.getPosition();
if (range.getLine() == 0 || range.getCol() == 0 || range.getEndLine() == 0 || range.getEndCol() == 0
|| range.getWideLine() == 0 || range.getWideCol() == 0 || range.getWideEndLine() == 0
|| range.getWideEndCol() == 0) {
logger.warn("warn.jan.Checker.missingPos", getNodeInfo(node));
}
}
@Override
public void visit(NewClass node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getConstructor() == null) {
logger.warn("warn.jan.Checker.missingConstructor", getNodeInfo(node));
}
}
@Override
public void visit(Jump node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getTarget() == null) {
logger.warn("warn.jan.Checker.missingTarget", getNodeInfo(node));
}
}
@Override
public void visit(Identifier node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
boolean dontWarn = true;
if (node.getRefersTo() == null) {
if ((node.getParent().getParent() instanceof Import)) {
dontWarn = true;
}
}
if (node.getName().toString().equals(names.length.toString())
|| node.getName().toString().equals(names.clone.toString())) {
dontWarn = true;
}
if (!dontWarn) {
logger.warn("warn.jan.Checker.missingRefersTo", getNodeInfo(node));
}
}
@Override
public void visit(MethodInvocation node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getInvokes() == null) {
Expression op = node.getOperand();
if (Common.getIsFieldAccess(op)) {
FieldAccess fa = (FieldAccess) op;
if (!((Identifier) fa.getRightOperand()).getName().equals(names.clone.toString())) {
logger.warn("warn.jan.Checker.missingInvokes", getNodeInfo(node));
}
}
}
}
@Override
public void visit(Expression node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getType() == null) {
// import with *
if (!(node instanceof FieldAccess && node.getParent() instanceof Import)
&& !(node instanceof Identifier && node.getParent().getParent() instanceof Import)
&& !(isParentAModuleDirective(node.getParent()))) {
logger.warn("warn.jan.Checker.missingType", getNodeInfo(node));
}
}
}
private boolean isParentAModuleDirective(Base node) {
if (node == null) {
return false;
} else if (node instanceof ModuleDirective || node instanceof ModuleDeclaration) {
return true;
}
return isParentAModuleDirective(node.getParent());
}
@Override
public void visit(MethodDeclaration node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getMethodType() == null) {
logger.warn("warn.jan.Checker.missingType", getNodeInfo(node));
}
}
// Types with edges
@Override
public void visit(WildcardType node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getBound() == null) {
logger.warn("warn.jan.Checker.missingBound", getNodeInfo(node));
}
}
@Override
public void visit(ScopedType node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getOwner() == null) {
logger.warn("warn.jan.Checker.missingOwner", getNodeInfo(node));
}
}
@Override
public void visit(ClassType node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getRefersTo() == null) {
logger.warn("warn.jan.Checker.missingRefersTo", getNodeInfo(node));
}
}
@Override
public void visit(ParameterizedType node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getRawType() == null) {
logger.warn("warn.jan.Checker.missingRawType", getNodeInfo(node));
}
if (node.getArgumentTypesIsEmpty()) {
logger.warn("warn.jan.Checker.missingArgType", getNodeInfo(node));
}
}
@Override
public void visit(PackageType node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getRefersTo() == null) {
logger.warn("warn.jan.Checker.missingRefersTo", getNodeInfo(node));
}
}
@Override
public void visit(ArrayType node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getSize() == 0) {
logger.warn("warn.jan.Checker.sizeIsZero", getNodeInfo(node));
}
if (node.getComponentType() == null) {
logger.warn("warn.jan.Checker.missingCompType", getNodeInfo(node));
}
}
@Override
public void visit(TypeVariable node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getRefersTo() == null) {
logger.warn("warn.jan.Checker.missingRefersTo", getNodeInfo(node));
}
}
@Override
public void visit(MethodType node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getReturnType() == null) {
logger.warn("warn.jan.Checker.missingRetType", getNodeInfo(node));
}
}
@Override
public void visit(UnionType node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getAlternativesIsEmpty()) {
logger.warn("warn.jan.Checker.missingAlternative", getNodeInfo(node));
}
}
@Override
public void visit(AnnotatedTypeExpression node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getAnnotationsIsEmpty()) {
logger.warn("warn.jan.Checker.missingAnnotation", getNodeInfo(node));
}
if (node.getUnderlyingType() == null) {
logger.warn("warn.jan.Checker.missingUnderlyingType", getNodeInfo(node));
}
}
@Override
public void visit(TypeIntersectionExpression node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getBoundsIsEmpty()) {
logger.warn("warn.jan.Checker.missingBound", getNodeInfo(node));
}
}
@Override
public void visit(FunctionalExpression node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getTarget() == null) {
logger.warn("warn.jan.Checker.missingTarget", getNodeInfo(node));
}
}
@Override
public void visit(Lambda node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getBody() == null) {
logger.warn("warn.jan.Checker.missingBody", getNodeInfo(node));
}
}
@Override
public void visit(MemberReference node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
if (node.getName().isEmpty()) {
logger.warn("warn.jan.Checker.missingName", getNodeInfo(node));
}
if (node.getQualifierExpression() == null) {
logger.warn("warn.jan.Checker.missingQualifierExpr", getNodeInfo(node));
}
if (node.getReferredMethod() == null) {
logger.warn("warn.jan.Checker.missingReferredMethod", getNodeInfo(node));
}
}
}
| 13,337 | 30.832936 | 116 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/JANFlags.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.util.EnumSet;
import columbus.java.asg.Common;
import columbus.java.asg.EdgeIterator;
import columbus.java.asg.enums.AccessibilityKind;
import columbus.java.asg.enums.MethodKind;
import columbus.java.asg.struc.MethodDeclaration;
import columbus.java.asg.struc.NamedDeclaration;
import columbus.java.asg.struc.NormalMethod;
import columbus.java.asg.struc.Parameter;
import columbus.java.asg.struc.TypeDeclaration;
import columbus.java.asg.struc.Variable;
import columbus.logger.LoggerHandler;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Flags.Flag;
public abstract class JANFlags {
private static final LoggerHandler logger = new LoggerHandler(JANFlags.class, OptionParser.getLoggerPropertyFile());
public static boolean hasStaticFlag(long flags) {
if ((flags & Flags.STATIC) != 0)
return true;
return false;
}
public static boolean hasEnumFlag(long flags) {
if ((flags & Flags.ENUM) != 0)
return true;
return false;
}
public static boolean hasAnnotationFlag(long flags) {
if ((flags & Flags.ANNOTATION) != 0)
return true;
return false;
}
public static boolean hasAnonconstrFlag(long flags) {
if ((flags & Flags.ANONCONSTR) != 0)
return true;
return false;
}
public static boolean hasGeneratedConstrFlag(long flags) {
if ((flags & Flags.GENERATEDCONSTR) != 0)
return true;
return false;
}
public static void setModifiers(long flags, NamedDeclaration memberNode) {
EnumSet<Flag> flagSet = Flags.asFlagSet(flags, false);
for (Flag f : flagSet) {
switch (f) {
case ABSTRACT:
if (Common.getIsMethodDeclaration(memberNode)) {
((MethodDeclaration) memberNode).setIsAbstract(true);
} else if (Common.getIsTypeDeclaration(memberNode)) {
((TypeDeclaration) memberNode).setIsAbstract(true);
} else {
// syntax error
}
break;
case FINAL:
memberNode.setIsFinal(true);
break;
case STATIC:
memberNode.setIsStatic(true);
break;
case STRICTFP:
if (Common.getIsMethodDeclaration(memberNode)) {
((MethodDeclaration) memberNode).setIsStrictfp(true);
} else if (Common.getIsTypeDeclaration(memberNode)) {
((TypeDeclaration) memberNode).setIsStrictfp(true);
} else {
// syntax error
}
break;
case PRIVATE:
memberNode.setAccessibility(AccessibilityKind.ackPrivate);
break;
case PROTECTED:
memberNode.setAccessibility(AccessibilityKind.ackProtected);
break;
case PUBLIC:
memberNode.setAccessibility(AccessibilityKind.ackPublic);
break;
case TRANSIENT:
if (Common.getIsVariableDeclaration(memberNode)) {
((Variable) memberNode).setIsTransient(true);
} else {
// syntax error
}
break;
case VOLATILE:
if (Common.getIsVariableDeclaration(memberNode)) {
((Variable) memberNode).setIsVolatile(true);
} else {
// syntax error
}
break;
case VARARGS:
if (Common.getIsParameter(memberNode)) {
((Parameter) memberNode).setIsVarargs(true);
} else if (Common.getIsNormalMethod(memberNode)) {
// MethodSymbol's flag can be VARARGS
NormalMethod method = (NormalMethod) memberNode;
if (!method.getParametersIsEmpty()) {
Parameter lastParam = null;
for (EdgeIterator<Parameter> pit = method.getParametersIterator(); pit.hasNext();) {
lastParam = pit.next();
}
lastParam.setIsVarargs(true);
}
} else {
// syntax error
}
break;
case GENERATEDCONSTR:
if (Common.getIsNormalMethod(memberNode)) {
((NormalMethod) memberNode).setMethodKind(MethodKind.mekGeneratedDefaultConstructor);
} else {
// syntax error
}
break;
case SYNCHRONIZED:
if (Common.getIsNormalMethod(memberNode)) {
((NormalMethod) memberNode).setIsSynchronized(true);
} else {
// syntax error
}
break;
case NATIVE:
if (Common.getIsNormalMethod(memberNode)) {
((NormalMethod) memberNode).setIsNative(true);
} else {
// syntax error
}
break;
case ENUM:
case PARAMETER:
case INTERFACE:
case ANNOTATION:
case HASINIT:
case DEPRECATED:
// dont used here
break;
case ANONCONSTR:
// handled later
break;
case ACYCLIC:
case ACYCLIC_ANN:
case EFFECTIVELY_FINAL:
case BRIDGE:
case CLASS_SEEN:
case PROPRIETARY:
// dont needed
break;
//java 1.8 new flags
case DEFAULT:
if (Common.getIsNormalMethod(memberNode)) {
((NormalMethod) memberNode).setIsDefault(true);
}
break;
case MANDATED:
case AUXILIARY:
case NOT_IN_PROFILE:
case BAD_OVERRIDE:
case SIGNATURE_POLYMORPHIC:
case THROWS:
case LAMBDA_METHOD:
case TYPE_TRANSLATED:
break;
//java 9 support (new flags)
case MODULE:
case AUTOMATIC_MODULE:
case SYSTEM_MODULE:
case DEPRECATED_ANNOTATION:
case DEPRECATED_REMOVAL:
case HAS_RESOURCE:
break;
default:
logger.warn("warn.jan.JANFlags.modifierIsntHandled", f);
break;
}
}
if (flagSet.contains(Flag.ANONCONSTR)) {
((NormalMethod) memberNode).setMethodKind(MethodKind.mekGeneratedAnonymousClassConstructor);
}
if (flagSet.contains(Flag.DEFAULT) && Common.getIsMethodDeclaration(memberNode)) {
// Default methods read from class file both have default and abstract modifiers.
// But according to JLS 9.4 it mustn't happen:
// It is a compile-time error if a method is declared with more than one of the modifiers
// abstract, default, or static.
((MethodDeclaration) memberNode).setIsAbstract(false);
}
}
}
| 6,312 | 27.183036 | 117 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/TreeBuilder.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.lang.model.type.TypeKind;
import javax.tools.JavaFileObject;
import columbus.java.asg.Common;
import columbus.java.asg.EdgeIterator;
import columbus.java.asg.Factory;
import columbus.java.asg.JavaException;
import columbus.java.asg.Range;
import columbus.java.asg.algorithms.AlgorithmPreorder;
import columbus.java.asg.base.Base;
import columbus.java.asg.base.Named;
import columbus.java.asg.base.Positioned;
import columbus.java.asg.enums.AssignmentOperatorKind;
import columbus.java.asg.enums.InfixOperatorKind;
import columbus.java.asg.enums.LambdaBodyKind;
import columbus.java.asg.enums.LambdaParameterKind;
import columbus.java.asg.enums.MemberReferenceKind;
import columbus.java.asg.enums.MemberReferenceModeKind;
import columbus.java.asg.enums.MemberReferenceOverloadKind;
import columbus.java.asg.enums.MethodKind;
import columbus.java.asg.enums.ModuleKind;
import columbus.java.asg.enums.NodeKind;
import columbus.java.asg.enums.PolyExpressionKind;
import columbus.java.asg.enums.PostfixOperatorKind;
import columbus.java.asg.enums.PrefixOperatorKind;
import columbus.java.asg.enums.PrimitiveTypeKind;
import columbus.java.asg.enums.TypeBoundKind;
import columbus.java.asg.expr.AnnotatedTypeExpression;
import columbus.java.asg.expr.Annotation;
import columbus.java.asg.expr.ArrayAccess;
import columbus.java.asg.expr.ArrayTypeExpression;
import columbus.java.asg.expr.Assignment;
import columbus.java.asg.expr.BooleanLiteral;
import columbus.java.asg.expr.CharacterLiteral;
import columbus.java.asg.expr.ClassLiteral;
import columbus.java.asg.expr.Conditional;
import columbus.java.asg.expr.DoubleLiteral;
import columbus.java.asg.expr.Erroneous;
import columbus.java.asg.expr.ErroneousTypeExpression;
import columbus.java.asg.expr.FieldAccess;
import columbus.java.asg.expr.FloatLiteral;
import columbus.java.asg.expr.Identifier;
import columbus.java.asg.expr.InfixExpression;
import columbus.java.asg.expr.InstanceOf;
import columbus.java.asg.expr.IntegerLiteral;
import columbus.java.asg.expr.Lambda;
import columbus.java.asg.expr.LongLiteral;
import columbus.java.asg.expr.MarkerAnnotation;
import columbus.java.asg.expr.MemberReference;
import columbus.java.asg.expr.MethodInvocation;
import columbus.java.asg.expr.NewArray;
import columbus.java.asg.expr.NewClass;
import columbus.java.asg.expr.NormalAnnotation;
import columbus.java.asg.expr.NullLiteral;
import columbus.java.asg.expr.ParenthesizedExpression;
import columbus.java.asg.expr.PolyExpression;
import columbus.java.asg.expr.PostfixExpression;
import columbus.java.asg.expr.PrefixExpression;
import columbus.java.asg.expr.PrimitiveTypeExpression;
import columbus.java.asg.expr.QualifiedTypeExpression;
import columbus.java.asg.expr.SimpleTypeExpression;
import columbus.java.asg.expr.SingleElementAnnotation;
import columbus.java.asg.expr.StringLiteral;
import columbus.java.asg.expr.Super;
import columbus.java.asg.expr.This;
import columbus.java.asg.expr.TypeApplyExpression;
import columbus.java.asg.expr.TypeCast;
import columbus.java.asg.expr.TypeExpression;
import columbus.java.asg.expr.TypeIntersectionExpression;
import columbus.java.asg.expr.TypeUnionExpression;
import columbus.java.asg.expr.Unary;
import columbus.java.asg.expr.WildcardExpression;
import columbus.java.asg.module.Exports;
import columbus.java.asg.module.Opens;
import columbus.java.asg.module.Provides;
import columbus.java.asg.module.Requires;
import columbus.java.asg.module.Uses;
import columbus.java.asg.statm.Assert;
import columbus.java.asg.statm.BasicFor;
import columbus.java.asg.statm.Block;
import columbus.java.asg.statm.Break;
import columbus.java.asg.statm.Case;
import columbus.java.asg.statm.Continue;
import columbus.java.asg.statm.Default;
import columbus.java.asg.statm.Do;
import columbus.java.asg.statm.Empty;
import columbus.java.asg.statm.EnhancedFor;
import columbus.java.asg.statm.ExpressionStatement;
import columbus.java.asg.statm.For;
import columbus.java.asg.statm.Handler;
import columbus.java.asg.statm.If;
import columbus.java.asg.statm.Jump;
import columbus.java.asg.statm.LabeledStatement;
import columbus.java.asg.statm.Return;
import columbus.java.asg.statm.Switch;
import columbus.java.asg.statm.SwitchLabel;
import columbus.java.asg.statm.Synchronized;
import columbus.java.asg.statm.Throw;
import columbus.java.asg.statm.Try;
import columbus.java.asg.statm.While;
import columbus.java.asg.struc.AnnotationType;
import columbus.java.asg.struc.AnnotationTypeElement;
import columbus.java.asg.struc.AnonymousClass;
import columbus.java.asg.struc.Class;
import columbus.java.asg.struc.ClassGeneric;
import columbus.java.asg.struc.CompilationUnit;
import columbus.java.asg.struc.Enum;
import columbus.java.asg.struc.GenericDeclaration;
import columbus.java.asg.struc.Import;
import columbus.java.asg.struc.InitializerBlock;
import columbus.java.asg.struc.InstanceInitializerBlock;
import columbus.java.asg.struc.Interface;
import columbus.java.asg.struc.InterfaceGeneric;
import columbus.java.asg.struc.Method;
import columbus.java.asg.struc.MethodDeclaration;
import columbus.java.asg.struc.MethodGeneric;
import columbus.java.asg.struc.Module;
import columbus.java.asg.struc.ModuleDeclaration;
import columbus.java.asg.struc.NamedDeclaration;
import columbus.java.asg.struc.NormalMethod;
import columbus.java.asg.struc.Package;
import columbus.java.asg.struc.PackageDeclaration;
import columbus.java.asg.struc.Parameter;
import columbus.java.asg.struc.StaticInitializerBlock;
import columbus.java.asg.struc.TypeDeclaration;
import columbus.java.asg.struc.TypeParameter;
import columbus.java.asg.struc.Variable;
import columbus.java.asg.struc.VariableDeclaration;
import columbus.java.asg.type.ModuleType;
import columbus.java.asg.visitors.VisitorAbstractNodes;
import columbus.logger.LoggerHandler;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.ModuleSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.comp.DuplicatedHack;
import com.sun.tools.javac.parser.Tokens.TokenKind;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotatedType;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCArrayAccess;
import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree;
import com.sun.tools.javac.tree.JCTree.JCAssert;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCAssignOp;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCBreak;
import com.sun.tools.javac.tree.JCTree.JCCase;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import com.sun.tools.javac.tree.JCTree.JCContinue;
import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop;
import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop;
import com.sun.tools.javac.tree.JCTree.JCErroneous;
import com.sun.tools.javac.tree.JCTree.JCExports;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCForLoop;
import com.sun.tools.javac.tree.JCTree.JCFunctionalExpression;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCIf;
import com.sun.tools.javac.tree.JCTree.JCImport;
import com.sun.tools.javac.tree.JCTree.JCInstanceOf;
import com.sun.tools.javac.tree.JCTree.JCLabeledStatement;
import com.sun.tools.javac.tree.JCTree.JCLambda;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCMemberReference;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCModuleDecl;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCOpens;
import com.sun.tools.javac.tree.JCTree.JCPackageDecl;
import com.sun.tools.javac.tree.JCTree.JCParens;
import com.sun.tools.javac.tree.JCTree.JCPolyExpression;
import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
import com.sun.tools.javac.tree.JCTree.JCProvides;
import com.sun.tools.javac.tree.JCTree.JCRequires;
import com.sun.tools.javac.tree.JCTree.JCReturn;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCSwitch;
import com.sun.tools.javac.tree.JCTree.JCSynchronized;
import com.sun.tools.javac.tree.JCTree.JCThrow;
import com.sun.tools.javac.tree.JCTree.JCTry;
import com.sun.tools.javac.tree.JCTree.JCTypeApply;
import com.sun.tools.javac.tree.JCTree.JCTypeCast;
import com.sun.tools.javac.tree.JCTree.JCTypeIntersection;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCTypeUnion;
import com.sun.tools.javac.tree.JCTree.JCUnary;
import com.sun.tools.javac.tree.JCTree.JCUses;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.JCTree.JCWhileLoop;
import com.sun.tools.javac.tree.JCTree.JCWildcard;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Position;
import com.sun.tools.javac.util.Position.LineMap;
public class TreeBuilder {
private static final LoggerHandler logger = new LoggerHandler(TreeBuilder.class,
OptionParser.getLoggerPropertyFile());
private Names names;
private Symtab symtab;
private Factory fact;
private SymbolMaps symMaps;
private Package rootNode;
private Package unnamedPackage = null;
private PackageSymbol unnamedPackageSym = null;
private Module unnamedModule = null;
private Set<Integer> defaultPackageChilds = new HashSet<>();
private JCCompilationUnit actualJCCU;
private CompilationUnit actualColumbusCU;
private Package actualColumbusPackage;
private int actualColumbusCuPathKey;
private LineMap lineMap;
private int actualModuleId;
// flag variables, must reset them if an Exception occurred
private JCBlock lastBlockNode;
private VarDeclType varDeclType = VarDeclType.NONE;
private BlockType blockType = BlockType.NORMAL;
private MethodType methodType = MethodType.NORMAL;
private JCTree generatedTreeRoot = null;
private boolean isAnonymusClass = false;
private Name duplicatedTypeDeclarationName = null;
private boolean inImport = false;
private JCExpression innerAnonymusClassSuperClass;
public TreeBuilder(Factory fact, SymbolMaps symMaps, Context context) {
this.names = Names.instance(context);
this.symtab = Symtab.instance(context);
this.fact = fact;
this.symMaps = symMaps;
rootNode = fact.getRoot();
}
public void visit(JCCompilationUnit jcCU) {
actualJCCU = jcCU;
JavaFileObject sourcefile = jcCU.sourcefile;
lineMap = jcCU.lineMap;
if (logger.isInfoEnabled()) {
logger.info("info.jan.TreeBuilder.sourceFile", sourcefile.getName());
}
CompilationUnit cuNode = (CompilationUnit) fact.createNode(NodeKind.ndkCompilationUnit);
cuNode.setFileEncoding(OptionParser.encoding);
actualColumbusCU = cuNode;
//Declare the pkgNode. We refer it later but we'd not create it if the current comp.unit is a module-info file.
Package pkgNode = null;
actualModuleId = createModule(jcCU.modle);
Module moduleNode = (Module) fact.getRef(actualModuleId);
if (jcCU.getModuleDecl() == null) {
//Create the module, when the compilation unit is not a module-info file.
PackageSymbol pkgSym = jcCU.packge;
int actualPackageId = createAndAddPackages(pkgSym);
pkgNode = (Package) fact.getRef(actualPackageId);
actualColumbusPackage = pkgNode;
pkgNode.addCompilationUnits(cuNode);
//Handle packages for modules. If the module already has the package we want to add, we won't do it.
Map<Integer, HashSet<Integer>> packagesOfModulesMap = symMaps.getPackagesOfModulesMap();
HashSet<Integer> packageSet = packagesOfModulesMap.get(actualModuleId);
if (packageSet == null) {
//The set is null, so we didn't meet with this module before.
HashSet<Integer> ps = new HashSet<>();
ps.add(actualPackageId);
packagesOfModulesMap.put(actualModuleId, ps);
moduleNode.addPackages(actualPackageId);
pkgNode.addIsInModule(moduleNode);
} else {
//If the set doesn't contain the package id, we add it and add the package to the module as well. Otherwise, we do nothing.
if (!packageSet.contains(actualPackageId)) {
packageSet.add(actualPackageId);
moduleNode.addPackages(actualPackageId);
pkgNode.addIsInModule(moduleNode);
}
}
} else if (pkgNode == null) {
//Add module-info files to the unnamed package.
createUnnamedPackage();
unnamedPackage.addCompilationUnits(cuNode);
}
cuNode.setIsInModule(actualModuleId);
// set position
int endline = 1, endcol = 1;
int wideEndPos = jcCU.getEndPosition(actualJCCU.endPositions);
if (wideEndPos != Position.NOPOS) {
endline = lineMap.getLineNumber(wideEndPos);
endcol = lineMap.getColumnNumber(wideEndPos);
}
Range range = new Range(fact.getStringTable(), jcCU.sourcefile.getName(), 1, 1, endline, endcol, 1, 1, endline, endcol);
cuNode.setPosition(range);
actualColumbusCuPathKey = actualColumbusCU.getPosition().getPathKey();
for (JCTree t : jcCU.defs) {
Base node = fact.getRef(visit(t));
duplicatedTypeDeclarationName = null;
if (Common.getIsTypeDeclaration(node)) {
cuNode.addTypeDeclarations((TypeDeclaration) node);
//The pkgNode is null when the current comp.unit is a module-info file.
if (pkgNode != null) {
pkgNode.addMembers((TypeDeclaration) node);
}
} else if (Common.getIsEmpty(node)) {
cuNode.addOthers((Empty) node);
} else if (Common.getIsImport(node)) {
cuNode.addImports((Import) node);
} else if (Common.getIsErroneous(node)) {
cuNode.addOthers((Erroneous) node);
} else if (Common.getIsPackageDeclaration(node)) {
cuNode.setPackageDeclaration((PackageDeclaration) node);
} else if (Common.getIsModuleDeclaration(node)) {
cuNode.setModuleDeclaration((ModuleDeclaration) node);
} else {
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.notHandledPackageMember",
node.getNodeKind()));
}
}
Main.updateMemoryUsage();
// release some no more necessary "big" fields
jcCU.endPositions = null;
jcCU.lineMap = null;
}
private int visit(Symbol pkg, JCExpression pid) {
int ret = 0;
Identifier identifierNode = (Identifier) fact.createNode(NodeKind.ndkIdentifier);
identifierNode.setName(pkg.name.toString());
setPositionAndGenerated(pid, identifierNode.getId());
ret = identifierNode.getId();
symMaps.addToIdMap(ret, pkg);
symMaps.addNodeType(pkg.type, identifierNode.getId());
// "asdf.asdf"
if (pkg.owner.owner != null) {
FieldAccess fieldAccessNode = (FieldAccess) fact.createNode(NodeKind.ndkFieldAccess);
setPositionAndGenerated(pid, fieldAccessNode.getId());
ret = fieldAccessNode.getId();
fieldAccessNode.setLeftOperand(visit(pkg.owner, ((JCFieldAccess) pid).selected));
fieldAccessNode.setRightOperand(identifierNode);
symMaps.addNodeType(pkg.owner.type, fieldAccessNode.getId());
}
return ret;
}
public int createAndAddPackages(PackageSymbol pkgSym) {
int ret = 0;
if (pkgSym != null) {
if (pkgSym.isUnnamed()) {
ret = createUnnamedPackage();
if (unnamedPackageSym == null) {
unnamedPackageSym = pkgSym;
symMaps.getPackageMap().put(pkgSym, ret);
}
} else {
ret = createPackageHierarchy(pkgSym);
addToDefaultPackage(ret);
}
} else {
ret = createUnnamedPackage();
}
return ret;
}
private int createUnnamedPackage() {
if (unnamedPackage != null)
return unnamedPackage.getId();
Package pkg = (Package) fact.createNode(NodeKind.ndkPackage);
pkg.setName("unnamed package");
pkg.setQualifiedName("unnamed package");
rootNode.addMembers(pkg);
unnamedPackage = pkg;
return pkg.getId();
}
private void addToDefaultPackage(int actualPkgId) {
Package p = (Package) fact.getRef(actualPkgId);
while (p.getParent() != null && p.getParent() != rootNode) {
p = (Package) p.getParent();
}
if (!defaultPackageChilds.contains(p.getId())) {
defaultPackageChilds.add(p.getId());
rootNode.addMembers(p);
}
}
private int createPackageHierarchy(PackageSymbol sym) {
int pkgId = 0;
Integer key = symMaps.getPackageMap().get(sym);
if (key != null) {
pkgId = key;
} else {
String fullName = sym.type.toString();
if (fullName.isEmpty())
// throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.emptyPkgName", sym));
return createUnnamedPackage();
key = symMaps.getPackageNameMap().get(fullName);
if (key != null) {
pkgId = key;
} else {
Package packageNode = (Package) fact.createNode(NodeKind.ndkPackage);
packageNode.setName(sym.name.toString());
packageNode.setQualifiedName(fullName);
pkgId = packageNode.getId();
symMaps.getPackageMap().put(sym, pkgId);
symMaps.getPackageNameMap().put(fullName, pkgId);
if (sym.owner != null && !sym.owner.name.isEmpty()) {
PackageSymbol owner = (PackageSymbol) sym.owner;
Package parentPkg = (Package) fact.getRef(createPackageHierarchy(owner));
parentPkg.addMembers(packageNode);
}
}
}
return pkgId;
}
private int createModule(ModuleSymbol moduleSym) {
int moduleId = 0;
if (moduleSym.isUnnamed()) {
if (unnamedModule == null) {
unnamedModule = (Module) fact.createNode(NodeKind.ndkModule);
unnamedModule.setName("unnamed module");
symMaps.getModuleMap().put(moduleSym, unnamedModule.getId());
symMaps.getModuleNameMap().put("unnamed module", unnamedModule.getId());
}
moduleId = unnamedModule.getId();
} else {
//Handle named module.
Integer id = symMaps.getModuleMap().get(moduleSym);
if (id != null) {
moduleId = id;
} else {
Module mod = (Module) fact.createNode(NodeKind.ndkModule);
String fullname = moduleSym.name.toString();
mod.setName(fullname);
moduleId = mod.getId();
symMaps.getModuleMap().put(moduleSym, moduleId);
symMaps.getModuleNameMap().put(fullname, moduleId);
}
}
return moduleId;
}
private int visit(JCTree jcTree) {
int ret = 0;
if (jcTree == null) {
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.visitJCTreeGetANullNode"));
}
try {
if (jcTree instanceof JCStatement) {
ret = visit((JCStatement) jcTree);
} else if (jcTree instanceof JCExpression) {
ret = visit((JCExpression) jcTree);
} else {
switch (jcTree.getKind()) {
// "TypeBoundKind is not part of a public API"
// case COMPILATION_UNIT:
// it has an own visit method
case MODIFIERS:
// we don't build a node from it
case CATCH: {
JCCatch jcCatch = (JCCatch) jcTree;
Handler handlerNode = (Handler) fact.createNode(NodeKind.ndkHandler);
ret = handlerNode.getId();
varDeclType = VarDeclType.PARAMETER;
handlerNode.setParameter(visit(jcCatch.param));
handlerNode.setBlock(visit(jcCatch.body));
break;
}
case TYPE_PARAMETER: {
JCTypeParameter jcTypeParameter = (JCTypeParameter) jcTree;
TypeParameter typeParameterNode = (TypeParameter) fact.createNode(NodeKind.ndkTypeParameter);
ret = typeParameterNode.getId();
typeParameterNode.setName(jcTypeParameter.name.toString());
if (jcTypeParameter.bounds.isEmpty()) {
if (jcTypeParameter.type != null && ((Type.TypeVar) jcTypeParameter.type).bound != null) {
typeParameterNode
.addBounds(createSimpleTypeExpression(((Type.TypeVar) jcTypeParameter.type).bound));
}
} else {
for (JCExpression b : jcTypeParameter.bounds) {
typeParameterNode.addBounds(visitTypeExpression(b));
}
}
symMaps.getTypeParameterMap().put(jcTypeParameter.type, typeParameterNode.getId());
break;
}
case IMPORT: {
try {
inImport = true;
JCImport jcImport = (JCImport) jcTree;
Import importNode = (Import) fact.createNode(NodeKind.ndkImport);
ret = importNode.getId();
importNode.setIsStatic(jcImport.staticImport);
importNode.setTarget(visit(jcImport.qualid));
} finally {
inImport = false;
}
break;
}
case METHOD: {
try {
JCMethodDecl jcMethod = (JCMethodDecl) jcTree;
if (generatedTreeRoot == null
&& (JANFlags.hasAnonconstrFlag(jcMethod.mods.flags) || JANFlags
.hasGeneratedConstrFlag(jcMethod.mods.flags))) {
generatedTreeRoot = jcTree;
}
MethodDeclaration methodDecl = null;
if (methodType == MethodType.ANNOTATION_ELEMENT) {
AnnotationTypeElement annotTypeElemNode = (AnnotationTypeElement) fact
.createNode(NodeKind.ndkAnnotationTypeElement);
if (jcMethod.defaultValue != null) {
annotTypeElemNode.setDefaultValue(visit(jcMethod.defaultValue));
}
methodDecl = annotTypeElemNode;
ret = annotTypeElemNode.getId();
} else {
NormalMethod normalMethod = null;
if (!jcMethod.typarams.isEmpty()) {
MethodGeneric methodGenericNode = (MethodGeneric) fact
.createNode(NodeKind.ndkMethodGeneric);
ret = methodGenericNode.getId();
for (JCTypeParameter typaram : jcMethod.typarams) {
methodGenericNode.addTypeParameters(visit(typaram));
}
normalMethod = methodGenericNode;
} else {
Method methodNode = (Method) fact.createNode(NodeKind.ndkMethod);
ret = methodNode.getId();
normalMethod = methodNode;
}
if (jcMethod.body != null) {
normalMethod.setBody(visit(jcMethod.body));
}
for (JCExpression thr : jcMethod.thrown) {
normalMethod.addThrownExceptions(visitTypeExpression(thr));
}
for (JCVariableDecl param : jcMethod.params) {
varDeclType = VarDeclType.PARAMETER;
normalMethod.addParameters(visit(param));
}
methodDecl = normalMethod;
}
setModifiersAndAnnotations(jcMethod.mods, methodDecl);
MethodSymbol sym = jcMethod.sym;
if (sym != null && jcMethod.name == names.init) {
NormalMethod normalMethod = (NormalMethod) methodDecl;
if (normalMethod.getMethodKind() == MethodKind.mekNormal) {
normalMethod.setMethodKind(MethodKind.mekConstructor);
}
if (sym.owner != null) {
methodDecl.setName(sym.owner.name.toString());
} else {
methodDecl.setName(sym.toString());
}
} else {
methodDecl.setName(jcMethod.name.toString());
}
if (duplicatedTypeDeclarationName != null && Common.getIsNormalMethod(methodDecl)
&& ((NormalMethod) methodDecl).getMethodKind() != MethodKind.mekNormal && sym != null
&& sym.owner != null) {
methodDecl.setName(sym.owner.name.toString());
}
if (jcMethod.restype != null) {
methodDecl.setReturnType(visitTypeExpression(jcMethod.restype));
}
if (jcMethod.sym != null) {
symMaps.getMethodDeclarationMap().put(jcMethod.sym, ret);
}
symMaps.addMethodType(jcMethod.type, methodDecl.getId());
} finally {
methodType = MethodType.NORMAL;
}
break;
}
// Java 9 package declaration
case PACKAGE: {
JCPackageDecl jcPackageDecl = (JCPackageDecl) jcTree;
PackageDeclaration pkgDeclNode = (PackageDeclaration) fact.createNode(NodeKind.ndkPackageDeclaration);
ret = pkgDeclNode.getId();
if (jcPackageDecl.pid != null) {
if (jcPackageDecl.packge != null && jcPackageDecl.packge.owner != null) {
pkgDeclNode.setPackageName(visit(jcPackageDecl.packge, jcPackageDecl.pid));
}
pkgDeclNode.setRefersTo(actualColumbusPackage);
setPositionAndGenerated(jcPackageDecl.pid, pkgDeclNode.getId());
}
for (JCAnnotation a : jcPackageDecl.annotations) {
actualColumbusPackage.addAnnotations(visit(a));
}
break;
}
case MODULE: {
JCModuleDecl jcModuleDecl = (JCModuleDecl) jcTree;
ModuleDeclaration moduleDecl = (ModuleDeclaration) fact.createNode(NodeKind.ndkModuleDeclaration);
//Set the module kind.
switch (jcModuleDecl.getModuleType()) {
case OPEN:
moduleDecl.setModuleKind(ModuleKind.mkOpen);
break;
case STRONG:
moduleDecl.setModuleKind(ModuleKind.mkStrong);
break;
}
moduleDecl.setName(visit(jcModuleDecl.qualId));
moduleDecl.setRefersTo(actualModuleId);
jcModuleDecl.directives.forEach(item -> {
moduleDecl.addDirectives(visit(item));
});
if (jcModuleDecl.sym != null) {
int modTypeNodeId = createModuleTypeNode(jcModuleDecl.sym.type);
moduleDecl.setModuleType(modTypeNodeId);
}
ret = moduleDecl.getId();
break;
}
case EXPORTS:
JCExports jcExports = (JCExports) jcTree;
Exports exportsNode = (Exports) fact.createNode(NodeKind.ndkExports);
exportsNode.setPackageName(visit(jcExports.qualid));
//If the moduleNames is null it means the package is exported to everyone, so null is not a problem in this case.
if (jcExports.moduleNames != null) {
jcExports.moduleNames.forEach(item -> exportsNode.addModuleNames(visit(item)));
}
ret = exportsNode.getId();
break;
case OPENS:
JCOpens jcOpens = (JCOpens) jcTree;
Opens opensNode = (Opens) fact.createNode(NodeKind.ndkOpens);
opensNode.setPackageName(visit(jcOpens.qualid));
//If the moduleNames is null it means anyone can open the package, so null is not a problem in this case.
if (jcOpens.moduleNames != null) {
jcOpens.moduleNames.forEach(item -> opensNode.addModuleNames(visit(item)));
}
ret = opensNode.getId();
break;
case PROVIDES:
JCProvides jcProvides = (JCProvides) jcTree;
Provides providesNode = (Provides) fact.createNode(NodeKind.ndkProvides);
providesNode.setServiceName(visit(jcProvides.serviceName));
jcProvides.implNames.forEach(item -> providesNode.addImplementationNames(visit(item)));
ret = providesNode.getId();
break;
case REQUIRES:
JCRequires jcRequires = (JCRequires) jcTree;
Requires requiresNode = (Requires) fact.createNode(NodeKind.ndkRequires);
requiresNode.setIsTransitive(jcRequires.isTransitive);
requiresNode.setIsStatic(jcRequires.isStaticPhase);
requiresNode.setModuleName(visit(jcRequires.moduleName));
ret = requiresNode.getId();
break;
case USES:
JCUses jcUses = (JCUses) jcTree;
Uses usesNode = (Uses) fact.createNode(NodeKind.ndkUses);
usesNode.setServiceName(visit(jcUses.qualid));
ret = usesNode.getId();
break;
default:
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.invalidJCTreeKind",
jcTree.getKind()));
}
if (ret == 0) {
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.visitJCTreeRetIsZero"));
} else {
setPositionAndGenerated(jcTree, ret);
}
}
} finally {
if (generatedTreeRoot != null && generatedTreeRoot == jcTree) {
generatedTreeRoot = null;
}
}
return ret;
}
private int visit(JCStatement jcStatement) {
int ret = 0;
if (jcStatement == null) {
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.visitStatementGetANullNode"));
}
try {
if (generatedTreeRoot == null && lastBlockNode != null && jcStatement.pos == lastBlockNode.pos) {
generatedTreeRoot = jcStatement;
}
if (jcStatement instanceof JCClassDecl) {
try {
JCClassDecl jcClassDecl = (JCClassDecl) jcStatement;
TypeDeclaration typeDeclNode = null;
if (isAnonymusClass) {
typeDeclNode = (TypeDeclaration) fact.createNode(NodeKind.ndkAnonymousClass);
isAnonymusClass = false;
} else {
switch (jcStatement.getKind()) {
case CLASS:
if (jcClassDecl.typarams.isEmpty()) {
typeDeclNode = (Class) fact.createNode(NodeKind.ndkClass);
} else {
typeDeclNode = (ClassGeneric) fact.createNode(NodeKind.ndkClassGeneric);
}
break;
case INTERFACE:
if (jcClassDecl.typarams.isEmpty()) {
typeDeclNode = (Interface) fact.createNode(NodeKind.ndkInterface);
} else {
typeDeclNode = (InterfaceGeneric) fact.createNode(NodeKind.ndkInterfaceGeneric);
}
break;
case ENUM:
typeDeclNode = (Enum) fact.createNode(NodeKind.ndkEnum);
if (jcClassDecl.sym != null) {
List<Symbol> elemList = jcClassDecl.sym.getEnclosedElements();
for (Symbol s : elemList) {
// the same name is not enough
if (s instanceof MethodSymbol
&& (s.toString().equals("values()") || s.toString().equals(
"valueOf(java.lang.String)"))) {
symMaps.getEnumFunctions().put((MethodSymbol) s, typeDeclNode.getId());
}
}
}
break;
case ANNOTATION_TYPE:
// methodType = MethodType.ANNOTATION_ELEMENT;
typeDeclNode = (AnnotationType) fact.createNode(NodeKind.ndkAnnotationType);
break;
default:
throw new JavaException(logger.formatMessage(
"ex.jan.TreeBuilder.statementIsntHandledInVisitJCExpr", jcStatement.getKind()));
}
if (Common.getIsGenericDeclaration(typeDeclNode)) {
GenericDeclaration genericDecl = (GenericDeclaration) typeDeclNode;
for (JCTypeParameter typ : jcClassDecl.typarams) {
genericDecl.addTypeParameters(visit(typ));
}
}
}
ret = typeDeclNode.getId();
if (jcClassDecl.sym != null) {
Name binaryName = null;
if (duplicatedTypeDeclarationName != null) {
String origName = jcClassDecl.sym.flatname.toString();
// only search from the second character, because if the typedeclaration's name is bad, it
// will be replaced with $ character
int endOfTypeDeclName = origName.indexOf(duplicatedTypeDeclarationName.toString())+ duplicatedTypeDeclarationName.length();
String postfix = origName.substring(origName.indexOf("$", endOfTypeDeclName));
binaryName = names.fromString(duplicatedTypeDeclarationName.toString() + postfix);
} else {
Name name = jcClassDecl.sym.flatname;
if (DuplicatedHack.duplicatedTypeDeclarations.containsKey(name)) {
binaryName = DuplicatedHack.duplicatedTypeDeclarations.get(name);
duplicatedTypeDeclarationName = binaryName;
} else {
binaryName = name;
}
}
typeDeclNode.setBinaryName(binaryName.toString());
symMaps.getInnerTypeDeclarationMap().put(jcClassDecl.sym, ret);
//The top level of type declarations in a compilation unit. The program connects it to the module it belongs to.
if (jcClassDecl.sym.owner instanceof PackageSymbol) {
Integer parentModuleId = symMaps.getModuleMap().get(jcClassDecl.sym.packge().modle);
typeDeclNode.setIsInModule(parentModuleId);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TreeBuilder.typeDeclSymIsNull", ret);
}
}
for (JCTree def : jcClassDecl.defs) {
if (def.getKind() == Kind.ERRONEOUS) {
continue;
} else if (def.getKind() == Kind.VARIABLE) {
setVariableType(def);
} else if (def.getKind() == Kind.BLOCK) {
setBlockType(def);
} else if (def.getKind() == Kind.METHOD) {
setMethodType(jcClassDecl);
} else if (def.getKind() == Kind.EMPTY_STATEMENT) {
typeDeclNode.addOthers(visit(def));
continue;
}
typeDeclNode.addMembers(visit(def));
}
if (jcClassDecl.name != null)
typeDeclNode.setName(jcClassDecl.name.toString());
typeDeclNode.setIsInCompilationUnit(actualColumbusCU);
Type.ClassType classType = (Type.ClassType) jcClassDecl.type;
if (jcClassDecl.extending != null) {
if (innerAnonymusClassSuperClass != null) {
try {
typeDeclNode.setSuperClass(visitTypeExpression(innerAnonymusClassSuperClass));
} finally {
innerAnonymusClassSuperClass = null;
}
} else {
typeDeclNode.setSuperClass(visitTypeExpression(jcClassDecl.extending));
}
} else {
// classes where super class is not given in the declarations
// interfaces and annotation don't have default super class
// enums extend java.lang.Enum by default
if (jcClassDecl.type != null && !jcClassDecl.type.isInterface()) {
typeDeclNode.setSuperClass(createSimpleTypeExpression(classType.supertype_field));
}
}
if (jcClassDecl.type != null && JANFlags.hasAnnotationFlag(jcClassDecl.type.tsym.flags_field)) {
for (Type t : classType.interfaces_field) {
typeDeclNode.addSuperInterfaces(createSimpleTypeExpression(t));
}
}
for (JCExpression imp : jcClassDecl.implementing) {
typeDeclNode.addSuperInterfaces(visitTypeExpression(imp));
}
// if we override an external class, we have to build it fully for method override edges
if (OptionParser.buildAllParentForOverrides
&& (jcClassDecl.extending != null || !jcClassDecl.implementing.isEmpty())) {
symMaps.addAllParentToFullBuild(jcClassDecl.sym);
}
setModifiersAndAnnotations(jcClassDecl.mods, typeDeclNode);
} finally {
isAnonymusClass = false;
}
} else {
switch (jcStatement.getKind()) {
case ASSERT: {
JCAssert jcAssert = (JCAssert) jcStatement;
Assert assertNode = (Assert) fact.createNode(NodeKind.ndkAssert);
ret = assertNode.getId();
assertNode.setCondition(visit(jcAssert.cond));
if (jcAssert.detail != null) {
assertNode.setDetail(visit(jcAssert.detail));
}
break;
}
case BLOCK: {
try {
JCBlock jcBlock = (JCBlock) jcStatement;
lastBlockNode = jcBlock;
Block blockNode = (Block) fact.createNode(NodeKind.ndkBlock);
ret = blockNode.getId();
// to handle blocks inside init blocks correctly
BlockType saveBlockType = blockType;
blockType = BlockType.NORMAL;
for (JCStatement s : jcBlock.stats) {
if (s.getKind().equals(Kind.VARIABLE))
setVariableType(s);
blockNode.addStatements(visit(s));
}
blockType = saveBlockType;
InitializerBlock initBlockNode;
if (blockType.equals(BlockType.INSTANCE_INIT)) {
setPositionAndGenerated(jcStatement, ret);
initBlockNode = (InstanceInitializerBlock) fact
.createNode(NodeKind.ndkInstanceInitializerBlock);
ret = initBlockNode.getId();
initBlockNode.setBody(blockNode.getId());
} else if (blockType.equals(BlockType.STATIC_INIT)) {
setPositionAndGenerated(jcStatement, ret);
initBlockNode = (InitializerBlock) fact.createNode(NodeKind.ndkStaticInitializerBlock);
ret = initBlockNode.getId();
initBlockNode.setBody(blockNode.getId());
}
} finally {
blockType = BlockType.NORMAL;
lastBlockNode = null;
}
break;
}
case BREAK: {
JCBreak jcBreak = (JCBreak) jcStatement;
Break breakNode = (Break) fact.createNode(NodeKind.ndkBreak);
ret = breakNode.getId();
Name name = jcBreak.label;
if (name != null) {
breakNode.setLabel(name.toString());
}
break;
}
case CASE: {
JCCase jcCase = (JCCase) jcStatement;
SwitchLabel switchLabelNode;
if (jcCase.pat == null) {
switchLabelNode = (Default) fact.createNode(NodeKind.ndkDefault);
} else {
switchLabelNode = (Case) fact.createNode(NodeKind.ndkCase);
((Case) switchLabelNode).setExpression(visit(jcCase.pat));
}
ret = switchLabelNode.getId();
for (JCStatement stmt : jcCase.stats) {
if (stmt.getKind() == Kind.VARIABLE) {
varDeclType = VarDeclType.VARIABLE;
}
switchLabelNode.addStatements(visit(stmt));
}
break;
}
case CONTINUE: {
JCContinue jcContinue = (JCContinue) jcStatement;
Continue continueNode = (Continue) fact.createNode(NodeKind.ndkContinue);
ret = continueNode.getId();
Name name = jcContinue.label;
if (name != null) {
continueNode.setLabel(name.toString());
}
break;
}
case DO_WHILE_LOOP: {
JCDoWhileLoop jcDoWhileLoop = (JCDoWhileLoop) jcStatement;
Do doNode = (Do) fact.createNode(NodeKind.ndkDo);
ret = doNode.getId();
doNode.setCondition(visit(jcDoWhileLoop.cond));
doNode.setSubstatement(visit(jcDoWhileLoop.body));
break;
}
case ENHANCED_FOR_LOOP: {
JCEnhancedForLoop jcEFor = (JCEnhancedForLoop) jcStatement;
columbus.java.asg.statm.EnhancedFor enhancedForNode = (EnhancedFor) fact
.createNode(NodeKind.ndkEnhancedFor);
ret = enhancedForNode.getId();
varDeclType = VarDeclType.PARAMETER;
enhancedForNode.setParameter(visit(jcEFor.var));
enhancedForNode.setExpression(visit(jcEFor.expr));
enhancedForNode.setSubstatement(visit(jcEFor.body));
break;
}
case EXPRESSION_STATEMENT: {
JCExpressionStatement jcExpressionStatement = (JCExpressionStatement) jcStatement;
ExpressionStatement expressionStatementNode = (ExpressionStatement) fact
.createNode(NodeKind.ndkExpressionStatement);
ret = expressionStatementNode.getId();
expressionStatementNode.setExpression(visit(jcExpressionStatement.expr));
break;
}
case FOR_LOOP: {
JCForLoop jcForLoop = (JCForLoop) jcStatement;
BasicFor basicForNode = (BasicFor) fact.createNode(NodeKind.ndkBasicFor);
ret = basicForNode.getId();
for (JCStatement stmt : jcForLoop.init) {
if (stmt.getKind().equals(Kind.VARIABLE))
varDeclType = VarDeclType.VARIABLE;
basicForNode.addInitializers(visit(stmt));
}
if (jcForLoop.cond != null) {
basicForNode.setCondition(visit(jcForLoop.cond));
}
for (JCExpressionStatement stmt : jcForLoop.step) {
basicForNode.addUpdates(visit(stmt));
}
basicForNode.setSubstatement(visit(jcForLoop.body));
break;
}
case IF: {
JCIf jcIf = (JCIf) jcStatement;
If ifNode = (If) fact.createNode(NodeKind.ndkIf);
ret = ifNode.getId();
ifNode.setCondition(visit(jcIf.cond));
ifNode.setSubstatement(visit(jcIf.thenpart));
if (jcIf.elsepart != null) {
ifNode.setFalseSubstatement(visit(jcIf.elsepart));
}
break;
}
case LABELED_STATEMENT: {
JCLabeledStatement jcLabeledStatement = (JCLabeledStatement) jcStatement;
LabeledStatement labeledStatementNode = (LabeledStatement) fact
.createNode(NodeKind.ndkLabeledStatement);
ret = labeledStatementNode.getId();
labeledStatementNode.setLabel(jcLabeledStatement.label.toString());
labeledStatementNode.setStatement(visit(jcLabeledStatement.body));
break;
}
case RETURN: {
Return returnNode = (Return) fact.createNode(NodeKind.ndkReturn);
JCReturn jcReturn = (JCReturn) jcStatement;
ret = returnNode.getId();
if (jcReturn.expr != null) {
returnNode.setExpression(visit(jcReturn.expr));
}
break;
}
case EMPTY_STATEMENT: {
Empty emptyNode = (Empty) fact.createNode(NodeKind.ndkEmpty);
ret = emptyNode.getId();
break;
}
case SWITCH: {
JCSwitch jcSwitch = (JCSwitch) jcStatement;
Switch switchNode = (Switch) fact.createNode(NodeKind.ndkSwitch);
ret = switchNode.getId();
switchNode.setCondition(visit(jcSwitch.selector));
for (JCCase jcCase : jcSwitch.cases) {
switchNode.addCases(visit(jcCase));
}
break;
}
case SYNCHRONIZED: {
JCSynchronized jcSynchronized = (JCSynchronized) jcStatement;
Synchronized synchronizedNode = (Synchronized) fact.createNode(NodeKind.ndkSynchronized);
ret = synchronizedNode.getId();
synchronizedNode.setLock(visit(jcSynchronized.lock));
synchronizedNode.setBlock(visit(jcSynchronized.body));
break;
}
case THROW: {
JCThrow jcThrow = (JCThrow) jcStatement;
Throw throwNode = (Throw) fact.createNode(NodeKind.ndkThrow);
ret = throwNode.getId();
throwNode.setExpression(visit(jcThrow.expr));
break;
}
case TRY: {
JCTry jcTry = (JCTry) jcStatement;
Try tryNode = (Try) fact.createNode(NodeKind.ndkTry);
ret = tryNode.getId();
for (JCTree resource : jcTry.resources) {
if (resource instanceof JCVariableDecl) {
varDeclType = VarDeclType.VARIABLE;
}
tryNode.addResources(visit(resource));
}
tryNode.setBlock(visit(jcTry.body));
for (JCCatch catcher : jcTry.catchers) {
tryNode.addHandlers(visit(catcher));
}
if (jcTry.finalizer != null) {
tryNode.setFinallyBlock(visit(jcTry.finalizer));
}
break;
}
case VARIABLE: {
try {
JCVariableDecl jcVariableDecl = (JCVariableDecl) jcStatement;
VariableDeclaration varDeclNode = null;
switch (varDeclType) {
case VARIABLE: {
Variable variableNode = (Variable) fact.createNode(NodeKind.ndkVariable);
varDeclNode = variableNode;
if (jcVariableDecl.init != null) {
variableNode.setInitialValue(visit(jcVariableDecl.init));
}
break;
}
case ENUMCONST: {
columbus.java.asg.struc.EnumConstant enumConstantNode = (columbus.java.asg.struc.EnumConstant) fact
.createNode(NodeKind.ndkEnumConstant);
varDeclNode = enumConstantNode;
if (jcVariableDecl.init != null) {
if (jcVariableDecl.init.getKind().equals(Kind.NEW_CLASS)) {
int id = visit(jcVariableDecl.init);
enumConstantNode.setNewClass(id);
NewClass newClass = enumConstantNode.getNewClass();
newClass.getTypeName().setIsCompilerGenerated(true);
AnonymousClass anonClass = newClass.getAnonymousClass();
if (anonClass != null) {
if(anonClass.getSuperClass() != null) {
anonClass.getSuperClass().setIsCompilerGenerated(true);
} else {
logger.debug("debug.jan.TreeBuilder.anonymClassDontHaveSuperClass",newClass.getId());
}
} else {
newClass.setIsCompilerGenerated(true);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TreeBuilder.unexpectedEnumConstInitType",
jcVariableDecl.init.getKind());
}
}
}
break;
}
case PARAMETER: {
Parameter parameterNode = (Parameter) fact.createNode(NodeKind.ndkParameter);
varDeclNode = parameterNode;
break;
}
case NONE:
default:
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.varTypeIsNotGiven"));
}
if (jcVariableDecl.vartype != null) {
int id;
if (jcVariableDecl.vartype.pos < 0) {
id = createSimpleTypeExpression(jcVariableDecl.type);
((SimpleTypeExpression) fact.getRef(id)).setName("var");
} else {
id = visitTypeExpression(jcVariableDecl.vartype);
}
varDeclNode.setType(id);
if (varDeclNode.getNodeKind() == NodeKind.ndkEnumConstant) {
varDeclNode.getType().setIsCompilerGenerated(true);
}
}
varDeclNode.setName(jcVariableDecl.name.toString());
setModifiersAndAnnotations(jcVariableDecl.mods, varDeclNode);
ret = varDeclNode.getId();
if (jcVariableDecl.sym != null) {
symMaps.getVariableDeclarationMap().put(jcVariableDecl.sym, ret);
symMaps.addVarType(jcVariableDecl.sym);
}
} finally {
varDeclType = VarDeclType.NONE;
}
break;
}
case WHILE_LOOP: {
JCWhileLoop jcWhileLoop = (JCWhileLoop) jcStatement;
While whileNode = (While) fact.createNode(NodeKind.ndkWhile);
ret = whileNode.getId();
whileNode.setCondition(visit(jcWhileLoop.cond));
whileNode.setSubstatement(visit(jcWhileLoop.body));
break;
}
default:
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.jcStatementIsNotHandled",
jcStatement.getKind()));
}
}
if (ret == 0) {
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.atTheEndOfVisitStmtRetIsZero"));
} else {
setPositionAndGenerated(jcStatement, ret);
}
} finally {
if (generatedTreeRoot != null && generatedTreeRoot == jcStatement) {
generatedTreeRoot = null;
}
}
return ret;
}
// Expression
private int visit(JCExpression jcExpr) {
int ret = 0;
if (jcExpr == null) {
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.visitExprGetANullNode"));
}
if (jcExpr instanceof JCAssignOp) {
JCAssignOp jcAssignOp = (JCAssignOp) jcExpr;
Assignment assignmentNode = (Assignment) fact.createNode(NodeKind.ndkAssignment);
assignmentNode.setLeftOperand(visit(jcAssignOp.lhs));
assignmentNode.setRightOperand(visit(jcAssignOp.rhs));
switch (jcExpr.getKind()) {
case MULTIPLY_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askTimesAssign);
break;
case DIVIDE_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askDivideAssign);
break;
case REMAINDER_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askRemainderAssign);
break;
case PLUS_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askPlusAssign);
break;
case MINUS_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askMinusAssign);
break;
case LEFT_SHIFT_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askLeftShiftAssign);
break;
case RIGHT_SHIFT_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askSignedRightShiftAssign);
break;
case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askUnsignedRightShiftAssign);
break;
case AND_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askAndAssign);
break;
case XOR_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askXorAssign);
break;
case OR_ASSIGNMENT:
assignmentNode.setOperator(AssignmentOperatorKind.askOrAssign);
break;
default:
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.invalidOpKind", jcExpr.getKind()));
}
ret = assignmentNode.getId();
} else if (jcExpr instanceof JCBinary) {
JCBinary jcBinary = (JCBinary) jcExpr;
InfixExpression infixExprNode = (InfixExpression) fact.createNode(NodeKind.ndkInfixExpression);
infixExprNode.setLeftOperand(visit(jcBinary.lhs));
infixExprNode.setRightOperand(visit(jcBinary.rhs));
switch (jcExpr.getKind()) {
case MULTIPLY:
infixExprNode.setOperator(InfixOperatorKind.iokTimes);
break;
case DIVIDE:
infixExprNode.setOperator(InfixOperatorKind.iokDivide);
break;
case REMAINDER:
infixExprNode.setOperator(InfixOperatorKind.iokRemainder);
break;
case PLUS:
infixExprNode.setOperator(InfixOperatorKind.iokPlus);
break;
case MINUS:
infixExprNode.setOperator(InfixOperatorKind.iokMinus);
break;
case LEFT_SHIFT:
infixExprNode.setOperator(InfixOperatorKind.iokLeftShift);
break;
case RIGHT_SHIFT:
infixExprNode.setOperator(InfixOperatorKind.iokSignedRightShift);
break;
case UNSIGNED_RIGHT_SHIFT:
infixExprNode.setOperator(InfixOperatorKind.iokUnsignedRightShift);
break;
case LESS_THAN:
infixExprNode.setOperator(InfixOperatorKind.iokLessThan);
break;
case GREATER_THAN:
infixExprNode.setOperator(InfixOperatorKind.iokGreaterThan);
break;
case LESS_THAN_EQUAL:
infixExprNode.setOperator(InfixOperatorKind.iokLessThanOrEqualTo);
break;
case GREATER_THAN_EQUAL:
infixExprNode.setOperator(InfixOperatorKind.iokGreaterThanOrEqualTo);
break;
case EQUAL_TO:
infixExprNode.setOperator(InfixOperatorKind.iokEqualTo);
break;
case NOT_EQUAL_TO:
infixExprNode.setOperator(InfixOperatorKind.iokNotEqualTo);
break;
case AND:
infixExprNode.setOperator(InfixOperatorKind.iokBitwiseAndLogicalAnd);
break;
case XOR:
infixExprNode.setOperator(InfixOperatorKind.iokBitwiseAndLogicalXor);
break;
case OR:
infixExprNode.setOperator(InfixOperatorKind.iokBitwiseAndLogicalOr);
break;
case CONDITIONAL_AND:
infixExprNode.setOperator(InfixOperatorKind.iokConditionalAnd);
break;
case CONDITIONAL_OR:
infixExprNode.setOperator(InfixOperatorKind.iokConditionalOr);
break;
default:
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.invalidOpKind", jcExpr.getKind()));
}
ret = infixExprNode.getId();
} else if (jcExpr instanceof JCLiteral) {
JCLiteral jcLiteral = (JCLiteral) jcExpr;
switch (jcExpr.getKind()) {
case INT_LITERAL: {
IntegerLiteral l = (IntegerLiteral) fact.createNode(NodeKind.ndkIntegerLiteral);
l.setValue(jcLiteral.format);
l.setIntValue((int) jcLiteral.value);
ret = l.getId();
break;
}
case LONG_LITERAL: {
LongLiteral l = (LongLiteral) fact.createNode(NodeKind.ndkLongLiteral);
l.setValue(jcLiteral.format);
l.setLongValue((long) jcLiteral.value);
ret = l.getId();
break;
}
case FLOAT_LITERAL: {
FloatLiteral l = (FloatLiteral) fact.createNode(NodeKind.ndkFloatLiteral);
l.setValue(jcLiteral.format);
l.setFloatValue((float) jcLiteral.value);
ret = l.getId();
break;
}
case DOUBLE_LITERAL: {
DoubleLiteral l = (DoubleLiteral) fact.createNode(NodeKind.ndkDoubleLiteral);
l.setValue(jcLiteral.format);
l.setDoubleValue((double) jcLiteral.value);
ret = l.getId();
break;
}
case BOOLEAN_LITERAL: {
BooleanLiteral l = (BooleanLiteral) fact.createNode(NodeKind.ndkBooleanLiteral);
l.setBooleanValue((boolean) jcLiteral.getValue());
ret = l.getId();
break;
}
case CHAR_LITERAL: {
CharacterLiteral l = (CharacterLiteral) fact.createNode(NodeKind.ndkCharacterLiteral);
l.setCharValue((char) jcLiteral.getValue());
l.setFormatString(jcLiteral.format);
ret = l.getId();
break;
}
case STRING_LITERAL: {
StringLiteral l = (StringLiteral) fact.createNode(NodeKind.ndkStringLiteral);
l.setValue(jcLiteral.format);
l.setFormatString(jcLiteral.format);
ret = l.getId();
break;
}
case NULL_LITERAL: {
NullLiteral l = (NullLiteral) fact.createNode(NodeKind.ndkNullLiteral);
ret = l.getId();
break;
}
default:
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.invalidLiteralKind", jcExpr.getKind()));
}
} else if (jcExpr instanceof JCUnary) {
JCUnary jcUnary = (JCUnary) jcExpr;
Unary unary = null;
switch (jcExpr.getKind()) {
case POSTFIX_INCREMENT:
case POSTFIX_DECREMENT: {
PostfixExpression postfixExprNode = (PostfixExpression) fact.createNode(NodeKind.ndkPostfixExpression);
unary = postfixExprNode;
if (jcExpr.getKind() == Kind.POSTFIX_INCREMENT) {
postfixExprNode.setOperator(PostfixOperatorKind.pookIncrement);
} else {
postfixExprNode.setOperator(PostfixOperatorKind.pookDecrement);
}
break;
}
default: {
PrefixExpression prefixExprNode = (PrefixExpression) fact.createNode(NodeKind.ndkPrefixExpression);
unary = prefixExprNode;
switch (jcExpr.getKind()) {
case PREFIX_INCREMENT:
prefixExprNode.setOperator(PrefixOperatorKind.peokIncrement);
break;
case PREFIX_DECREMENT:
prefixExprNode.setOperator(PrefixOperatorKind.peokDecrement);
break;
case UNARY_PLUS:
prefixExprNode.setOperator(PrefixOperatorKind.peokPlus);
break;
case UNARY_MINUS:
prefixExprNode.setOperator(PrefixOperatorKind.peokMinus);
break;
case BITWISE_COMPLEMENT:
prefixExprNode.setOperator(PrefixOperatorKind.peokComplement);
break;
case LOGICAL_COMPLEMENT:
prefixExprNode.setOperator(PrefixOperatorKind.peokNot);
break;
case OTHER:
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TreeBuilder.otherJCUnaryKind", jcExpr.toString());
}
break;
default:
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.invalidUnaryKind",
jcExpr.getKind()));
}
break;
}
}
unary.setOperand(visit(jcUnary.arg));
ret = unary.getId();
} else {
switch (jcExpr.getKind()) {
case ARRAY_TYPE:
case PRIMITIVE_TYPE:
case PARAMETERIZED_TYPE:
case UNION_TYPE:
case ANNOTATED_TYPE:
case INTERSECTION_TYPE:
logger.error("ex.jan.TreeBuilder.erroneousInsteadOfExpr", jcExpr.getKind());
ErroneousTypeExpression errr = (ErroneousTypeExpression) fact
.createNode(NodeKind.ndkErroneousTypeExpression);
ret = errr.getId();
break;
case IDENTIFIER: {
JCIdent jcIdent = (JCIdent) jcExpr;
Name name = jcIdent.name;
if (name == names._this) {
This thisNode = (This) fact.createNode(NodeKind.ndkThis);
ret = thisNode.getId();
} else if (name == names._super) {
Super superNode = (Super) fact.createNode(NodeKind.ndkSuper);
ret = superNode.getId();
} else {
Identifier identifierNode = (Identifier) fact.createNode(NodeKind.ndkIdentifier);
identifierNode.setName(name.toString());
ret = identifierNode.getId();
if (jcIdent.sym != null) {
symMaps.addClassAndInterfaceUsageSet(jcIdent.sym);
symMaps.addClassAndInterfaceToFullBuildSet(jcIdent.sym.owner);
symMaps.addToIdMap(ret, jcIdent.sym);
}
}
break;
}
case MEMBER_SELECT: {
JCFieldAccess jcFieldAccess = (JCFieldAccess) jcExpr;
int rightOpId = 0;
if (jcFieldAccess.name == names._class) {
ClassLiteral classLiteralNode = (ClassLiteral) fact.createNode(NodeKind.ndkClassLiteral);
classLiteralNode.setComponentType(visitTypeExpression(jcFieldAccess.selected));
// adding the type of class literal to external class build set
if (jcExpr.type != null) {
if (jcExpr.type instanceof Type.ClassType) {
for (Type t : ((Type.ClassType) jcExpr.type).typarams_field) {
symMaps.addMemberToTypeSymbolSet(t.tsym);
}
}
}
ret = classLiteralNode.getId();
} else {
FieldAccess fieldAccessNode = (FieldAccess) fact.createNode(NodeKind.ndkFieldAccess);
fieldAccessNode.setLeftOperand(visit(jcFieldAccess.selected));
if (jcFieldAccess.sym != null) {
if (jcFieldAccess.name == names._this) {
This thisNode = (This) fact.createNode(NodeKind.ndkThis);
rightOpId = thisNode.getId();
symMaps.addNodeType(jcExpr.type, thisNode.getId());
fieldAccessNode.setRightOperand(thisNode);
} else if (jcFieldAccess.name == names._super) {
Super superNode = (Super) fact.createNode(NodeKind.ndkSuper);
rightOpId = superNode.getId();
symMaps.addNodeType(jcExpr.type, superNode.getId());
fieldAccessNode.setRightOperand(superNode);
} else {
Identifier identifierNode = (Identifier) fact.createNode(NodeKind.ndkIdentifier);
identifierNode.setName(jcFieldAccess.name.toString());
rightOpId = identifierNode.getId();
fieldAccessNode.setRightOperand(identifierNode);
symMaps.addClassAndInterfaceUsageSet(jcFieldAccess.sym);
if (!jcFieldAccess.sym.type.isPrimitive()) {
if ((jcFieldAccess.sym instanceof VarSymbol
|| jcFieldAccess.sym instanceof MethodSymbol || jcFieldAccess.sym instanceof ClassSymbol)
&& !(jcFieldAccess.sym.owner instanceof PackageSymbol)) {
symMaps.addClassAndInterfaceToFullBuildSet(jcFieldAccess.sym.owner);
}
} else {
// for example: array.length, where array is
// boolean[]
symMaps.addClassAndInterfaceToFullBuildSet(jcFieldAccess.selected.type.tsym);
}
symMaps.addNodeType(jcFieldAccess.sym.type, identifierNode.getId());
symMaps.addToIdMap(identifierNode.getId(), jcFieldAccess.sym);
}
symMaps.addMemberToTypeSymbolSet(jcFieldAccess.sym.owner);
} else {
if (jcFieldAccess.name != null) {
Identifier identifierNode = (Identifier) fact.createNode(NodeKind.ndkIdentifier);
identifierNode.setName(jcFieldAccess.name.toString());
rightOpId = identifierNode.getId();
fieldAccessNode.setRightOperand(identifierNode);
// the last part of the field accesses in imports dont have type nor symbol
if (!inImport) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TreeBuilder.jcFieldAccesSymWasNull", jcFieldAccess);
}
}
}
}
if (rightOpId != 0) {
setPositionAndGenerated(jcFieldAccess, fieldAccessNode.getId());
Positioned rightId = (Positioned) fact.getRef(rightOpId);
setPositionOfRightExpr(fieldAccessNode, rightId, jcFieldAccess.name.toString().length());
}
ret = fieldAccessNode.getId();
}
break;
}
case TYPE_ANNOTATION:
case ANNOTATION: {
// 0 -> marker
// 1( !Assign) -> single
// 1(assign)\2.. ->normal
JCAnnotation jcAnnotation = (JCAnnotation) jcExpr;
Annotation annotationNode = null;
switch (jcAnnotation.args.size()) {
case 0:
annotationNode = (MarkerAnnotation) fact.createNode(NodeKind.ndkMarkerAnnotation);
break;
case 1:
// in dir analyze sometimes the javac don't create @AnnotName(value=XY.xy) from @AnnotName(XY.xy)
JCExpression jcArgZero = jcAnnotation.args.get(0);
if (jcArgZero instanceof JCAssign) {
JCAssign jcAssign = (JCAssign) jcAnnotation.args.get(0);
if (jcAssign.lhs.pos == jcAssign.rhs.pos) {
annotationNode = (Annotation) fact.createNode(NodeKind.ndkSingleElementAnnotation);
((SingleElementAnnotation) annotationNode).setArgument(visit(jcAssign.rhs));
break;
} else {
// fall-through
}
} else {
annotationNode = (Annotation) fact.createNode(NodeKind.ndkSingleElementAnnotation);
((SingleElementAnnotation) annotationNode).setArgument(visit(jcArgZero));
break;
}
// no break here, fall-through from 1 branch
default:
annotationNode = (NormalAnnotation) fact.createNode(NodeKind.ndkNormalAnnotation);
for (JCExpression a : jcAnnotation.args) {
((NormalAnnotation) annotationNode).addArguments(visit(a));
}
break;
}
if (jcAnnotation.annotationType != null) {
annotationNode.setAnnotationName(visitTypeExpression(jcAnnotation.annotationType));
}
ret = annotationNode.getId();
break;
}
case ARRAY_ACCESS: {
JCArrayAccess jcArrayAccess = (JCArrayAccess) jcExpr;
ArrayAccess arrayAccessNode = (ArrayAccess) fact.createNode(NodeKind.ndkArrayAccess);
arrayAccessNode.setLeftOperand(visit(jcArrayAccess.indexed));
arrayAccessNode.setRightOperand(visit(jcArrayAccess.index));
ret = arrayAccessNode.getId();
break;
}
case ASSIGNMENT: {
JCAssign jcAssign = (JCAssign) jcExpr;
Assignment assignmentNode = (Assignment) fact.createNode(NodeKind.ndkAssignment);
assignmentNode.setLeftOperand(visit(jcAssign.lhs));
assignmentNode.setRightOperand(visit(jcAssign.rhs));
assignmentNode.setOperator(AssignmentOperatorKind.askAssign);
ret = assignmentNode.getId();
break;
}
case CONDITIONAL_EXPRESSION: {
JCConditional jcConditional = (JCConditional) jcExpr;
Conditional conditionalNode = (Conditional) fact.createNode(NodeKind.ndkConditional);
conditionalNode.setCondition(visit(jcConditional.cond));
conditionalNode.setTrueExpression(visit(jcConditional.truepart));
conditionalNode.setFalseExpression(visit(jcConditional.falsepart));
ret = conditionalNode.getId();
break;
}
case ERRONEOUS: {
JCErroneous jcErroneus = (JCErroneous) jcExpr;
Erroneous erroneousNode = (Erroneous) fact.createNode(NodeKind.ndkErroneous);
if (jcErroneus.errs != null) {
for (JCTree err : jcErroneus.errs) {
if (err.getKind() != Kind.MODIFIERS) {
erroneousNode.addErrors(visit(err));
}
}
}
ret = erroneousNode.getId();
break;
}
case INSTANCE_OF: {
JCInstanceOf jcInstanceOf = (JCInstanceOf) jcExpr;
InstanceOf instanceOfNode = (InstanceOf) fact.createNode(NodeKind.ndkInstanceOf);
instanceOfNode.setOperand(visit(jcInstanceOf.expr));
instanceOfNode.setTypeOperand(visitTypeExpression(jcInstanceOf.clazz));
ret = instanceOfNode.getId();
break;
}
case METHOD_INVOCATION: {
// public Type varargsElement;
JCMethodInvocation jcMethodInvocation = (JCMethodInvocation) jcExpr;
MethodInvocation methodInvocationNode = (MethodInvocation) fact
.createNode(NodeKind.ndkMethodInvocation);
ret = methodInvocationNode.getId();
for (JCExpression exp : jcMethodInvocation.args) {
methodInvocationNode.addArguments(visit(exp));
}
for (JCExpression typeargs : jcMethodInvocation.typeargs) {
methodInvocationNode.addTypeArguments(visitTypeExpression(typeargs));
}
methodInvocationNode.setOperand(visit(jcMethodInvocation.meth));
if (jcMethodInvocation.meth.getKind() == Kind.MEMBER_SELECT) {
JCFieldAccess jcFieldAcess = (JCFieldAccess) jcMethodInvocation.meth;
if (jcFieldAcess.sym != null) {
if (jcFieldAcess.sym.owner != null) {
symMaps.addMemberToTypeSymbolSet(jcFieldAcess.sym.owner);
}
symMaps.getMethodInvMap().put(ret, jcFieldAcess.sym);
}
} else if (jcMethodInvocation.meth.getKind() == Kind.IDENTIFIER) {
JCIdent jcIdent = (JCIdent) jcMethodInvocation.meth;
if (jcIdent.sym != null && jcIdent.sym.owner != null) {
symMaps.getMethodInvMap().put(ret, jcIdent.sym);
symMaps.addMemberToTypeSymbolSet(jcIdent.sym.owner);
if (jcIdent.name == names._super) {
symMaps.addClassAndInterfaceToFullBuildSet(jcIdent.sym.owner);
}
}
} else {
logger.debug("debug.jan.TreeBuilder.unexpectedMethKind");
}
if (jcMethodInvocation.type != null && jcMethodInvocation.type.tsym != null
&& jcMethodInvocation.type.getKind() != TypeKind.VOID) {
symMaps.addMethodReturnType(jcMethodInvocation.type.tsym);
}
break;
}
case NEW_ARRAY: {
JCNewArray jcNewArray = (JCNewArray) jcExpr;
NewArray newArrayNode = (NewArray) fact.createNode(NodeKind.ndkNewArray);
ret = newArrayNode.getId();
if (jcNewArray.elemtype != null) {
newArrayNode.setComponentType(visitTypeExpression(jcNewArray.elemtype));
}
for (JCExpression dim : jcNewArray.dims) {
newArrayNode.addDimensions(visit(dim));
}
if (jcNewArray.elems != null) {
for (JCExpression elem : jcNewArray.elems) {
newArrayNode.addInitializers(visit(elem));
}
}
break;
}
case NEW_CLASS: {
JCNewClass jcNewClass = (JCNewClass) jcExpr;
NewClass newClassNode = (NewClass) fact.createNode(NodeKind.ndkNewClass);
ret = newClassNode.getId();
if (jcNewClass.encl != null) {
newClassNode.setEnclosingExpression(visit(jcNewClass.encl));
}
//No need to check for null value, the program does it later anyways.
//innerAnonymusClassSuperClass = jcNewClass.clazz;
if (jcNewClass.clazz != null) {
newClassNode.setTypeName(visitTypeExpression(jcNewClass.clazz));
}
if (jcNewClass.constructor != null) {
symMaps.getNewClassConstructorMap().put(ret, jcNewClass.constructor);
symMaps.addClassAndInterfaceToFullBuildSet(jcNewClass.constructor.owner);
}
for (JCExpression exp : jcNewClass.args) {
newClassNode.addArguments(visit(exp));
}
for (JCExpression exp : jcNewClass.typeargs) {
newClassNode.addTypeArguments(visitTypeExpression(exp));
}
if (jcNewClass.def != null) {
try {
isAnonymusClass = true;
if (jcNewClass.clazz != null)
innerAnonymusClassSuperClass = jcNewClass.clazz;
newClassNode.setAnonymousClass(visit(jcNewClass.def));
} finally {
innerAnonymusClassSuperClass = null;
}
}
break;
}
case PARENTHESIZED: {
JCParens jcParens = (JCParens) jcExpr;
ParenthesizedExpression parenthesizedNode = (ParenthesizedExpression) fact
.createNode(NodeKind.ndkParenthesizedExpression);
parenthesizedNode.setOperand(visit(jcParens.expr));
ret = parenthesizedNode.getId();
break;
}
case TYPE_CAST: {
JCTypeCast jcTypeCast = (JCTypeCast) jcExpr;
TypeCast typeCastNode = (TypeCast) fact.createNode(NodeKind.ndkTypeCast);
typeCastNode.setOperand(visit(jcTypeCast.expr));
typeCastNode.setTypeOperand(visitTypeExpression(jcTypeCast.clazz));
ret = typeCastNode.getId();
break;
}
case LAMBDA_EXPRESSION:
JCLambda jcLambda = (JCLambda) jcExpr;
Lambda lambdaNode = (Lambda) fact.createNode(NodeKind.ndkLambda);
jcLambda.params.forEach(param -> {
varDeclType = VarDeclType.PARAMETER;
lambdaNode.addParameters(visit(param));
});
lambdaNode.setBody(visit(jcLambda.body));
switch (jcLambda.paramKind) {
case IMPLICIT:
lambdaNode.setParamKind(LambdaParameterKind.lpkImplicit);
break;
case EXPLICIT:
lambdaNode.setParamKind(LambdaParameterKind.lpkExplicit);
break;
}
switch (jcLambda.getBodyKind()) {
case EXPRESSION:
lambdaNode.setBodyKind(LambdaBodyKind.lbkExpression);
break;
case STATEMENT:
lambdaNode.setBodyKind(LambdaBodyKind.lbkStatement);
break;
}
ret = lambdaNode.getId();
break;
case MEMBER_REFERENCE:
{
JCMemberReference jcMemberReference = (JCMemberReference) jcExpr;
MemberReference memberReferenceNode = (MemberReference) fact.createNode(NodeKind.ndkMemberReference);
if (jcMemberReference.mode != null) {
switch (jcMemberReference.mode) {
case INVOKE:
memberReferenceNode.setMode(MemberReferenceModeKind.mrmkInvoke);
break;
case NEW:
memberReferenceNode.setMode(MemberReferenceModeKind.mrmkNew);
break;
}
}
memberReferenceNode.setName(jcMemberReference.name.toString());
if (jcMemberReference.getOverloadKind() != null) {
switch (jcMemberReference.getOverloadKind()) {
case OVERLOADED:
memberReferenceNode.setOverloadKind(MemberReferenceOverloadKind.mrokOverloaded);
break;
case UNOVERLOADED:
memberReferenceNode.setOverloadKind(MemberReferenceOverloadKind.mrokUnoverloaded);
break;
}
}
if (jcMemberReference.kind != null) {
switch (jcMemberReference.kind) {
case SUPER:
memberReferenceNode.setReferenceKind(MemberReferenceKind.mrkSuper);
break;
case UNBOUND:
memberReferenceNode.setReferenceKind(MemberReferenceKind.mrkUnbound);
break;
case STATIC:
memberReferenceNode.setReferenceKind(MemberReferenceKind.mrkStatic);
break;
case BOUND:
memberReferenceNode.setReferenceKind(MemberReferenceKind.mrkBound);
break;
case IMPLICIT_INNER:
memberReferenceNode.setReferenceKind(MemberReferenceKind.mrkImplicitInner);
break;
case TOPLEVEL:
memberReferenceNode.setReferenceKind(MemberReferenceKind.mrkToplevel);
break;
case ARRAY_CTOR:
memberReferenceNode.setReferenceKind(MemberReferenceKind.mrkArrayCtor);
break;
}
}
if (jcMemberReference.typeargs != null) {
jcMemberReference.typeargs.forEach(arg -> memberReferenceNode.addTypeArguments(visitTypeExpression(arg)));
}
boolean buildTypeExpr = false;
//When the expr is a FieldAccess or an Identifier, the program has to decide whether build an expression or a type.
//It does it using the sym attribute.
if (jcMemberReference.expr instanceof JCFieldAccess) {
JCFieldAccess jcfa = (JCFieldAccess) jcMemberReference.expr;
if (jcfa.sym instanceof ClassSymbol) {
buildTypeExpr = true;
}
} else if (jcMemberReference.expr instanceof JCIdent) {
JCIdent jci = (JCIdent) jcMemberReference.expr;
if (jci.sym instanceof ClassSymbol) {
buildTypeExpr = true;
}
} else if (jcMemberReference.expr instanceof JCWildcard) {
buildTypeExpr = true;
} else { //If the program can't decide until this point, the program looks at its kind.
switch (jcMemberReference.expr.getKind()) {
case ARRAY_TYPE:
case PRIMITIVE_TYPE:
case PARAMETERIZED_TYPE:
case UNION_TYPE:
case ANNOTATED_TYPE:
case INTERSECTION_TYPE:
buildTypeExpr = true;
break;
default:
//We can log here or something.
}
}
if (buildTypeExpr) {
memberReferenceNode.setQualifierExpression(visitTypeExpression(jcMemberReference.expr));
} else {
memberReferenceNode.setQualifierExpression(visit(jcMemberReference.expr));
}
ret = memberReferenceNode.getId();
if (jcMemberReference.sym != null) {
symMaps.getMemberReferenceMap().put(ret, jcMemberReference.sym);
symMaps.addClassAndInterfaceToFullBuildSet(jcMemberReference.sym.owner);
} else {
//We can log here or something when the sym is null.
}
//TODO Build referent type on member reference if needed.
//We can build later if needed. It contains the type the referred method returns. For example in case of "Hello"::length it will be int.
break;
}
default:
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.jcExprNotHandledYet", jcExpr.getKind()));
}
}
if (ret == 0) {
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.atTheEndOfVisitExprRetIsZero"));
} else {
setPositionAndGenerated(jcExpr, ret);
if (jcExpr.type != null) {
symMaps.addNodeType(jcExpr.type, ret);
} else {
if (inImport) {
// the last part of the field accesses in imports dont have type nor symbol
} else {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TreeBuilder.exprDontHaveAType", ret);
}
}
}
if (jcExpr instanceof JCPolyExpression) {
Base node = fact.getRef(ret);
if (Common.getIsPolyExpression(node)) {
// TODO the old nodes Conditional, MethodInvocation and NewClass are not yet
// handled as PolyExpression in our schema
PolyExpression polyExpr = (PolyExpression) node;
switch (((JCPolyExpression) jcExpr).polyKind) {
case STANDALONE:
polyExpr.setPolyKind(PolyExpressionKind.pekStandalone);
break;
case POLY:
polyExpr.setPolyKind(PolyExpressionKind.pekPoly);
break;
}
if (Common.getIsFunctionalExpression(node)) {
JCFunctionalExpression jcFunctionalExpression = (JCFunctionalExpression) jcExpr;
if (jcFunctionalExpression.target != null) {
symMaps.addFuncExprTarget(jcFunctionalExpression.target, ret);
}
}
}
}
}
return ret;
}
private int visitTypeExpression(JCTree jcTree) {
int ret = 0;
if (jcTree == null) {
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.visitExprGetANullNode"));
}
if (jcTree instanceof JCWildcard) {
JCWildcard jcWildcard = (JCWildcard) jcTree;
WildcardExpression wildcardExpreesionNode = (WildcardExpression) fact
.createNode(NodeKind.ndkWildcardExpression);
if (jcWildcard.inner != null) {
wildcardExpreesionNode.setBound(visitTypeExpression(jcWildcard.inner));
}
switch (jcTree.getKind()) {
case UNBOUNDED_WILDCARD:
wildcardExpreesionNode.setKind(TypeBoundKind.tbkWildcard);
break;
case EXTENDS_WILDCARD:
wildcardExpreesionNode.setKind(TypeBoundKind.tbkExtends);
break;
case SUPER_WILDCARD:
wildcardExpreesionNode.setKind(TypeBoundKind.tbkSuper);
break;
default:
throw new JavaException(
logger.formatMessage("ex.jan.TreeBuilder.invalidWildCardType", jcTree.getKind()));
}
ret = wildcardExpreesionNode.getId();
} else {
{
switch (jcTree.getKind()) {
case ARRAY_TYPE: {
JCArrayTypeTree jcArrayType = (JCArrayTypeTree) jcTree;
ArrayTypeExpression arrayTypeExprNode = (ArrayTypeExpression) fact
.createNode(NodeKind.ndkArrayTypeExpression);
if (jcArrayType.elemtype != null) {
arrayTypeExprNode.setComponentType(visitTypeExpression(jcArrayType.elemtype));
}
if (jcArrayType.type != null) {
symMaps.addClassAndInterfaceUsageSet(jcArrayType.type.tsym);
}
ret = arrayTypeExprNode.getId();
break;
}
case PRIMITIVE_TYPE: {
JCPrimitiveTypeTree jcPrimTypeTree = (JCPrimitiveTypeTree) jcTree;
PrimitiveTypeExpression primTypeExprNode = (PrimitiveTypeExpression) fact
.createNode(NodeKind.ndkPrimitiveTypeExpression);
switch (jcPrimTypeTree.typetag) {
case BOOLEAN:
primTypeExprNode.setKind(PrimitiveTypeKind.ptkBoolean);
break;
case BYTE:
primTypeExprNode.setKind(PrimitiveTypeKind.ptkByte);
break;
case SHORT:
primTypeExprNode.setKind(PrimitiveTypeKind.ptkShort);
break;
case INT:
primTypeExprNode.setKind(PrimitiveTypeKind.ptkInt);
break;
case LONG:
primTypeExprNode.setKind(PrimitiveTypeKind.ptkLong);
break;
case CHAR:
primTypeExprNode.setKind(PrimitiveTypeKind.ptkChar);
break;
case FLOAT:
primTypeExprNode.setKind(PrimitiveTypeKind.ptkFloat);
break;
case DOUBLE:
primTypeExprNode.setKind(PrimitiveTypeKind.ptkDouble);
break;
case VOID:
primTypeExprNode.setKind(PrimitiveTypeKind.ptkVoid);
break;
case ERROR:
// handled at the begining of the method to dont create unnecessary nodes
default:
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TreeBuilder.unknownPrimitiveTypeKind", jcPrimTypeTree.typetag);
}
}
ret = primTypeExprNode.getId();
break;
}
case PARAMETERIZED_TYPE: {
JCTypeApply jcTypeApply = (JCTypeApply) jcTree;
TypeApplyExpression typeApplyExprNode = (TypeApplyExpression) fact
.createNode(NodeKind.ndkTypeApplyExpression);
typeApplyExprNode.setRawType(visitTypeExpression(jcTypeApply.clazz));
for (JCExpression arg : jcTypeApply.arguments) {
typeApplyExprNode.addTypeArguments(visitTypeExpression(arg));
}
ret = typeApplyExprNode.getId();
break;
}
case UNION_TYPE: {
JCTypeUnion jcTypeUninon = (JCTypeUnion) jcTree;
TypeUnionExpression typeUnionExprNode = (TypeUnionExpression) fact
.createNode(NodeKind.ndkTypeUnionExpression);
for (JCExpression alt : jcTypeUninon.alternatives) {
typeUnionExprNode.addAlternatives(visitTypeExpression(alt));
}
ret = typeUnionExprNode.getId();
break;
}
case IDENTIFIER: {
JCIdent jcIdent = (JCIdent) jcTree;
SimpleTypeExpression simpleTypeExprNode = (SimpleTypeExpression) fact
.createNode(NodeKind.ndkSimpleTypeExpression);
simpleTypeExprNode.setName(jcIdent.name.toString());
ret = simpleTypeExprNode.getId();
if (OptionParser.isBuildExtFromSource()) {
symMaps.addClassAndInterfaceToFullBuildSet(jcIdent.sym);
}
symMaps.addClassAndInterfaceUsageSet(jcIdent.sym);
break;
}
case MEMBER_SELECT: {
JCFieldAccess jcFieldAccess = (JCFieldAccess) jcTree;
QualifiedTypeExpression qualiTypeExprNode = (QualifiedTypeExpression) fact
.createNode(NodeKind.ndkQualifiedTypeExpression);
// to build p1.p2.OuterClass.InnerClass instead of .p1.p2.OuterClass.InnerClass
boolean stop = false;
if (jcFieldAccess.selected instanceof JCFieldAccess) {
JCFieldAccess jFA = (JCFieldAccess) jcFieldAccess.selected;
if (jFA.selected instanceof JCIdent) {
JCIdent jI = (JCIdent) jFA.selected;
if (jI.sym == symtab.rootPackage) {
stop = true;
SimpleTypeExpression sTExprNode = (SimpleTypeExpression) fact
.createNode(NodeKind.ndkSimpleTypeExpression);
sTExprNode.setName(jFA.name.toString());
if (jcFieldAccess.pos == Position.NOPOS)
sTExprNode.setIsCompilerGenerated(true);
else
setPositionOfRightExpr(qualiTypeExprNode, sTExprNode, jcFieldAccess.name.toString()
.length());
symMaps.addNodeType(jcFieldAccess.type, sTExprNode.getId());
qualiTypeExprNode.setQualifierType(sTExprNode.getId());
}
}
}
if (!stop) {
qualiTypeExprNode.setQualifierType(visitTypeExpression(jcFieldAccess.selected));
}
SimpleTypeExpression simpleTypeExprNode = (SimpleTypeExpression) fact
.createNode(NodeKind.ndkSimpleTypeExpression);
simpleTypeExprNode.setName(jcFieldAccess.name.toString());
setPositionAndGenerated(jcFieldAccess, qualiTypeExprNode.getId());
if (jcFieldAccess.pos == Position.NOPOS)
simpleTypeExprNode.setIsCompilerGenerated(true);
else
setPositionOfRightExpr(qualiTypeExprNode, simpleTypeExprNode, jcFieldAccess.name.toString()
.length());
symMaps.addNodeType(jcFieldAccess.type, simpleTypeExprNode.getId());
qualiTypeExprNode.setSimpleType(simpleTypeExprNode.getId());
if (jcFieldAccess.sym != null) {
symMaps.addMemberToTypeSymbolSet(jcFieldAccess.sym);
} else {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TreeBuilder.jcFieldAccesSymWasNull", jcTree);
}
}
ret = qualiTypeExprNode.getId();
break;
}
case ERRONEOUS: {
JCErroneous jcErroneous = (JCErroneous) jcTree;
ErroneousTypeExpression erroneousTypeExprNode = (ErroneousTypeExpression) fact
.createNode(NodeKind.ndkErroneousTypeExpression);
for (JCTree err : jcErroneous.errs) {
if (err.getKind() != Kind.MODIFIERS) {
erroneousTypeExprNode.addErrors(visit(err));
}
}
ret = erroneousTypeExprNode.getId();
break;
}
case ANNOTATED_TYPE: {
JCAnnotatedType jcAnnotatedType = (JCAnnotatedType) jcTree;
AnnotatedTypeExpression annotatedTypeNode = (AnnotatedTypeExpression) fact.createNode(NodeKind.ndkAnnotatedTypeExpression);
jcAnnotatedType.annotations.forEach(annotation -> annotatedTypeNode.addAnnotations(visit(annotation)));
annotatedTypeNode.setUnderlyingType(visitTypeExpression(jcAnnotatedType.underlyingType));
ret = annotatedTypeNode.getId();
break;
}
case INTERSECTION_TYPE:
{
JCTypeIntersection jcTypeIntersection = (JCTypeIntersection) jcTree;
TypeIntersectionExpression typeIntersectionNode = (TypeIntersectionExpression) fact.createNode(NodeKind.ndkTypeIntersectionExpression);
jcTypeIntersection.bounds.forEach(bound -> typeIntersectionNode.addBounds(visitTypeExpression(bound)));
ret = typeIntersectionNode.getId();
break;
}
default:
ErroneousTypeExpression erroneousTypeExprNode = (ErroneousTypeExpression) fact
.createNode(NodeKind.ndkErroneousTypeExpression);
ret = erroneousTypeExprNode.getId();
logger.error("ex.jan.TreeBuilder.erroneousInsteadOfTypeExpr", jcTree.getKind());
}
}
}
if (ret == 0) {
throw new JavaException(logger.formatMessage("ex.jan.TreeBuilder.atTheEndOfVisitTypeExprRetIsZero"));
} else {
setPositionAndGenerated(jcTree, ret);
if (jcTree.type != null) {
symMaps.addNodeType(jcTree.type, ret);
} else {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TreeBuilder.exprDontHaveAType", ret);
}
}
}
return ret;
}
private int createSimpleTypeExpression(Type t) {
TypeExpression typeExprNode;
if(t.tsym != null) {
SimpleTypeExpression simpleTypeExprNode = (SimpleTypeExpression) fact
.createNode(NodeKind.ndkSimpleTypeExpression);
typeExprNode = simpleTypeExprNode;
simpleTypeExprNode.setName(t.tsym.name.toString());
if (OptionParser.isBuildExtFromSource()) {
symMaps.addClassAndInterfaceToFullBuildSet(t.tsym);
}
if (!t.isPrimitive()) {
symMaps.addClassAndInterfaceUsageSet(t.tsym);
}
} else {
typeExprNode = (ErroneousTypeExpression) fact
.createNode(NodeKind.ndkErroneousTypeExpression);
}
typeExprNode.setIsCompilerGenerated(true);
symMaps.addNodeType(t, typeExprNode.getId());
return typeExprNode.getId();
}
private void setMethodType(JCClassDecl jcClassDecl) {
if (JANFlags.hasAnnotationFlag(jcClassDecl.mods.flags))
methodType = MethodType.ANNOTATION_ELEMENT;
}
private void setVariableType(JCTree jcTree) {
JCVariableDecl var = (JCVariableDecl) jcTree;
if (JANFlags.hasEnumFlag(var.mods.flags))
varDeclType = VarDeclType.ENUMCONST;
else
varDeclType = VarDeclType.VARIABLE;
}
private void setBlockType(JCTree jcTree) {
JCBlock block = (JCBlock) jcTree;
if (JANFlags.hasStaticFlag(block.flags)) {
blockType = BlockType.STATIC_INIT;
} else {
blockType = BlockType.INSTANCE_INIT;
}
}
private void setModifiersAndAnnotations(JCModifiers jcMods, NamedDeclaration memberNode) {
JANFlags.setModifiers(jcMods.flags, memberNode);
for (JCAnnotation a : jcMods.annotations) {
memberNode.addAnnotations(visit(a));
}
setOtherPositions(jcMods, memberNode);
}
private void setPositionAndGenerated(JCTree jcTree, int nodeId) {
Positioned nodeC = (Positioned) fact.getRef(nodeId);
if (generatedTreeRoot != null || jcTree.pos == Position.NOPOS) {
nodeC.setIsCompilerGenerated(true);
} else {
if (jcTree != null) {
Range range = createRange(jcTree);
nodeC.setPosition(range);
setOtherPositions(jcTree, nodeC);
}
}
}
private Range createRange(JCTree jcTree) {
Range range = new Range(fact.getStringTable());
range.setPathKey(actualColumbusCuPathKey);
int pos = jcTree.pos;
int wideStartPos = jcTree.getStartPosition();
int wideEndPos = jcTree.getEndPosition(actualJCCU.endPositions);
if (pos != Position.NOPOS) {
range.setLine(lineMap.getLineNumber(pos));
range.setCol(lineMap.getColumnNumber(pos));
}
if (wideStartPos != Position.NOPOS) {
range.setWideLine(lineMap.getLineNumber(wideStartPos));
range.setWideCol(lineMap.getColumnNumber(wideStartPos));
}
if (wideEndPos != Position.NOPOS) {
range.setEndLine(lineMap.getLineNumber(wideEndPos)); // TODO not exist in the javac schema
range.setEndCol(lineMap.getColumnNumber(wideEndPos));
range.setWideEndLine(lineMap.getLineNumber(wideEndPos));
range.setWideEndCol(lineMap.getColumnNumber(wideEndPos));
}
return range;
}
private void setPositionOfRightExpr(Positioned fieldAccessNode, Positioned node, int length) {
if (generatedTreeRoot != null) {
node.setIsCompilerGenerated(true);
} else {
Range faRange = fieldAccessNode.getPosition();
Range range = new Range(fact.getStringTable());
range.setPathKey(actualColumbusCuPathKey);
int line = faRange.getWideEndLine();
int endCol = faRange.getWideEndCol();
int startCol = endCol - length;
if(startCol< 0) {
startCol = 0;
}
range.setLine(line);
range.setCol(startCol);
range.setEndLine(line);
range.setEndCol(endCol);
range.setWideLine(line);
range.setWideCol(startCol);
range.setWideEndLine(line);
range.setWideEndCol(endCol);
node.setPosition(range);
}
}
private Range getRangeFromOtherPosition(int pos, TokenKind token, Name name) {
Range range = null;
if (pos != Position.NOPOS) {
int line = 0, col = 0, endLine = 0, endCol = 0;
line = lineMap.getLineNumber(pos);
col = lineMap.getColumnNumber(pos);
endLine = line;
if (token.name != null) {
endCol = col + token.name.length();
} else {
if (name != null) {
endCol = col + name.length();
} else {
endCol = col + 1;
}
}
range = new Range(fact.getStringTable());
range.setPathKey(actualColumbusCuPathKey);
range.setLine(line);
range.setCol(col);
range.setEndLine(endLine);
range.setEndCol(endCol);
range.setWideLine(line);
range.setWideCol(col);
range.setWideEndLine(endLine);
range.setWideEndCol(endCol);
}
return range;
}
private void setOtherPositions(JCTree jcTree, Positioned node) {
Map<TokenKind, Set<Integer>> tokenPositions = actualJCCU.otherPositions.get(jcTree);
if (tokenPositions != null) {
for (Map.Entry<TokenKind, Set<Integer>> tokenPos : tokenPositions.entrySet()) {
TokenKind token = tokenPos.getKey();
Set<Integer> positions = tokenPos.getValue();
int pos = Position.NOPOS;
if (positions.size() == 2) {
if (token == TokenKind.SEMI && Common.getIsBasicFor(node)) {
Iterator<Integer> it = positions.iterator();
int firstPos = it.next();
int secondPos = it.next();
((BasicFor)node).setFirstSemiPosition(getRangeFromOtherPosition(firstPos, token, null));
((BasicFor)node).setSecondSemiPosition(getRangeFromOtherPosition(secondPos, token, null));
}
continue;
} else if (positions.size() != 1) {
// should not happen
continue;
} else {
pos = positions.iterator().next();
}
Name name = null;
if (jcTree instanceof JCClassDecl) {
name = ((JCClassDecl)jcTree).name;
} else if (jcTree instanceof JCMethodDecl) {
name = ((JCMethodDecl)jcTree).name;
} else if (jcTree instanceof JCVariableDecl) {
name = ((JCVariableDecl)jcTree).name;
} else if (jcTree instanceof JCTypeParameter) {
name = ((JCTypeParameter)jcTree).name;
} else if (jcTree instanceof JCBreak) {
name = ((JCBreak)jcTree).label;
} else if (jcTree instanceof JCContinue) {
name = ((JCContinue)jcTree).label;
}
Range range = getRangeFromOtherPosition(pos, token, name);
if (range == null) {
// should not happen
continue;
}
boolean warnNodeType = false;
boolean warnUnhandledToken = false;
switch (tokenPos.getKey()) {
case PUBLIC:
case PROTECTED:
case PRIVATE:
if (Common.getIsNamedDeclaration(node)) {
((NamedDeclaration)node).setAccessibilityPosition(range);
} else {
warnNodeType = true;
}
break;
case ABSTRACT:
if (Common.getIsTypeDeclaration(node)) {
((TypeDeclaration)node).setAbstractPosition(range);
} else if (Common.getIsMethodDeclaration(node)) {
((MethodDeclaration)node).setAbstractPosition(range);
} else {
warnNodeType = true;
}
break;
case STATIC:
if (Common.getIsImport(node)) {
((Import)node).setStaticPosition(range);
} else if (Common.getIsNamedDeclaration(node)) {
((NamedDeclaration)node).setStaticPosition(range);
} else {
warnNodeType = true;
}
break;
case FINAL:
if (Common.getIsNamedDeclaration(node)) {
((NamedDeclaration)node).setFinalPosition(range);
} else {
warnNodeType = true;
}
break;
case TRANSIENT:
if (Common.getIsVariable(node)) {
((Variable)node).setTransientPosition(range);
} else {
warnNodeType = true;
}
break;
case VOLATILE:
if (Common.getIsVariable(node)) {
((Variable)node).setVolatilePosition(range);
} else {
warnNodeType = true;
}
break;
case SYNCHRONIZED:
if (Common.getIsNormalMethod(node)) {
((NormalMethod)node).setSynchronizedPosition(range);
} else {
warnNodeType = true;
}
break;
case NATIVE:
if (Common.getIsNormalMethod(node)) {
((NormalMethod)node).setNativePosition(range);
} else {
warnNodeType = true;
}
break;
case STRICTFP:
if (Common.getIsMethodDeclaration(node)) {
((MethodDeclaration)node).setStrictfpPosition(range);
} else {
warnNodeType = true;
}
break;
case IDENTIFIER:
//case ASSERT:
//case ENUM:
// 'assert' and 'enum' can also be used as identifiers in old java versions
// but they are also stored as IDENTIFIER
if (Common.getIsNamed(node)) {
((Named)node).setNamePosition(range);
} else if (Common.getIsJump(node)) {
((Jump)node).setLabelPosition(range);
} else {
warnNodeType = true;
}
break;
case ELLIPSIS:
if (Common.getIsParameter(node)) {
((Parameter)node).setVarargsPosition(range);
} else {
warnNodeType = true;
}
break;
case CLASS:
case INTERFACE:
case ENUM:
if (Common.getIsTypeDeclaration(node)) {
((TypeDeclaration)node).setTypeNamePosition(range);
} else {
warnNodeType = true;
}
break;
case MONKEYS_AT:
if (Common.getIsAnnotationType(node)) {
((AnnotationType)node).setAtSignPosition(range);
} else {
warnNodeType = true;
}
break;
case ELSE:
if (Common.getIsIf(node)) {
((If)node).setElsePosition(range);
} else {
warnNodeType = true;
}
break;
case WHILE:
if (Common.getIsDo(node)) {
((Do)node).setWhilePosition(range);
} else {
warnNodeType = true;
}
break;
case FINALLY:
if (Common.getIsTry(node)) {
((Try)node).setFinallyPosition(range);
} else {
warnNodeType = true;
}
break;
case COLON:
if (Common.getIsSwitchLabel(node)) {
((SwitchLabel)node).setColonPosition(range);
} else if (Common.getIsAssert(node)) {
((Assert)node).setColonPosition(range);
} else if (Common.getIsConditional(node)) {
((Conditional)node).setColonPosition(range);
} else if (Common.getIsLabeledStatement(node)) {
((LabeledStatement)node).setColonPosition(range);
} else if (Common.getIsEnhancedFor(node)) {
((EnhancedFor)node).setColonPosition(range);
} else {
warnNodeType = true;
}
break;
case EXTENDS:
if (Common.getIsTypeDeclaration(node)) {
((TypeDeclaration)node).setExtendsPosition(range);
} else {
warnNodeType = true;
}
break;
case IMPLEMENTS:
if (Common.getIsTypeDeclaration(node)) {
((TypeDeclaration)node).setImplementsPosition(range);
} else {
warnNodeType = true;
}
break;
case THROWS:
if (Common.getIsNormalMethod(node)) {
((NormalMethod)node).setThrowsPosition(range);
} else {
warnNodeType = true;
}
break;
case DEFAULT:
if (Common.getIsAnnotationTypeElement(node)) {
((AnnotationTypeElement)node).setDefaultPosition(range);
} else {
warnNodeType = true;
}
break;
case LPAREN:
if (Common.getIsMethodDeclaration(node)) {
((MethodDeclaration)node).setParametersStartPosition(range);
} else if (Common.getIsTry(node)) {
((Try)node).setResourceLeftParenPosition(range);
} else if (Common.getIsHandler(node)) {
((Handler)node).setLeftParenPosition(range);
} else if (Common.getIsFor(node)) {
((For)node).setLeftParenPosition(range);
} else {
warnNodeType = true;
}
break;
case RPAREN:
if (Common.getIsMethodDeclaration(node)) {
((MethodDeclaration)node).setParametersEndPosition(range);
} else if (Common.getIsTry(node)) {
((Try)node).setResourceRightParenPosition(range);
} else if (Common.getIsHandler(node)) {
((Handler)node).setRightParenPosition(range);
} else if (Common.getIsFor(node)) {
((For)node).setRightParenPosition(range);
} else {
warnNodeType = true;
}
break;
case LBRACE:
if (Common.getIsSwitch(node)) {
((Switch)node).setBlockStartPosition(range);
} else if (Common.getIsTypeDeclaration(node)) {
((TypeDeclaration)node).setBodyStartPosition(range);
} else if (Common.getIsStaticInitializerBlock(node)) {
((StaticInitializerBlock)node).setBlockStartPosition(range);
} else if (Common.getIsBlock(node)) {
// nothing to do, position is stored for static init block
} else if (Common.getIsNewArray(node)) {
((NewArray)node).setLeftBracePosition(range);
} else {
warnNodeType = true;
}
break;
case EQ:
if (Common.getIsVariable(node)) {
((Variable)node).setEqualSignPosition(range);
} else {
warnNodeType = true;
}
break;
case SEMI:
if (Common.getIsEnum(node)) {
((Enum)node).setSemiPosition(range);
} else {
warnNodeType = true;
}
break;
default:
warnUnhandledToken = true;
break;
}
}
}
}
public void setLLOCToSubTree(TreeSet<Integer> usefulLines) {
AlgorithmPreorder preorder = new AlgorithmPreorder();
preorder.setVisitSpecialNodes(false, false);
// The visitor to set the LLOC values of given nodes.
VisitorAbstractNodes v = new VisitorAbstractNodes() {
@Override
public void visit(TypeDeclaration node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
node.setLloc(getLLOC(node));
}
@Override
public void visit(MethodDeclaration node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
node.setLloc(getLLOC(node));
}
public void visit(Lambda node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
node.setLloc(getLLOC(node));
};
@Override
public void visit(InitializerBlock node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
node.setLloc(getLLOC(node));
}
private int getLLOC(Positioned node) {
return usefulLines
.subSet(node.getPosition().getWideLine(), true, node.getPosition().getWideEndLine(), true)
.size();
}
};
EdgeIterator<TypeDeclaration> typeDeclarationsIterator = actualColumbusCU.getTypeDeclarationsIterator();
while (typeDeclarationsIterator.hasNext()) {
preorder.run(fact, v, typeDeclarationsIterator.next());
}
}
private int createModuleTypeNode(Type modType) {
ModuleType modTypeNode = (ModuleType) fact.createNode(NodeKind.ndkModuleType);
modTypeNode.setRefersTo(actualModuleId);
symMaps.getModuleTypeMap().put(modType, modTypeNode.getId());
return modTypeNode.getId();
}
}
enum MethodType {
NORMAL, ANNOTATION_ELEMENT,
}
enum BlockType {
NORMAL, INSTANCE_INIT, STATIC_INIT;
}
enum VarDeclType {
NONE, VARIABLE, ENUMCONST, PARAMETER
}
| 96,131 | 32.600839 | 140 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/TypeBuilder.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.type.TypeMirror;
import org.jan.SymbolMaps.TypeKinds;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.DelegatedType;
import com.sun.tools.javac.code.Type.UnknownType;
import columbus.java.asg.Common;
import columbus.java.asg.Factory;
import columbus.java.asg.JavaException;
import columbus.java.asg.base.Base;
import columbus.java.asg.enums.NodeKind;
import columbus.java.asg.expr.Expression;
import columbus.java.asg.expr.FunctionalExpression;
import columbus.java.asg.struc.MethodDeclaration;
import columbus.java.asg.type.ArrayType;
import columbus.java.asg.type.BooleanType;
import columbus.java.asg.type.ByteType;
import columbus.java.asg.type.CharType;
import columbus.java.asg.type.DoubleType;
import columbus.java.asg.type.ErrorType;
import columbus.java.asg.type.FloatType;
import columbus.java.asg.type.IntType;
import columbus.java.asg.type.IntersectionType;
import columbus.java.asg.type.LongType;
import columbus.java.asg.type.MethodType;
import columbus.java.asg.type.NoType;
import columbus.java.asg.type.NullType;
import columbus.java.asg.type.PackageType;
import columbus.java.asg.type.ScopedType;
import columbus.java.asg.type.ShortType;
import columbus.java.asg.type.TypeVariable;
import columbus.java.asg.type.UnionType;
import columbus.java.asg.type.VoidType;
import columbus.java.asg.type.WildcardType;
import columbus.logger.LoggerHandler;
public class TypeBuilder {
private static final LoggerHandler logger = new LoggerHandler(TypeBuilder.class,
OptionParser.getLoggerPropertyFile());
private Factory fact;
private SymbolMaps symMaps;
private Map<Symbol, Integer> classSymbolMap = new HashMap<>();
private Map<Type, Integer> builtTypeSymbols = new HashMap<>();
private Map<Integer, Integer> classAndPackageTypes = new HashMap<>();
public TypeBuilder(Factory factory, SymbolMaps symMaps) {
this.fact = factory;
this.symMaps = symMaps;
classSymbolMap.putAll(symMaps.getExternalTypeDeclarationMap());
classSymbolMap.putAll(symMaps.getInnerTypeDeclarationMap());
}
public void build() {
buildTypes(symMaps.getUsedTypesMap(), TypeKinds.EXPR_TYPE);
buildTypes(symMaps.getMethodTypeMap(), TypeKinds.METHOD_TYPE);
buildTypes(symMaps.getFuncExprTargetMap(), TypeKinds.FUNC_EXPR_TARGET);
// create ClassType node for each TypeDeclaration
Factory.Iterator it = fact.iterator();
while (it.hasNext()) {
Base node = it.next();
if (Common.getIsTypeDeclaration(node)) {
createClassOrPackageType(node);
}
}
classAndPackageTypes.clear();
}
public void buildTypes(Map<Type, List<Integer>> typeMap, TypeKinds typeKind) {
for (Map.Entry<Type, List<Integer>> entry : typeMap.entrySet()) {
int typeId = visit(entry.getKey());
if (typeId != 0) {
for (Integer id : entry.getValue()) {
Base b = fact.getRef(id);
boolean wrongNode = false;
switch (typeKind) {
case EXPR_TYPE:
if (b instanceof Expression) {
Expression expr = (Expression) b;
columbus.java.asg.type.Type t = expr.getType();
if (t == null) {
expr.setType(typeId);
} else if (t.getId() != typeId) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TypeBuilder.couldntSetExpTypeToAnother", id,
expr.getNodeKind(), t.getId(), typeId);
}
}
} else {
wrongNode = true;
}
break;
case METHOD_TYPE:
if (b instanceof MethodDeclaration && Common.getIsMethodType(fact.getRef(typeId))) {
MethodDeclaration m = (MethodDeclaration) b;
m.setMethodType(typeId);
} else {
wrongNode = true;
}
break;
case FUNC_EXPR_TARGET:
if (b instanceof FunctionalExpression) {
FunctionalExpression expr = (FunctionalExpression) b;
// TODO is it possible, that the type of the expression and this target type are
// always the same?
expr.setTarget(typeId);
} else {
wrongNode = true;
}
break;
}
if (wrongNode) {
logger.error("error.jan.TypeBuilder.unexpectedNodeIdForType", id, b.getNodeKind(), typeId,
fact.getNodeKind(typeId), entry.getKey());
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TypeBuilder.unknownType", entry.getKey());
}
}
}
}
private int createClassOrPackageType(Base node) {
if (node == null) {
return 0;
}
if (Common.getIsTypeDeclaration(node) || Common.getIsPackage(node)) {
Integer type = classAndPackageTypes.get(node.getId());
if (type != null) {
return type;
}
}
if (Common.getIsTypeDeclaration(node)) {
int ownerTypeId = 0;
if (node.getParent() != null) {
ownerTypeId = createClassOrPackageType(node.getParent());
}
int typeId = fact.createClassType(ownerTypeId, node.getId()).getId();
classAndPackageTypes.put(node.getId(), typeId);
return typeId;
} else if (Common.getIsPackage(node)) {
int typeId = fact.createPackageType(node.getId()).getId();
classAndPackageTypes.put(node.getId(), typeId);
return typeId;
} else {
if (node.getParent() != null) {
return createClassOrPackageType(node.getParent());
}
}
return 0;
}
public static <RetType> RetType getValueFromTypeMap(Type type, Map<Type, RetType> map) {
if (type == null) {
return null;
}
return map.get(type);
}
private int visit(Type type) {
int ret = 0;
if (type == null)
return 0;
try {
Integer typeId = getValueFromTypeMap(type, builtTypeSymbols);
if (typeId != null) {
ret = typeId;
} else {
switch (type.getKind()) {
case INT: {
IntType typeNode = fact.createIntType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case BOOLEAN: {
BooleanType typeNode = fact.createBooleanType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case BYTE: {
ByteType typeNode = fact.createByteType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case CHAR: {
CharType typeNode = fact.createCharType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case DOUBLE: {
DoubleType typeNode = fact.createDoubleType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case FLOAT: {
FloatType typeNode = fact.createFloatType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case LONG: {
LongType typeNode = fact.createLongType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case SHORT: {
ShortType typeNode = fact.createShortType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case VOID: {
VoidType typeNode = fact.createVoidType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case NULL: {
NullType typeNode = fact.createNullType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case ARRAY: {
String name = type.toString();
int dim = (name.length() - name.indexOf('[')) / 2;
int componentId = visit(((Type.ArrayType) type).elemtype);
ArrayType typeNode = fact.createArrayType(dim, componentId);
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case ERROR: {
ErrorType typeNode = fact.createErrorType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case PACKAGE: {
int refersToId = 0;
Integer ref = symMaps.findPackage(type.tsym.packge());
if (ref == null) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TypeBuilder.packageCouldntBeFound", type);
}
} else {
refersToId = ref;
}
PackageType typeNode = fact.createPackageType(refersToId);
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case TYPEVAR: {
if (type instanceof Type.CapturedType) {
ret = visit(((Type.CapturedType) type).wildcard);
} else {
int refersToId = 0;
Integer ref = symMaps.getTypeParameterMap().get(type);
if (ref == null) {
// if we reach this, than check the type parameters of the owner symbol
// it should be a Symbol.MethodSymbol and its type should be Type.ForAll
Type ownerType = type.tsym.owner.type;
for (Type tv : ownerType.getTypeArguments()) {
if (type.tsym.name.toString().equals(tv.tsym.name.toString())) {
ref = symMaps.getTypeParameterMap().get(tv);
break;
}
}
}
if (ref == null) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TypeBuilder.typeParamCouldntBeFound", type, type.tsym.owner);
}
} else {
refersToId = ref;
}
TypeVariable typeNode = fact.createTypeVariable(refersToId);
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
}
break;
}
case UNION: {
List<Integer> alternativeIds = new ArrayList<>();
Type.UnionClassType t = (Type.UnionClassType) type;
for (TypeMirror alt : t.getAlternatives()) {
alternativeIds.add(visit((Type) alt));
}
UnionType typeNode = fact.createUnionType(alternativeIds);
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case WILDCARD: {
com.sun.tools.javac.code.Type.WildcardType wildcardType = (com.sun.tools.javac.code.Type.WildcardType) type;
WildcardType typeNode = null;
int boundId = 0;
if (wildcardType.kind == BoundKind.EXTENDS) {
boundId = visit(wildcardType.getExtendsBound());
typeNode = fact.createUpperBoundedWildcardType(boundId);
} else if (wildcardType.kind == BoundKind.SUPER) {
boundId = visit(wildcardType.getSuperBound());
typeNode = fact.createLowerBoundedWildcardType(boundId);
} else if (wildcardType.kind == BoundKind.UNBOUND) {
boundId = visit(wildcardType.type);
typeNode = fact.createUnboundedWildcardType(boundId);
} else {
throw new JavaException(logger.formatMessage("ex.jan.TypeBuilder.invalidWildcardType"));
}
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case DECLARED: {
ScopedType typeNode;
int ownerId = 0;
int refersToId = 0;
List<Integer> argumentTypeIds = null;
int rawTypeId = 0;
if (type.getTypeArguments().isEmpty()) {
for (Map.Entry<Symbol, Integer> entry : classSymbolMap.entrySet()) {
if (type.tsym == entry.getKey().type.tsym) {
refersToId = entry.getValue();
break;
}
}
if (refersToId == 0) {
logger.debug("debug.jan.TypeBuilder.refIsntStored", type);
}
} else {
Type erased = type.tsym.erasure_field;
if (erased == null) {
//Java 10 support
erased = new Type.ErasedClassType(type, type.tsym, type.getMetadata());
}
rawTypeId = visit(erased);
argumentTypeIds = new ArrayList<>();
for (Type type_arg : type.getTypeArguments()) {
argumentTypeIds.add(visit(type_arg));
}
}
Symbol sym = type.tsym.owner;
while (!(sym instanceof ClassSymbol) && !(sym instanceof PackageSymbol)) {
sym = sym.owner;
}
ownerId = visit(sym.type);
if (type.getTypeArguments().isEmpty()) {
typeNode = fact.createClassType(ownerId, refersToId);
} else {
typeNode = fact.createParameterizedType(ownerId, rawTypeId, argumentTypeIds);
}
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case EXECUTABLE: {
int returnTypeId = 0;
List<Integer> parameterTypeIds = new ArrayList<>();
List<Integer> thrownTypeIds = new ArrayList<>();
returnTypeId = visit(type.getReturnType());
for (Type t : type.getParameterTypes()) {
parameterTypeIds.add(visit(t));
}
for (Type t : type.getThrownTypes()) {
thrownTypeIds.add(visit(t));
}
MethodType typeNode = fact.createMethodType(returnTypeId, parameterTypeIds, thrownTypeIds);
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case NONE: {
NoType typeNode = fact.createNoType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case OTHER:
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.TypeBuilder.otherType", type);
}
if (type instanceof DelegatedType) {
DelegatedType delegated = ((DelegatedType) type);
ret = visit(delegated.qtype);
} else if (type instanceof UnknownType) {
// TODO java 1.8 (Type.UnknownType e.g. <any?>)
logger.debug("ex.jan.TypeBuilder.errorTypeInsteadOfJava18Type", type.getKind());
ErrorType typeNode = fact.createErrorType();
ret = typeNode.getId();
builtTypeSymbols.put(type, ret);
} else {
throw new JavaException(logger.formatMessage("ex.jan.TypeBuilder.unknownTypeKind", type.getKind()));
}
break;
case INTERSECTION: {
Type.IntersectionClassType intersectionType = (Type.IntersectionClassType) type;
IntersectionType intersectionTypeNode = (IntersectionType) fact.createNode(NodeKind.ndkIntersectionType);
intersectionType.getBounds().forEach(bound -> intersectionTypeNode.addBounds(visit((Type) bound)));
ret = intersectionTypeNode.getId();
builtTypeSymbols.put(type, ret);
break;
}
case MODULE:
Integer retId = symMaps.getModuleTypeMap().get(type);
if (retId != null) {
builtTypeSymbols.put(type, retId);
ret = retId;
}
break;
default:
throw new JavaException(logger.formatMessage("ex.jan.TypeBuilder.unknownTypeKind", type.getKind()));
}
}
} catch (NullPointerException e) {
logger.error("error.jan.TypeBuilder.nodeTypeWasNull", e);
} catch (Exception e) {
logger.error("error.jan.TypeBuilder.couldntBuildTheType", type.getKind(), type, e);
}
return ret;
}
}
| 15,207 | 29.910569 | 113 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/CommentBuilder.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;
import columbus.java.asg.EdgeIterator;
import columbus.java.asg.Factory;
import columbus.java.asg.JavaException;
import columbus.java.asg.Range;
import columbus.java.asg.algorithms.AlgorithmPreorder;
import columbus.java.asg.base.Base;
import columbus.java.asg.base.Commentable;
import columbus.java.asg.base.Positioned;
import columbus.java.asg.struc.CompilationUnit;
import columbus.java.asg.struc.Import;
import columbus.java.asg.struc.Member;
import columbus.java.asg.struc.PackageDeclaration;
import columbus.java.asg.struc.TypeDeclaration;
import columbus.java.asg.visitors.Visitor;
import columbus.java.asg.visitors.VisitorAbstractNodes;
import columbus.logger.LoggerHandler;
import com.sun.tools.javac.parser.JANComment;
import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle;
public class CommentBuilder extends Visitor {
private static final LoggerHandler logger = new LoggerHandler(CommentBuilder.class, OptionParser.getLoggerPropertyFile());
private Factory factory;
private AlgorithmPreorder ap, subAP;
private HashMap<String, ArrayList<JANComment>> comments;
private TreeMap<Interval, ArrayList<Positioned>> map, endMap;
static class Interval
{
private int fromLine;
private int fromCol;
private int toLine;
private int toCol;
public Interval(int fromLine, int fromCol, int toLine, int toCol) {
this.fromLine = fromLine;
this.fromCol = fromCol;
this.toLine = toLine;
this.toCol = toCol;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + fromCol;
result = prime * result + fromLine;
result = prime * result + toCol;
result = prime * result + toLine;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Interval other = (Interval) obj;
if (fromCol != other.fromCol)
return false;
if (fromLine != other.fromLine)
return false;
if (toCol != other.toCol)
return false;
if (toLine != other.toLine)
return false;
return true;
}
public int getFromLine() {
return fromLine;
}
public void setFromLine(int fromLine) {
this.fromLine = fromLine;
}
public int getFromCol() {
return fromCol;
}
public void setFromCol(int fromCol) {
this.fromCol = fromCol;
}
public int getToLine() {
return toLine;
}
public void setToLine(int toLine) {
this.toLine = toLine;
}
public int getToCol() {
return toCol;
}
public void setToCol(int toCol) {
this.toCol = toCol;
}
public String toString()
{
return "([" + fromLine + "," + fromCol + "]->[" + toLine + "," + toCol + "])";
}
}
static class FromComparator implements Comparator<Interval>
{
@Override
public int compare( Interval a, Interval b )
{
if ( a.fromLine < b.fromLine ) return -1;
if ( a.fromLine > b.fromLine ) return 1;
if ( a.fromCol < b.fromCol ) return -1;
if ( a.fromCol > b.fromCol ) return 1;
return 0;
}
}
static class ToComparator implements Comparator<Interval>
{
@Override
public int compare( Interval a, Interval b )
{
if ( a.toLine < b.toLine ) return -1;
if ( a.toLine > b.toLine ) return 1;
if ( a.toCol < b.toCol ) return -1;
if ( a.toCol > b.toCol ) return 1;
return 0;
}
}
static class PositionedStartComparator implements Comparator<Positioned>
{
@Override
public int compare( Positioned a, Positioned b )
{
Range posA = a.getPosition();
Range posB = b.getPosition();
if ( posA.getWideLine() < posB.getWideLine() ) return -1;
if ( posA.getWideLine() > posB.getWideLine() ) return 1;
if ( posA.getWideCol() < posB.getWideCol() ) return -1;
if ( posA.getWideCol() > posB.getWideCol() ) return 1;
return 0;
}
}
static class PositionedEndComparator implements Comparator<Positioned>
{
@Override
public int compare( Positioned a, Positioned b )
{
Range posA = a.getPosition();
Range posB = b.getPosition();
if ( posA.getWideEndLine() < posB.getWideEndLine() ) return -1;
if ( posA.getWideEndLine() > posB.getWideEndLine() ) return 1;
if ( posA.getWideEndCol() < posB.getWideEndCol() ) return -1;
if ( posA.getWideEndCol() > posB.getWideEndCol() ) return 1;
return 0;
}
}
protected class SubTreeVisitor extends VisitorAbstractNodes
{
@Override
public void visit( Positioned p, boolean callVirtualBase )
{
push( p );
}
}
public CommentBuilder( Factory factory, HashMap<String, ArrayList<JANComment>> commentMap )
{
this.factory = factory;
this.comments = commentMap;
this.ap = new AlgorithmPreorder();
this.subAP = new AlgorithmPreorder();
this.subAP.setVisitSpecialNodes(false, false); // traverse only the subtree and skip ap_spec nodes
this.map = new TreeMap<Interval, ArrayList<Positioned>>( new FromComparator() );
this.endMap = new TreeMap<Interval, ArrayList<Positioned>>( new ToComparator() );
}
private void push( Positioned p )
{
if ( p == null )
{
return;
}
Range position = p.getPosition();
Interval i = new Interval
(
position.getWideLine()
, position.getWideCol()
, position.getWideEndLine()
, position.getWideEndCol()
);
if ( ! map.containsKey(i) )
{
map.put( i, new ArrayList<Positioned>() );
}
map.get( i ).add( p );
if ( ! endMap.containsKey(i) )
{
endMap.put( i, new ArrayList<Positioned>() );
}
endMap.get( i ).add( p );
}
@Override
public void visit( CompilationUnit cu, boolean callVirtualBase )
{
// Processing the imports
for( EdgeIterator<Import> i = cu.getImportsIterator(); i.hasNext(); )
{
push( i.next() );
}
// Processing the package declaration
push( cu.getPackageDeclaration() );
// Processing all TypeDeclarations by visiting their subtrees
SubTreeVisitor stv = new SubTreeVisitor();
for ( EdgeIterator<TypeDeclaration> i = cu.getTypeDeclarationsIterator(); i.hasNext(); )
{
TypeDeclaration next = i.next();
subAP.run( factory, stv, next );
}
// Building the Comments in this CompilationUnit
buildCU( cu );
// Clearing the maps
map.clear();
endMap.clear();
}
public void build()
{
ap.run( factory, this );
}
private void buildCU( CompilationUnit cu )
{
String fileKey = cu.getPosition().getPath();
if ( comments.containsKey( fileKey ) )
{
ArrayList<JANComment> fileComments = comments.get( fileKey );
for ( JANComment fileComment : fileComments )
{
// get a Range from the positions of the comment
Range position = new Range( factory.getStringTable() );
position.setPathKey( cu.getPosition().getPathKey() );
int line = (int) fileComment.line();
int col = (int) fileComment.col();
int endLine = (int) fileComment.endLine();
int endCol = (int) fileComment.endCol();
position.setCol( col );
position.setWideCol( col );
position.setEndCol( endCol );
position.setWideEndCol( endCol );
position.setLine( line );
position.setWideLine( line );
position.setEndLine( endLine );
position.setWideEndLine( endLine );
// we search the relevant Positioned node to attach the comment to
// before
ArrayList<Positioned> pre = null;
Entry<Interval, ArrayList<Positioned>> preEntry = map.lowerEntry( new Interval( line, col, 0, 0 ) );
if ( preEntry != null)
{
pre = preEntry.getValue();
}
ArrayList<Positioned> preEnd = null;
Entry<Interval, ArrayList<Positioned>> preEndEntry = endMap.lowerEntry( new Interval( 0, 0, endLine, endCol ) );
if ( preEndEntry != null)
{
preEnd = preEndEntry.getValue();
}
// after
ArrayList<Positioned> post = null;
Entry<Interval, ArrayList<Positioned>> postEntry = map.higherEntry( new Interval( endLine, endCol, 0, 0 ) );
if ( postEntry != null)
{
post = postEntry.getValue();
}
ArrayList<Positioned> postEnd = null;
Entry<Interval, ArrayList<Positioned>> postEndEntry = endMap.higherEntry( new Interval( 0, 0, endLine, endCol ) );
if ( postEndEntry != null)
{
postEnd = postEndEntry.getValue();
}
// the node that starts right before this is not in the same scope
// if it also starts after something that ends right before the current node
boolean preIsInOtherScope = false;
if ( pre != null && preEnd != null )
{
Interval firstStart = preEntry.getKey();
// transfer Tos to Froms for comparison
Interval firstEnd = new Interval(
preEndEntry.getKey().getToLine()
, preEndEntry.getKey().getToCol()
, 0, 0
);
if ( new FromComparator().compare(firstEnd, firstStart) < 0 )
{
preIsInOtherScope = true;
}
}
// the node that starts right after this is not in the same scope
// if it also starts after something that encloses the current node
boolean postIsInOtherScope = false;
if ( post != null && postEnd != null )
{
Interval firstStart = postEntry.getKey();
// transfer Tos to Froms for comparison
Interval firstEnd = new Interval(
postEndEntry.getKey().getToLine()
, postEndEntry.getKey().getToCol()
, 0, 0
);
if ( new FromComparator().compare(firstEnd, firstStart) < 0 )
{
postIsInOtherScope = true;
}
}
/*
* Javadocs are supposed to immediately precede a Member
* if that's the case, it gets attached
* if not, it's treated as a simple block comment
*/
if ( fileComment.style() == CommentStyle.JAVADOC )
{
if ( post != null )
{
Commentable toNode = null;
boolean packageInfo = cu.getPosition().getPath().endsWith("package-info.java");
for ( Positioned p : post )
{
if ( packageInfo && p instanceof PackageDeclaration )
{
// Separate treatment for package-level comments
toNode = ((PackageDeclaration)p).getRefersTo();
break;
}
else if ( p instanceof Member )
{
toNode = p;
break;
}
}
if ( toNode != null )
{
attach( toNode, fileComment, position );
continue;
}
}
fileComment.style( CommentStyle.BLOCK );
}
/*
* A line comment (in our estimation) belongs to:
* - (1) either the "highest rank" preceding node, while it's on the same line
* - (2) or the highest rank node immediately following the comment ( if it's in the same scope )
* - (3) if there's nothing on the same line or after, then the node before (wherever it is)
* - (4) if there's nothing before of after, the comment gets attached to the CU itself
*/
if ( fileComment.style() == CommentStyle.LINE )
{
Commentable node = null;
Positioned temp = null;
if ( pre != null )
{
Collections.sort( pre, new PositionedEndComparator() );
temp = pre.get( pre.size() - 1 );
if ( temp.getPosition().getWideLine() == line )
{
node = highestInLine( temp, line ); // (1)
}
else if ( (post == null || postIsInOtherScope) )
{
if ( preIsInOtherScope )
{
node = highestInLine( temp, temp.getPosition().getWideLine() ); // (3)
}
else if ( preEnd != null )
{
Collections.sort( preEnd, new PositionedStartComparator() );
node = preEnd.get( 0 ); // (3)
}
}
}
if ( node == null && post != null )
{
Collections.sort( post, new PositionedEndComparator() );
node = post.get( post.size() - 1 ); // (2)
}
if ( node == null )
{
node = cu; // (4)
}
attach( node, fileComment, position );
continue;
}
/*
* The same applies to a block comment (or a degraded javadoc), only if the
* node is in the same line (preceding the comment), the "highest rank" search
* is modified so that the comment gets attached to the highest rank node that
* ENDS immediately before it.
* For example:
*
* for ( int i = 1; / * starts at 1 because 0 is invalid * / i < max; ++i ) { ... }
*
* In this case the comment belongs to the assignment, not the for statement.
*/
if ( fileComment.style() == CommentStyle.BLOCK )
{
Commentable node = null;
if ( preEnd != null && ! preIsInOtherScope )
{
Collections.sort( preEnd, new PositionedStartComparator() );
Positioned temp = preEnd.get( 0 );
if ( temp.getPosition().getWideLine() == line || post == null || postIsInOtherScope )
{
node = temp; // (1,3)
}
}
if ( node == null && pre != null && ( post == null || postIsInOtherScope ) )
{
Collections.sort( pre, new PositionedEndComparator() );
node = pre.get( pre.size() - 1 ); // (3)
}
if ( node == null && post != null )
{
Collections.sort( post, new PositionedEndComparator() );
node = post.get( post.size() - 1 ); // (2)
}
if ( node == null )
{
node = cu; // (4)
}
attach( node, fileComment, position );
}
}
}
comments.remove( fileKey );
}
private void attach( Commentable target, JANComment c, Range r )
{
columbus.java.asg.base.Comment node;
String text = c.text();
// we build the corresponding Comment node
switch( c.style() )
{
case LINE:
node = factory.createLineComment(r, text);
break;
case BLOCK:
node = factory.createBlockComment(r, text);
break;
case JAVADOC:
node = factory.createJavadocComment(r, text);
break;
default:
throw new JavaException(logger.formatMessage("ex.jan.CommentBuilder.unknownCommentStyle", c.style()));
}
// and attach it to the Positioned node where it (most likely) belongs
target.addComments( node );
}
private Positioned highestInLine( Positioned p, int line )
{
Positioned result = null;
do
{
result = p;
Base parent = p.getParent();
if ( parent == null ) break;
if ( ! ( parent instanceof Positioned ) ) break;
p = (Positioned) parent;
}
while ( p.getPosition().getWideLine() == line );
return result;
}
}
| 15,165 | 27.033272 | 123 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/JDKTreeMaker.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.tools.JavaFileObject;
import com.glaforge.i18n.io.CharsetToolkit;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import columbus.logger.LoggerHandler;
class CompilerLogger extends Writer {
private static final LoggerHandler logger = new LoggerHandler(CompilerLogger.class,
OptionParser.getLoggerPropertyFile());
private static final String eol = System.getProperty("line.separator");
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
String str = new String(cbuf, off, len);
if (!str.equals(eol)) {
logger.info("info.jan.CompilerLogger.compilerMessage", str);
}
}
@Override
public void flush() throws IOException {
}
@Override
public void close() throws IOException {
}
}
public class JDKTreeMaker {
private static final LoggerHandler logger = new LoggerHandler(JDKTreeMaker.class,
OptionParser.getLoggerPropertyFile());
private Context context = null;
public List<CompilationUnitTree> build(List<File> files, List<String> options) {
List<CompilationUnitTree> tree = null;
JavacTool compiler = JavacTool.create();
if (logger.isInfoEnabled()) {
logger.info("info.jan.JDKTreeMaker.javacOptions");
for (String o : options) {
logger.info("info.jan.JDKTreeMaker.javacOption", o);
}
}
Iterable<? extends JavaFileObject> fileObjects = getFileObjects(files, compiler);
Writer writer = new CompilerLogger();
JavacTaskImpl javacTask = (JavacTaskImpl) compiler.getTask(writer, null, null, options, null, fileObjects);
Iterable<? extends CompilationUnitTree> trees = null;
try {
trees = javacTask.parse();
} catch (Exception e) {
logger.error("error.jan.JDKTreeMaker.javacParseError", e);
System.exit(1);
}
tree = new ArrayList<>();
for (CompilationUnitTree t : trees) {
tree.add(t);
}
try {
javacTask.analyze();
} catch (Exception e) {
logger.error("error.jan.JDKTreeMaker.javacAnalyzeError", e);
System.exit(1);
}
context = javacTask.getContext();
return tree;
}
@SuppressWarnings("unchecked")
private Iterable<? extends JavaFileObject> getFileObjects(List<File> files, JavacTool compiler) {
Charset charset = null;
Charset defaultEncoding = Charset.defaultCharset();
Iterable<? extends JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
if (OptionParser.encoding == null) {
if (OptionParser.wrappedMode) {
charset = defaultEncoding;
logger.info("info.jan.JDKTreeMaker.defaultFileEncoding", charset.toString());
fileObjects = getFileObjectsWithEncoding(files, compiler, charset);
} else {
// FIXME restore if we found a solution for PMD
boolean detectEncoding = false;
if (detectEncoding) {
for (File javaFile : files) {
try {
byte[] buffer = new byte[4096];
BufferedInputStream br = new BufferedInputStream(new FileInputStream(javaFile));
br.read(buffer);
CharsetToolkit detector = new CharsetToolkit(buffer, defaultEncoding);
detector.setEnforce8Bit(true);
charset = detector.guessEncoding();
br.close();
ArrayList<File> singleList = new ArrayList<>();
singleList.add(javaFile);
Iterable<? extends JavaFileObject> l = getFileObjectsWithEncoding(singleList, compiler,
charset);
((ArrayList<JavaFileObject>) fileObjects).addAll((ArrayList<JavaFileObject>) l);
} catch (IOException e) {
logger.error("error.jan.JDKTreeMaker.IOErrorWhileGuessEncoding", e);
System.exit(1);
}
}
} else {
fileObjects = getFileObjectsWithEncoding(files, compiler, defaultEncoding);
}
}
} else {
try {
charset = Charset.forName(OptionParser.encoding);
} catch (Exception e) {
logger.error("error.jan.JDKTreeMaker.cantCreateCharSet", OptionParser.encoding, e);
System.exit(1);
}
fileObjects = getFileObjectsWithEncoding(files, compiler, charset);
}
return fileObjects;
}
private Iterable<? extends JavaFileObject> getFileObjectsWithEncoding(List<File> files, JavacTool compiler,
Charset charset) {
JavacFileManager fileManager = compiler.getStandardFileManager(null, null, charset);
Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromFiles(files);
return fileObjects;
}
public Context getContext() {
return context;
}
}
| 5,491 | 28.847826 | 109 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/CrossEdges.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.lang.model.type.TypeKind;
import org.jan.SymbolMaps.EdgeType;
import columbus.java.asg.Common;
import columbus.java.asg.Factory;
import columbus.java.asg.algorithms.AlgorithmPreorder;
import columbus.java.asg.base.Base;
import columbus.java.asg.enums.NodeKind;
import columbus.java.asg.expr.Identifier;
import columbus.java.asg.expr.MemberReference;
import columbus.java.asg.expr.MethodInvocation;
import columbus.java.asg.expr.NewClass;
import columbus.java.asg.statm.Break;
import columbus.java.asg.statm.Continue;
import columbus.java.asg.statm.Jump;
import columbus.java.asg.statm.LabeledStatement;
import columbus.java.asg.statm.Statement;
import columbus.java.asg.struc.MethodDeclaration;
import columbus.java.asg.visitors.Visitor;
import columbus.logger.LoggerHandler;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.util.Context;
public class CrossEdges {
private static final LoggerHandler logger = new LoggerHandler(CrossEdges.class,
OptionParser.getLoggerPropertyFile());
private Factory fact;
private SymbolMaps symMaps;
private Types types;
public CrossEdges(Factory fact, SymbolMaps symMaps, Context context) {
this.fact = fact;
this.symMaps = symMaps;
types = Types.instance(context);
}
public void setCrossEdges() {
logger.debug("debug.jan.CrossEdges.setMethodInvsTarget");
connectEdges(symMaps.getMethodDeclarationMap(), symMaps.getMethodInvMap(), EdgeType.METHOD);
logger.debug("debug.jan.CrossEdges.setNewClassConstr");
connectEdges(symMaps.getMethodDeclarationMap(), symMaps.getNewClassConstructorMap(), EdgeType.NEWCLASS);
logger.debug("debug.jan.CrossEdges.setMemberRef");
//Connecting the referred method to the member reference node.
connectEdges(symMaps.getMethodDeclarationMap(), symMaps.getMemberReferenceMap(), EdgeType.MEMBER_REF);
logger.debug("debug.jan.CrossEdges.setIdsTarget");
Map<Symbol, Integer> idTargetMap = new LinkedHashMap<>(symMaps.getVariableDeclarationMap());
idTargetMap.putAll(symMaps.getInnerTypeDeclarationMap());
idTargetMap.putAll(symMaps.getExternalTypeDeclarationMap());
idTargetMap.putAll(symMaps.getMethodDeclarationMap());
idTargetMap.putAll(symMaps.getPackageMap());
Map<Integer, Symbol> idRefMap = new LinkedHashMap<>();
Iterator<Entry<Integer, Symbol>> iter = symMaps.getIdMapIterator();
while (iter.hasNext()) {
Entry<Integer, Symbol> entry = iter.next();
idRefMap.put(entry.getKey(), entry.getValue());
}
connectEdges(idTargetMap, idRefMap, EdgeType.ID);
logger.debug("debug.jan.CrossEdges.setJumpsTarget");
connectJumps();
logger.debug("debug.jan.CrossEdges.setOverrideEdges");
connectOverrides();
}
private void connectOverrides() {
for (Entry<Symbol, Integer> method : symMaps.getMethodDeclarationMap().entrySet()) {
MethodSymbol methodSym = (MethodSymbol) method.getKey();
ClassSymbol ownerClass = (ClassSymbol) methodSym.owner;
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.CrossEdges.methodInfo", ownerClass.toString(), methodSym.toString());
}
HashSet<ClassSymbol> visitedInterfaces = new HashSet<ClassSymbol>();
visitOverrideSuperClasses(methodSym, method.getValue(), ownerClass, visitedInterfaces);
}
}
private void visitOverrideSuperClasses(MethodSymbol methodSym, Integer id, ClassSymbol classSym,
HashSet<ClassSymbol> visitedInterfaces) {
boolean foundClassOverride = false;
boolean foundInterfaceOverride;
HashSet<ClassSymbol> visitedClasses = new HashSet<ClassSymbol>();
while (!foundClassOverride && classSym != null) {
if (!visitedClasses.add(classSym)) {
break;
}
// super classes
if (!foundClassOverride) {
foundClassOverride = checkMethodOverrides(methodSym, id, (ClassSymbol) classSym.getSuperclass().tsym);
}
// super interfaces
Iterator<Type> it = classSym.getInterfaces().iterator();
while (it.hasNext()) {
ClassSymbol interfaceSym = (ClassSymbol) it.next().tsym;
if (!visitedInterfaces.add(interfaceSym)) {
continue;
}
foundInterfaceOverride = checkMethodOverrides(methodSym, id, interfaceSym);
if (!foundInterfaceOverride) {
visitOverrideSuperClasses(methodSym, id, interfaceSym, visitedInterfaces);
}
}
classSym = (ClassSymbol) classSym.getSuperclass().tsym;
}
}
private boolean checkMethodOverrides(MethodSymbol methodSym, Integer id, ClassSymbol classSym) {
// superclass of interface
if (classSym == null) {
return false;
}
for (Symbol enclosed : classSym.getEnclosedElements()) {
// Java 10 support
if (enclosed.kind == Kinds.Kind.MTH && methodSym.name.toString().equals(enclosed.name.toString()) ) {
if (methodSym.overrides(enclosed, classSym, types, true)) {
MethodDeclaration methodDeclaration = (MethodDeclaration) fact.getRef(id);
Integer overridedMethodId = symMaps.getMethodDeclarationMap().get(enclosed);
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.CrossEdges.setOverrideEdge", classSym.toString(), enclosed.toString());
}
// for example the method is not built when we don't need to fully build an external class
if (overridedMethodId != null) {
methodDeclaration.addOverrides(overridedMethodId);
} else if (OptionParser.buildAllParentForOverrides) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.CrossEdges.overridenMethodNotBuilded", methodSym.owner.toString(),
classSym.toString(), enclosed.toString());
}
}
return true;
}
}
}
return false;
}
private void connectEdges(Map<Symbol, Integer> declarationMap, Map<Integer, Symbol> referenceMap, EdgeType e) {
for (Entry<Integer, Symbol> refEntry : referenceMap.entrySet()) {
try {
Symbol refSym = refEntry.getValue();
Integer refId = refEntry.getKey();
if (refSym == null || refId == 0) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.CrossEdges.refSymError", refSym, refId);
}
continue;
}
Integer declId = null;
if (refSym instanceof PackageSymbol)
declId = symMaps.findPackage((PackageSymbol) refSym);
else
declId = declarationMap.get(refSym);
if (declId == null) {
tryToConnectByName(declarationMap, refSym, refId, e);
continue;
}
switch (e) {
case METHOD:
try {
MethodInvocation methodInvocationNode = (MethodInvocation) fact.getRef(refId);
methodInvocationNode.setInvokes(declId);
} catch (Exception ex) {
logger.error("error.jan.CrossEdges.errorInCrossEdges", ex);
}
break;
case NEWCLASS:
NewClass newClassNode = (NewClass) fact.getRef(refId);
newClassNode.setConstructor(declId);
break;
case ID:
Base base = fact.getRef(refId);
if (base.getNodeKind() == NodeKind.ndkIdentifier) {
((Identifier) base).setRefersTo(declId);
}
break;
case MEMBER_REF:
try {
//Connect the crossedge to the member reference node.
MemberReference memberRefNode = (MemberReference) fact.getRef(refId);
memberRefNode.setReferredMethod(declId);
} catch (Exception ex) {
logger.error("error.jan.CrossEdges.errorInCrossEdges", ex);
}
break;
default:
logger.error("error.jan.CrossEdges.notHandledCrossEdgeType");
break;
}
} catch (Exception ex) {
logger.error("error.jan.CrossEdges.errorInCrossEdges", ex);
}
}
}
private void tryToConnectByName(Map<Symbol, Integer> declarationMap, Symbol refSym, Integer refId, EdgeType e) {
Symbol decl = null;
decl = visitSuperClassesForConnectByName(declarationMap, refSym, refSym.owner);
if (decl == null) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.CrossEdges.cantFindTheEndOfCrossedge", refId);
}
return;
}
Integer id = declarationMap.get(decl);
if (id == null){
// cant connect the crossedge
return;
}
switch (e) {
case METHOD:
MethodInvocation methodInvocationNode = (MethodInvocation) fact.getRef(refId);
methodInvocationNode.setInvokes(id);
break;
case NEWCLASS:
NewClass newClassNode = (NewClass) fact.getRef(refId);
newClassNode.setConstructor(id);
break;
case ID:
Base base = fact.getRef(refId);
if (base == null) {
return;
}
if (base.getNodeKind() == NodeKind.ndkIdentifier) {
((Identifier) base).setRefersTo(id);
}
break;
case MEMBER_REF:
MemberReference memberRefNode = (MemberReference) fact.getRef(refId);
memberRefNode.setReferredMethod(id);
break;
default:
logger.error("error.jan.CrossEdges.notHandledCrossEdgeType");
break;
}
}
public Symbol visitSuperClassesForConnectByName(Map<Symbol, Integer> declarationMap, Symbol refSym, Symbol parent) {
Symbol decl = null;
if (parent != null && parent.type.getKind() == TypeKind.DECLARED) {
decl = tryConnectParentByName(declarationMap, refSym, parent);
if (decl == null) {
for (Type t : ((ClassSymbol) parent).getInterfaces()) {
decl = tryConnectParentByName(declarationMap, refSym, t.tsym);
if (decl != null) {
break;
} else {
decl = visitSuperClassesForConnectByName(declarationMap, refSym, t.tsym);
}
}
}
if (decl == null) {
decl = visitSuperClassesForConnectByName(declarationMap, refSym,
((ClassSymbol) parent).getSuperclass().tsym);
}
}
return decl;
}
public Symbol tryConnectParentByName(Map<Symbol, Integer> declarationMap, Symbol refSym, Symbol parent) {
if (parent.type.getKind() == TypeKind.NONE) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.CrossEdges.wrongTypeOfSymbol", parent.type);
}
return null;
}
Symbol decl = null;
for (Symbol s : parent.getEnclosedElements()) {
if (s.getQualifiedName().equals(refSym.getQualifiedName())) {
decl = s;
}
}
return decl;
}
private void connectJumps() {
AlgorithmPreorder algPre = new AlgorithmPreorder();
Visitor vis = new Visitor() {
@Override
public void visit(Break node, boolean callVirtualBase) {
super.visit(node, callVirtualBase);
connectToLoop((Jump) node);
}
@Override
public void visit(Continue node, boolean callVirtualBase) {
connectToLoop((Jump) node);
super.visit(node, callVirtualBase);
}
private void connectToLoop(Jump jump) {
Base parent = jump.getParent();
while (true) {
if (parent == null) {
break;
}
if (jump.getLabelKey() != 0) {
if (Common.getIsLabeledStatement(parent)) {
LabeledStatement labeled = (LabeledStatement) parent;
if (labeled.getLabelKey() == jump.getLabelKey()) {
jump.setTarget(labeled);
break;
}
}
} else {
if (Common.getIsIteration(parent) || Common.getIsSwitch(parent)) {
jump.setTarget((Statement) parent);
break;
}
}
parent = parent.getParent();
}
}
};
algPre.run(fact, vis);
}
}
| 12,067 | 30.023136 | 117 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/JANCmdLine.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.util.List;
import com.lexicalscope.jewel.cli.CommandLineInterface;
import com.lexicalscope.jewel.cli.Option;
@CommandLineInterface(application = "JAN")
public interface JANCmdLine {
@Option(shortName = "i", description = "The input file(s) or directory(ies)")
List<String> getInput();
boolean isInput();
@Option(shortName = "a", description = "JAN options.")
String getJanoptions();
boolean isJanoptions();
@Option(shortName = "d", description = "The output directory for .jsi classes.")
String getOutputdir();
boolean isOutputdir();
@Option(shortName = "e", description = "The output directory for extra .jsi file.")
String getExtrajsidir();
boolean isExtrajsidir();
@Option(shortName = "o", description = "The output .jsi file.")
String getOutputjsi();
boolean isOutputjsi();
@Option(shortName = "x", description = "The output .xml file.")
String getOutputxml();
boolean isOutputxml();
@Option(shortName = "y", description = "Dump minimal xml file")
boolean isMinXml();
@Option(shortName = "j", description = "The extra arguments for javac.")
String getJavacoptions();
boolean isJavacoptions();
@Option(shortName = "c", description = "The config.ini file.")
String getConfigfile();
boolean isConfigfile();
@Option(shortName = "l", description = "The name of the jsi list file.")
String getJsilistfile();
boolean isJsilistfile();
@Option(shortName = "f", description = "Javac Argument files")
List<String> getJavacargumentfiles();
boolean isJavacargumentfiles();
@Option(shortName = "s", description = "The name of the source list file")
String getAnalyzedsourcelist();
boolean isAnalyzedsourcelist();
@Option(shortName = "u", description = "The name of the classpath list file")
String getUsedclasspathlist();
boolean isUsedclasspathlist();
@Option(shortName = "t", description = "The path of the statistic file.")
String getStatisticfile();
boolean isStatisticfile();
@Option(shortName = "w", description = "The path of the current working directory.")
String getWorkingdirectory();
boolean isWorkingdirectory();
@Option(shortName = "p", hidden = true, description = "Don't set it manually")
boolean isWrappedmode();
@Option(shortName = "r", hidden = true, description = "Don't set it manually")
boolean isDirecotryAnalyzeMode();
@Option(shortName = "g", hidden = true, description = "Don't set it manually")
boolean isDevelopermode();
@Option(shortName = "h", description = "The path of the hard filter file.")
String getHardfilter();
boolean isHardfilter();
@Option(shortName = "v", description = "Print version informations.")
boolean isVersion();
@Option(shortName = "m", description = "The log level from 0 to 3, ( silent, error, warn, info).")
int getMessagelevel();
boolean isMessagelevel();
}
| 3,551 | 31 | 99 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/ClassSaver.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.io.File;
import columbus.CsiHeader;
import columbus.StrTable.StrType;
import columbus.java.asg.Common;
import columbus.java.asg.Factory;
import columbus.java.asg.Factory.Iterator;
import columbus.java.asg.algorithms.AlgorithmPreorder;
import columbus.java.asg.base.Base;
import columbus.java.asg.enums.NodeKind;
import columbus.java.asg.struc.Package;
import columbus.java.asg.struc.TypeDeclaration;
import columbus.java.asg.visitors.VisitorJAVAML;
import columbus.java.asg.visitors.VisitorSpecFilter;
import columbus.logger.LoggerHandler;
public class ClassSaver {
private static final LoggerHandler logger = new LoggerHandler(ClassSaver.class,
OptionParser.getLoggerPropertyFile());
public static void saveMinXml(Factory fact, String xmlPath) {
AlgorithmPreorder preorder = new AlgorithmPreorder();
preorder.setVisitSpecialNodes(false, false);
VisitorSpecFilter visitor = new VisitorSpecFilter(fact);
fact.turnFilterOff();
Iterator it = fact.iterator();
while (it.hasNext()) {
Base node = it.next();
if (node.getParent() != null &&
((Common.getIsTypeDeclaration(node) && Common.getIsPackage(node.getParent()) && ((TypeDeclaration) node).getIsInCompilationUnit() != null) ||
Common.getIsCompilationUnit(node))
) {
visitor.addRoot(node);
if (Common.getIsTypeDeclaration(node))
visitor.addRef(((TypeDeclaration) node).getIsInCompilationUnit());
}
}
visitor.run();
visitor.createFilter();
fact.turnFilterOn();
saveToXml(fact, xmlPath);
visitor.restoreStrTable();
}
public static void saveClasses(Factory fact, String outDir, String extraAsg, CsiHeader header) {
AlgorithmPreorder preorder = new AlgorithmPreorder();
preorder.setVisitSpecialNodes(false, false);
VisitorSpecFilter visitor = new VisitorSpecFilter(fact);
// determining the path of the extra jsi
if (extraAsg == null) {
logger.error("error.jan.ClassSaver.missingDirectoryOfExtraAsg");
} else {
int no = 0;
while (new File(extraAsg, "extra" + (++no) + ".jsi").exists())
;
extraAsg += File.separator + "extra" + no;
}
fact.turnFilterOff();
Iterator it = fact.iterator();
while (it.hasNext()) {
fact.turnFilterOff();
Base node = it.next();
if (node.getParent() == null || !Common.getIsTypeDeclaration(node)
|| node.getParent().getNodeKind() != NodeKind.ndkPackage
|| ((TypeDeclaration) node).getIsInCompilationUnit() == null) {
continue;
}
visitor.init();
visitor.addRoot(node);
visitor.addRef(((TypeDeclaration) node).getIsInCompilationUnit());
visitor.run();
visitor.createFilter();
fact.turnFilterOn();
String path = "";
if (outDir == null) {
String tmpPath = ((TypeDeclaration) node).getPosition().getPath();
String parent = new File(tmpPath).getParent();
path = (parent != null ? parent : ".") + File.separator;
} else {
path = outDir + File.separator;
if (node.getParent() != fact.getRoot()
&& !((Package) node.getParent()).getName().equals("unnamed package")) {
path += ((Package) node.getParent()).getQualifiedName().replace('.', File.separatorChar);
path += File.separator;
}
}
if (OptionParser.getColumbusResultDir() != null) {
path += OptionParser.getColumbusResultDir() + File.separator;
}
path += ((TypeDeclaration) node).getName();
if (extraAsg != null)
header.add("ExtraAsg", extraAsg + ".jsi");
saveToSmallJsi(fact, path + ".jsi", header);
if (OptionParser.isXmlToEveryClass()) {
saveToXml(fact, path + ".jml");
}
visitor.restoreStrTable();
}
// saving extra jsi
if (extraAsg != null) {
fact.turnFilterOff();
visitor.init();
it = fact.iterator();
while (it.hasNext()) {
Base node = it.next();
if (node.getParent() == null || !Common.getIsTypeDeclaration(node)
|| node.getParent().getNodeKind() != NodeKind.ndkPackage
|| ((TypeDeclaration) node).getIsInCompilationUnit() != null) {
continue;
}
visitor.addRoot(node);
}
visitor.run();
visitor.createFilter();
fact.turnFilterOn();
saveToSmallJsi(fact, extraAsg + ".jsi", new CsiHeader());
if (OptionParser.isXmlToEveryClass()) {
saveToXml(fact, extraAsg + ".xml");
}
visitor.restoreStrTable();
}
}
private static void createParentDirectory(String filename) {
File dir = new File(filename).getParentFile();
if (dir != null && !dir.exists())
dir.mkdirs();
}
public static void saveToXml(Factory fact, String xmlPath) {
createParentDirectory(xmlPath);
VisitorJAVAML vis = new VisitorJAVAML(xmlPath, "", false);
AlgorithmPreorder algPre = new AlgorithmPreorder();
algPre.run(fact, vis);
}
public static void saveToJsi(Factory fact, String jsiPath, CsiHeader header) {
String timestamp = Long.toString(System.currentTimeMillis());
header.add("TimeStamp", timestamp);
logger.info("info.jan.classSaver.savingFileTimestamp", timestamp);
if (OptionParser.getComponentId() != null) {
header.add(CsiHeader.csih_OriginalLocation, OptionParser.getComponentId());
}
if (OptionParser.getChangesetID() != null) {
header.add(CsiHeader.csih_ChangesetID, OptionParser.getChangesetID());
}
saveToJsi(fact, jsiPath, header, true, false, StrType.strDefault);
}
private static void saveToSmallJsi(Factory fact, String jsiPath, CsiHeader header) {
saveToJsi(fact, jsiPath, header, false, true, StrType.strToSave);
}
private static void saveToJsi(Factory fact, String jsiPath, CsiHeader header, boolean saveFilter,
boolean usedSpecNodesOnly, StrType strType) {
createParentDirectory(jsiPath);
// save jsi
logger.debug("debug.jan.classSaver.savingFile", jsiPath);
fact.save(jsiPath, header, strType, usedSpecNodesOnly);
if (saveFilter) {
// save filter
String filterPath = jsiPath;
int idx = filterPath.lastIndexOf('.');
if (idx != -1) {
filterPath = filterPath.substring(0, idx) + ".fjsi";
} else {
filterPath += ".fjsi";
}
fact.saveFilter(filterPath);
}
}
}
| 6,761 | 29.736364 | 146 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/Filter.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import columbus.java.asg.Factory;
import columbus.java.asg.algorithms.AlgorithmPreorder;
import columbus.java.asg.base.Base;
import columbus.java.asg.visitors.VisitorAbstractNodes;
import columbus.logger.LoggerHandler;
public class Filter {
private static final LoggerHandler logger = new LoggerHandler(Filter.class, OptionParser.getLoggerPropertyFile());
private Factory factory;
private int nodesAfterExternalClasses;
private boolean[] visitedNodes;
public Filter(Factory factory, int nodesBeforeExternalClasses, int nodesAfterExternalClasses) {
this.factory = factory;
this.nodesAfterExternalClasses = nodesAfterExternalClasses;
this.visitedNodes = new boolean[factory.size()];
for (int i = nodesBeforeExternalClasses; i < nodesAfterExternalClasses; ++i) {
// the nodes that were built from external classes are automatically filtered out
factory.setFilteredThisNodeOnly(i);
}
}
protected class UsedNodesVisitor extends VisitorAbstractNodes {
@Override
public void visit(Base node, boolean callVirtualBase) {
visitedNodes[node.getId()] = true;
}
}
public void run() {
AlgorithmPreorder ap = new AlgorithmPreorder();
ap.setVisitSpecialNodes(true, true);
UsedNodesVisitor visitor = new UsedNodesVisitor();
// traverse the internal nodes and the referred types
ap.run(factory, visitor, factory.getRoot());
// filter out types that are used only by filtered nodes
for (int i = nodesAfterExternalClasses; i < factory.size(); ++i) {
if (!visitedNodes[i]) {
factory.setFilteredThisNodeOnly(i);
}
}
}
public static boolean filterList(List<File> inputs, final String hardFilterFilePath) {
List<String> lines = new LinkedList<String>();
// open the filter pattern file
try (BufferedReader reader = new BufferedReader(new FileReader(new File(hardFilterFilePath)))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("-") || line.startsWith("+")) {
lines.add(0, line);
}
}
} catch (IOException e) {
logger.error("error.jan.Filter.badHardFilter", e);
return false;
}
Iterator<File> it = inputs.iterator();
while (it.hasNext()) {
File inputFileName = it.next();
for (String filterLine : lines) {
String regexp = ".*" + filterLine.substring(1) + ".*";
Pattern pattern = null;
if (System.getProperty("os.name").contains("Windows")){
pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
} else {
pattern = Pattern.compile(regexp);
}
Matcher m = pattern.matcher(inputFileName.getAbsolutePath());
if (m.matches()) {
if (filterLine.startsWith("-")) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.Filter.skippingFileByHardFilter", inputFileName.getAbsolutePath());
}
it.remove();
}
break;
}
}
}
return true;
}
}
| 3,856 | 30.614754 | 115 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/FileProcessor.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;
import java.util.Scanner;
import java.util.TreeSet;
/**
* A class which contains methods to process a file and search it for useful lines.
*/
public class FileProcessor {
private Scanner scanner;
/**
* @param filePath The path to the file.
* @return A TreeSet, which contains the line indexes of non-empty and non-comment lines.
*/
public TreeSet<Integer> processFile(String filePath) {
File file = new File(filePath);
Charset encoding = OptionParser.encoding == null ? Charset.defaultCharset() : Charset.forName(OptionParser.encoding);
try {
scanner = new Scanner(file, encoding.name());
return searchForLogicalLines(scanner);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new TreeSet<>();
}
private TreeSet<Integer> searchForLogicalLines(Scanner scanner) {
TreeSet<Integer> lines = new TreeSet<>();
int lineIndex = 0;
boolean[] response = {false, false};
String line;
while(scanner.hasNextLine()) {
line = scanner.nextLine().trim();
lineIndex++;
response = processLine(line, response[1]);
if (response[0]) {
lines.add(lineIndex);
}
}
return lines;
}
/**
* @param line The line to process.
* @param multi True, if the processing is a multi line comment.
* @return a boolean array with two values: the first is true, if the line is useful, the second is true, if the processing continues in a multi line comment.
*/
private boolean[] processLine(String line, boolean multi) {
/*
* A boolean array to return two boolean values.
* 0. The value, which says whether the line is a useful line for LLOC.
* 1. This says, whether the processing is in a multi line comment. The method will get it back as a parameter on the next call.
*/
boolean[] responseArray = new boolean[] {false, false};
if (multi) {
if (line.contains("*/")) {
int boundIndex = findInString(line, new char[]{'*', '/'}, true);
if (boundIndex != -1) {
if (boundIndex < line.length() - 2) {
line = line.substring(boundIndex + 2).trim();
} else {
line = "";
}
}
} else {
responseArray[1] = true;
return responseArray;
}
}
if (line.isEmpty()) {
return responseArray;
} else if (line.length() == 1) {
//In this case this line should be a useful one.
responseArray[0] = true;
} else {
if (line.charAt(0) == '/') {
if (line.charAt(1) == '/') {
//It is a simple line comment. The whole line is a comment line.
return responseArray;
} else if (line.charAt(1) == '*') {
//This is the start of a multi line comment. Actually it could be a multi line comment in one line.
String l = line.substring(1);
if (l.contains("*/")) {
int boundIndex = findInString(line, new char[]{'*', '/'}, true);
if (boundIndex != -1) {
if (boundIndex < line.length() - 2) {
line = line.substring(boundIndex + 2).trim();
responseArray = processLine(line, false);
}
}
} else {
responseArray[1] = true;
}
}
} else if (line.contains("/*")) {
boolean r = findMultiLineComments(line, new char[]{'/', '*'}, false);
responseArray[1] = r;
responseArray[0] = true;
} else {
responseArray[0] = true;
}
}
return responseArray;
}
/**
* @param line the line (practically a string) to process
* @param bound the bound character to search for. It should be either {/, *} or {*, /}
* @param findClosingTag If true, the method will stop when it founds the first match for the bounds. It is used to find the closing tag of the comment.
* @return true, if the processing is in a multi line comment, otherwise false.
*/
private boolean findMultiLineComments(String line, char[] bound, boolean findClosingTag) {
boolean result = false;
int commentBound = findInString(line, bound, findClosingTag);
if (commentBound != -1) {
String subLine = line.substring(commentBound + 2).trim();
//Switch the places of the char array and create a string to use in String.contains().
String boundToLookFor = String.copyValueOf(new char[]{bound[1], bound[0]});
if (!subLine.isEmpty() && subLine.contains(boundToLookFor)) {
//The program stores the return value here, but doesn't use it later.
@SuppressWarnings("unused")
boolean returnValue = findMultiLineComments(subLine, new char[]{bound[1], bound[0]}, !findClosingTag);
} else if (!findClosingTag) {
result = true;
}
}
return result;
}
/**
* @param line the line (practically a string) to process.
* @param bound the bound character to search for. It should be either or {'/','*'} or {'*', '/'}.
* @param findClosingTag If true, the method will stop when it founds the first match for the bounds. It is used to find the closing tag of the comment.
* @return The index of the bound if the program finds it, -1 otherwise.
*/
private int findInString(String line, char[] bound, boolean findClosingTag) {
int commentBound = -1;
boolean inString = false;
char[] cLine = line.toCharArray();
for (int i = 0; i < line.length(); i++) {
if (cLine[i] == '\"') {
if (i > 0 && cLine[i - 1] == '\\') { //Escaped " doesn't count.
continue;
}
inString = !inString;
}
if (inString) {
continue;
}
//When the program flips the inString value to be false, this condition will run althought it is not needed.
if (cLine[i] == bound[0] && (i < line.length() - 1) && cLine[i + 1] == bound[1]) {
commentBound = i;
if (findClosingTag) {
break;
}
}
}
return commentBound;
}
}
| 7,640 | 36.092233 | 162 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/FileCollector.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import columbus.logger.LoggerHandler;
public class FileCollector {
private static final LoggerHandler logger = new LoggerHandler(FileCollector.class,
OptionParser.getLoggerPropertyFile());
private static String IN_COLUMBUS_REGTEST_ENV_VAR = "IN_COLUMBUS_REGTEST";
private static boolean IN_COLUMBUS_REGTEST = System.getenv(IN_COLUMBUS_REGTEST_ENV_VAR) != null;
public static List<File> collectFiles(List<String> fileNames) {
Set<File> inputFiles = new HashSet<>();
for (String s : fileNames) {
if (s.contains("*")) {
// if there is a * in the path, we add the parent directory as the input list
int lastSlashPos = s.replace("\\", "/").lastIndexOf("/");
String parentDir = null;
if (lastSlashPos == -1) {
parentDir = ".";
} else {
parentDir = s.substring(0, lastSlashPos);
}
collectFiles(inputFiles, new File(parentDir), false, s.substring(lastSlashPos + 1).split("\\*"));
} else {
collectFiles(inputFiles, new File(s), true, null);
}
}
File[] fileList = inputFiles.toArray(new File[inputFiles.size()]);
Arrays.sort(fileList, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getPath().compareToIgnoreCase(o2.getPath());
}
});
return new ArrayList<>(Arrays.asList(fileList));
}
public static void writeSourceFileList(List<File> inputFiles, String listFileName) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File(listFileName)))) {
for (File f : inputFiles) {
bw.write(f.getAbsolutePath());
bw.newLine();
}
} catch (IOException e) {
logger.error("error.jan.FileCollector.fileListWritingErr", e);
}
}
private static void collectFiles(Set<File> inputFiles, File file, boolean recursively, String[] patternFragments) {
if (!file.exists()) {
logger.error("error.jan.FileCollector.fileOrDirDoesNotExist", file);
return;
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
// according to the description of File.listFiles(), the result array is not (necessarily) sorted
// but the final list will be sorted later, so we don't bother with it
if (f.isFile()) {
collectFiles(inputFiles, f, recursively, patternFragments);
} else {
if (recursively) {
collectFiles(inputFiles, f, recursively, patternFragments);
}
}
}
} else {
if ((patternFragments != null && matches(file.getName(), patternFragments))
|| (patternFragments == null && file.getName().endsWith(".java"))) {
if (OptionParser.wrappedMode) {
if (IN_COLUMBUS_REGTEST) {
inputFiles.add(file);
} else {
try {
inputFiles.add(file.getCanonicalFile());
} catch (IOException e) {
logger.error("error.jan.FileCollector.couldntDetermineCanonicalPath", file, e);
inputFiles.add(file.getAbsoluteFile());
}
}
} else {
inputFiles.add(file);
}
}
}
}
private static boolean matches(String str, String[] patternFragments) {
int startpos = 0;
for (String fragment : patternFragments) {
if ((startpos = str.indexOf(fragment, startpos)) != -1) {
startpos += fragment.length();
} else {
return false;
}
}
return true;
}
}
| 4,229 | 29.652174 | 116 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/Timer.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
/*
* Only works properly for single threaded tasks, can be extended for multiple threads
*/
public class Timer {
// time spent running the application's own code.
private long startUserTime;
private long stopUserTime;
// the time spent running OS code on behalf of the application (such as for I/O).
private long startSystemTime;
private long stopSystemTime;
// User time plus system time. It's the total time spent using a CPU for the application.
private long startCpuTime;
private long stopCpuTime;
private String info;
public Timer(String info) {
this.info = info;
}
public void start() {
startUserTime = getCurrentUserTime();
startSystemTime = getCurrentSystemTime();
startCpuTime = getCurrentCpuTime();
}
public void stop() {
stopUserTime = getCurrentUserTime();
stopSystemTime = getCurrentSystemTime();
stopCpuTime = getCurrentCpuTime();
}
public long getTotalUserTime() {
return (stopUserTime - startUserTime)/1000000;
}
public long getTotalSystemTime() {
return (stopSystemTime - startSystemTime)/1000000;
}
public long getTotalCpuTime() {
return (stopCpuTime - startCpuTime)/1000000;
}
public String getInfo() {
return info;
}
// Get user time in nanoseconds.
private long getCurrentUserTime() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
return bean.isCurrentThreadCpuTimeSupported() ? bean.getCurrentThreadUserTime() : 0L;
}
// Get system time in nanoseconds.
private long getCurrentSystemTime() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
return bean.isCurrentThreadCpuTimeSupported() ? (bean.getCurrentThreadCpuTime() - bean
.getCurrentThreadUserTime()) : 0L;
}
// Get CPU time in nanoseconds.
private long getCurrentCpuTime() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
return bean.isCurrentThreadCpuTimeSupported() ? bean.getCurrentThreadCpuTime() : 0L;
}
}
| 2,751 | 27.371134 | 90 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/ExternalClassBuilder.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.lang.model.element.ElementKind;
import javax.lang.model.type.TypeKind;
import columbus.java.asg.Common;
import columbus.java.asg.Factory;
import columbus.java.asg.JavaException;
import columbus.java.asg.base.Base;
import columbus.java.asg.base.Positioned;
import columbus.java.asg.enums.MethodKind;
import columbus.java.asg.enums.NodeKind;
import columbus.java.asg.expr.Annotation;
import columbus.java.asg.expr.Assignment;
import columbus.java.asg.expr.BooleanLiteral;
import columbus.java.asg.expr.CharacterLiteral;
import columbus.java.asg.expr.ClassLiteral;
import columbus.java.asg.expr.DoubleLiteral;
import columbus.java.asg.expr.Erroneous;
import columbus.java.asg.expr.ExternalTypeExpression;
import columbus.java.asg.expr.FloatLiteral;
import columbus.java.asg.expr.Identifier;
import columbus.java.asg.expr.IntegerLiteral;
import columbus.java.asg.expr.LongLiteral;
import columbus.java.asg.expr.MarkerAnnotation;
import columbus.java.asg.expr.NewArray;
import columbus.java.asg.expr.NormalAnnotation;
import columbus.java.asg.expr.StringLiteral;
import columbus.java.asg.struc.AnnotationType;
import columbus.java.asg.struc.AnnotationTypeElement;
import columbus.java.asg.struc.ClassGeneric;
import columbus.java.asg.struc.Enum;
import columbus.java.asg.struc.EnumConstant;
import columbus.java.asg.struc.Interface;
import columbus.java.asg.struc.InterfaceGeneric;
import columbus.java.asg.struc.Method;
import columbus.java.asg.struc.MethodDeclaration;
import columbus.java.asg.struc.MethodGeneric;
import columbus.java.asg.struc.NamedDeclaration;
import columbus.java.asg.struc.NormalMethod;
import columbus.java.asg.struc.Package;
import columbus.java.asg.struc.Parameter;
import columbus.java.asg.struc.TypeDeclaration;
import columbus.java.asg.struc.TypeParameter;
import columbus.java.asg.struc.Variable;
import columbus.java.asg.struc.VariableDeclaration;
import columbus.logger.LoggerHandler;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Attribute.Compound;
import com.sun.tools.javac.code.Attribute.Constant;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symbol.TypeVariableSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Pair;
public class ExternalClassBuilder {
private static final LoggerHandler logger = new LoggerHandler(ExternalClassBuilder.class,
OptionParser.getLoggerPropertyFile());
private TreeBuilder builder;
private Factory fact;
private SymbolMaps symMaps;
private Set<Symbol> symbolsToBuild = new LinkedHashSet<>();
private Set<Symbol> symbolsToBuild2 = new LinkedHashSet<>();
private boolean even = true;
private boolean innerPart = false;
private boolean buildExtFromSource = OptionParser.isBuildExtFromSource();
private Set<Symbol> typeDeclarationSymbolSet = new LinkedHashSet<>();
private Map<Symbol, Integer> nestedClassMap = new LinkedHashMap<>();
private boolean oneMoreRoundNeeded = false;
// to check if the TypeDeclaration is already built
private Map<Symbol, TypeDeclaration> builtTypeDeclarations = new HashMap<>();
private Set<Symbol> partlyBuiltTypeDeclarations = new HashSet<>();
private Names names;
private Symtab symtab;
public ExternalClassBuilder(Factory factory, TreeBuilder builder, SymbolMaps symMaps, Context context) {
this.names = Names.instance(context);
this.symtab = Symtab.instance(context);
this.fact = factory;
this.builder = builder;
this.symMaps = symMaps;
}
public void build() {
typeDeclarationSymbolSet = symMaps.getExternalClassAndInterfaceSet();
symMaps.clearInnerClassesFromFullBuildSet();
boolean firstBuild = true;
while (oneMoreRoundNeeded || firstBuild) {
Set<Symbol> set = null;
if (firstBuild) {
logger.info("info.jan.ExternalClassBuilder.firstRound");
set = typeDeclarationSymbolSet;
firstBuild = false;
} else {
logger.info("info.jan.ExternalClassBuilder.nextRound");
if (even) {
set = symbolsToBuild;
symbolsToBuild2.clear();
even = !even;
} else {
set = symbolsToBuild2;
symbolsToBuild.clear();
even = !even;
}
typeDeclarationSymbolSet.addAll(set);
}
oneMoreRoundNeeded = false;
for (Symbol sym : set) {
if (sym.type != null && sym.type.getKind() == TypeKind.ERROR) {
// should not happen
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.ExternalClassBuilder.symbolTypeIsError", sym);
}
continue;
}
if (sym == symtab.boundClass || sym == symtab.arrayClass || sym == symtab.methodClass || sym == symtab.unknownSymbol ||
(sym.type != null && sym.type == symtab.botType)) {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.ExternalClassBuilder.dontBuildBuiltinSymbol", sym.name);
}
continue;
}
if (typeDeclarationSymbolSet.contains(sym.owner) && symMaps.containsSymbolsToFullBuild(sym.owner)) {
continue;
}
int id = 0;
id = visitSymbol(sym);
Base n = fact.getRef(id);
if (n.getParent() == null) {
if (sym.owner.getKind() == ElementKind.PACKAGE || sym.owner.getKind().isClass()
|| sym.owner.getKind().isInterface()) {
int parentId = createClassHierarchy(sym.owner);
Base parentNode = fact.getRef(parentId);
if (Common.getIsTypeDeclaration(parentNode)) {
((TypeDeclaration) parentNode).addMembers(id);
} else {
((Package) parentNode).addMembers(id);
}
} else {
fact.getRoot().addMembers(id);
}
}
}
buildExtFromSource = false;
}
// build the missing values and valueOf nodes from symbols
innerPart = true;
for (Entry<MethodSymbol, Integer> e : symMaps.getEnumFunctions().entrySet()) {
int id = visitSymbol(e.getKey());
Enum enumNode = (Enum) fact.getRef(e.getValue());
enumNode.addMembers(id);
}
innerPart = false;
}
private int createClassHierarchy(Symbol sym) {
int ret = 0;
try {
if (sym.getKind() == ElementKind.PACKAGE) {
return builder.createAndAddPackages((PackageSymbol) sym);
} else {
if (nestedClassMap.containsKey(sym)) {
ret = nestedClassMap.get(sym);
} else {
int actual = createClass((ClassSymbol) sym, symMaps.containsSymbolsToFullBuild(sym));
TypeDeclaration td = (TypeDeclaration) fact.getRef(actual);
if (td.getParent() != null)
return actual;
Base parentNode = fact.getRef(createClassHierarchy(sym.owner));
if (Common.getIsTypeDeclaration(parentNode)) {
((TypeDeclaration) parentNode).addMembers(actual);
} else {
((Package) parentNode).addMembers(actual);
}
nestedClassMap.put(sym, actual);
ret = actual;
}
}
} catch (Exception e) {
logger.error("ex.jan.ExternalClassBuilder.errorCreatingOwnerOfTypeDecl", e);
}
return ret;
}
private int visitSymbol(Symbol sym) {
NamedDeclaration member = null;
try {
if (sym == null) {
throw new JavaException(logger.formatMessage("ex.jan.ExternalClassBuilder.symCantBeNull"));
}
boolean prevInnerPart = innerPart;
if (sym instanceof ClassSymbol) {
ClassSymbol classSym = (ClassSymbol) sym;
boolean fullBuild = symMaps.containsSymbolsToFullBuild(sym);
TypeDeclaration typeDeclNode = (TypeDeclaration) fact.getRef(createClass(classSym, fullBuild));
if (typeDeclNode.getParent() != null)
return typeDeclNode.getId();
member = typeDeclNode;
} else if (sym instanceof VarSymbol) {
VarSymbol varSym = (VarSymbol) sym;
if (sym.type instanceof Type.ArrayType) {
Type t = ((Type.ArrayType) sym.type).elemtype;
if (!t.isPrimitive()) {
addToSymbolsToBuildSet(t.tsym);
}
}
VariableDeclaration varDeclNode = null;
switch (varSym.getKind()) {
case PARAMETER:
Parameter parameterNode = (Parameter) fact.createNode(NodeKind.ndkParameter);
varDeclNode = parameterNode;
addToSymbolsToBuildSet(sym.owner);
break;
case ENUM_CONSTANT:
EnumConstant enumConstNode = (EnumConstant) fact.createNode(NodeKind.ndkEnumConstant);
varDeclNode = enumConstNode;
break;
case FIELD:
Variable variableNode = (Variable) fact.createNode(NodeKind.ndkVariable);
varDeclNode = variableNode;
addToSymbolsToBuildSet(sym.owner);
break;
case EXCEPTION_PARAMETER:
case ENUM:
case LOCAL_VARIABLE:
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.ExternalClassBuilder.unexpectedVarSym", varSym.getKind());
}
break;
default:
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.ExternalClassBuilder.unknownVarSym");
}
break;
}
varDeclNode.setType(visitTypeExpression(varSym.type));
symMaps.getVariableDeclarationMap().put(varSym, varDeclNode.getId());
member = varDeclNode;
} else if (sym instanceof MethodSymbol) {
MethodSymbol methodSym = (MethodSymbol) sym;
// for debug only, the condition should never be true
if (methodSym.getKind() == ElementKind.STATIC_INIT) {
return 0;
}
if (JANFlags.hasAnonconstrFlag(sym.flags()) || JANFlags.hasGeneratedConstrFlag(sym.flags())) {
innerPart = true;
}
MethodDeclaration methodDecl = null;
if (methodSym.getEnclosingElement() != null
&& methodSym.getEnclosingElement().getKind() == ElementKind.ANNOTATION_TYPE) {
AnnotationTypeElement annotTypeElem = (AnnotationTypeElement) fact
.createNode(NodeKind.ndkAnnotationTypeElement);
methodDecl = annotTypeElem;
} else {
NormalMethod methodNode = null;
if (methodSym.getTypeParameters().size() != 0) {
MethodGeneric methodGenericNode = (MethodGeneric) fact.createNode(NodeKind.ndkMethodGeneric);
for (TypeSymbol typaram : methodSym.getTypeParameters()) {
methodGenericNode.addTypeParameters(visitSymbol(typaram));
}
methodNode = methodGenericNode;
} else {
methodNode = (Method) fact.createNode(NodeKind.ndkMethod);
}
for (Type throwType : methodSym.getThrownTypes()) {
methodNode.addThrownExceptions(visitTypeExpression(throwType));
}
for (VarSymbol param : methodSym.getParameters()) {
methodNode.addParameters(visitSymbol(param));
}
methodDecl = methodNode;
}
symMaps.getMethodDeclarationMap().put(methodSym, methodDecl.getId());
symMaps.addMethodType(methodSym.type, methodDecl.getId());
if (methodSym.getKind() != ElementKind.CONSTRUCTOR) { // don't build return type for constructors
if (methodSym.getReturnType() != null) {
methodDecl.setReturnType(visitTypeExpression(methodSym.getReturnType()));
}
}
member = methodDecl;
} else if (sym instanceof TypeSymbol) {
return visitType(sym.type);
} else {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.ExternalClassBuilder.notHandledSymKind", sym.getKind());
}
}
JANFlags.setModifiers(sym.flags(), member);
if (sym.name == names.init) { // constructor
member.setName(sym.owner.name.toString());
NormalMethod meth = (NormalMethod) member;
if (meth.getMethodKind() == MethodKind.mekNormal) {
meth.setMethodKind(MethodKind.mekConstructor);
}
} else {
member.setName(sym.name.toString());
}
for (Compound c : sym.getAnnotationMirrors()) {
member.addAnnotations(visitCompound(c));
}
if (innerPart) {
member.setIsCompilerGenerated(true);
}
innerPart = prevInnerPart;
} catch (Exception e) {
logger.error("error.jan.ExternalClassBuilder.errorVisitingSym", e);
}
return member.getId();
}
private int visitClassTypeParameter(Type t) {
TypeParameter typeParameterNode = (TypeParameter) fact.createNode(NodeKind.ndkTypeParameter);
try {
typeParameterNode.addBounds(visitTypeExpression(t));
typeParameterNode.setName(t.toString());
Integer oldvalue = symMaps.getTypeParameterMap().put(t, typeParameterNode.getId());
if (oldvalue != null) {
// System.out.println("TypeParam " + t + " already added, old " + oldvalue + " new " +
// typeParameterNode.getId());
}
if (innerPart) {
typeParameterNode.setIsCompilerGenerated(true);
}
} catch (Exception e) {
logger.error("error.jan.ExternalClassBuilder.errorVisitingTypeParam", e);
}
return typeParameterNode.getId();
}
private int createClass(ClassSymbol classSym, boolean fullBuild) {
TypeDeclaration typeDeclNode = null;
try {
TypeDeclaration td = builtTypeDeclarations.get(classSym);
if (td != null) {
// if have to build fully a partly built class, we fill the missing parts
if (partlyBuiltTypeDeclarations.remove(classSym) && fullBuild) {
if (logger.isInfoEnabled()) {
logger.info("info.jan.ExternalClassBuilder.fillExtTypeDecl", classSym.toString());
}
Type superClassType = classSym.getSuperclass();
if (superClassType != null && superClassType.getKind() != TypeKind.NONE) {
addToSymbolsToBuildSet(superClassType.tsym);
}
for (Type type : classSym.getInterfaces()) {
addToSymbolsToBuildSet(type.tsym);
}
buildInnerPartsOfTypeDeclarations(classSym, td);
}
return td.getId();
}
if (logger.isInfoEnabled()) {
logger.info("info.jan.ExternalClassBuilder.buildingExtTypeDecl", classSym.toString());
}
switch (classSym.getKind()) {
case CLASS:
if (classSym.type.getTypeArguments().size() == 0) {
typeDeclNode = (TypeDeclaration) fact.createNode(NodeKind.ndkClass);
} else {
ClassGeneric classGenericNode = (ClassGeneric) fact.createNode(NodeKind.ndkClassGeneric);
for (Type t : classSym.type.getTypeArguments()) {
if (t.getKind() != TypeKind.TYPEVAR) {
classGenericNode.addTypeParameters(visitClassTypeParameter(t));
} else {
classGenericNode.addTypeParameters(visitType(t));
}
}
typeDeclNode = classGenericNode;
}
break;
case INTERFACE:
if (classSym.type.getTypeArguments().size() == 0) {
typeDeclNode = (Interface) fact.createNode(NodeKind.ndkInterface);
} else {
InterfaceGeneric interfaceGenericNode = (InterfaceGeneric) fact
.createNode(NodeKind.ndkInterfaceGeneric);
for (Type t : classSym.type.getTypeArguments()) {
if (t.getKind() != TypeKind.TYPEVAR) {
interfaceGenericNode.addTypeParameters(visitClassTypeParameter(t));
} else {
interfaceGenericNode.addTypeParameters(visitType(t));
}
}
typeDeclNode = interfaceGenericNode;
}
break;
case ANNOTATION_TYPE:
AnnotationType annotTypeNode = (AnnotationType) fact.createNode(NodeKind.ndkAnnotationType);
typeDeclNode = annotTypeNode;
break;
case ENUM:
Enum enumNode = (Enum) fact.createNode(NodeKind.ndkEnum);
typeDeclNode = enumNode;
break;
default:
throw new JavaException(logger.formatMessage("ex.jan.ExternalClassBuilder.incorrectClassSymKind"));
}
builtTypeDeclarations.put(classSym, typeDeclNode);
typeDeclNode.setBinaryName(classSym.flatname.toString());
typeDeclNode.setName(classSym.name.toString());
symMaps.getExternalTypeDeclarationMap().put(classSym, typeDeclNode.getId());
Type superClassType = classSym.getSuperclass();
if (superClassType != null && superClassType.getKind() != TypeKind.NONE) {
typeDeclNode.setSuperClass(visitTypeExpression(superClassType));
addToSymbolsToBuildSet(superClassType.tsym);
}
for (Type type : classSym.getInterfaces()) {
typeDeclNode.addSuperInterfaces(visitTypeExpression(type));
addToSymbolsToBuildSet(type.tsym);
}
if (buildExtFromSource || OptionParser.isBuildAllExternal() || fullBuild) {
// if we fully build an external class, we need to fully build all it's parents for override edges
buildInnerPartsOfTypeDeclarations(classSym, typeDeclNode);
} else {
partlyBuiltTypeDeclarations.add(classSym);
}
} catch (Exception e) {
logger.error("error.jan.ExternalClassBuilder.errorCreatingClass", e);
}
return typeDeclNode.getId();
}
private void buildInnerPartsOfTypeDeclarations(ClassSymbol classSym, TypeDeclaration typeDeclNode) {
if (OptionParser.buildAllParentForOverrides) {
symMaps.addAllParentToFullBuild(classSym);
}
for (Symbol m : classSym.getEnclosedElements()) {
// symbols does not contains useful informations of static init blocks, so we skip them
if (m.getKind() == ElementKind.STATIC_INIT) {
continue;
}
typeDeclNode.addMembers(visitSymbol(m));
}
}
private int visitCompound(Compound c) {
Annotation annotationNode = null;
try {
switch (c.getElementValues().size()) {
case 0:
annotationNode = (MarkerAnnotation) fact.createNode(NodeKind.ndkMarkerAnnotation);
break;
case 1:
default:
NormalAnnotation normalAnnotationNode = (NormalAnnotation) fact
.createNode(NodeKind.ndkNormalAnnotation);
for (Pair<MethodSymbol, Attribute> value : c.values) {
MethodSymbol methodSym = value.fst;
Identifier identifierNode = (Identifier) fact.createNode(NodeKind.ndkIdentifier);
symMaps.addNodeType(methodSym.type, identifierNode.getId());
identifierNode.setName(methodSym.name.toString());
symMaps.addToIdMap(identifierNode.getId(), methodSym);
addToSymbolsToBuildSet(methodSym.owner);
symMaps.addClassAndInterfaceToFullBuildSet(methodSym.owner);
Assignment assignmentNode = (Assignment) fact.createNode(NodeKind.ndkAssignment);
symMaps.addNodeType(methodSym.type, assignmentNode.getId());
assignmentNode.setLeftOperand(identifierNode);
int snd_id = createAnnotationElementValue(value.snd.getValue(), value.snd.type);
assignmentNode.setRightOperand(snd_id);
symMaps.addNodeType(value.snd.type, snd_id);
normalAnnotationNode.addArguments(assignmentNode);
}
annotationNode = normalAnnotationNode;
break;
}
if (c.type != null) {
symMaps.addNodeType(c.type, annotationNode.getId());
annotationNode.setAnnotationName(visitTypeExpression(c.type));
}
if (innerPart) {
annotationNode.setIsCompilerGenerated(true);
}
} catch (Exception e) {
logger.error("error.jan.ExternalClassBuilder.errorVisitingAnnot", e);
}
return annotationNode.getId();
}
private int createAnnotationElementValue(Object value, Type type) {
int ret = 0;
try {
if (value instanceof String) {
StringLiteral l = (StringLiteral) fact.createNode(NodeKind.ndkStringLiteral);
l.setValue(value.toString());
ret = l.getId();
} else if (value instanceof Boolean) {
BooleanLiteral l = (BooleanLiteral) fact.createNode(NodeKind.ndkBooleanLiteral);
l.setBooleanValue((boolean) value);
ret = l.getId();
} else if (value instanceof Character) {
CharacterLiteral l = (CharacterLiteral) fact.createNode(NodeKind.ndkCharacterLiteral);
l.setCharValue((char) value);
ret = l.getId();
} else if (value instanceof Integer) {
IntegerLiteral l = (IntegerLiteral) fact.createNode(NodeKind.ndkIntegerLiteral);
l.setIntValue((int) value);
l.setValue(value.toString());
ret = l.getId();
} else if (value instanceof Long) {
LongLiteral l = (LongLiteral) fact.createNode(NodeKind.ndkLongLiteral);
l.setLongValue(((long) value));
l.setValue(value.toString());
ret = l.getId();
} else if (value instanceof Float) {
FloatLiteral l = (FloatLiteral) fact.createNode(NodeKind.ndkFloatLiteral);
l.setFloatValue(((float) value));
l.setValue(value.toString());
ret = l.getId();
} else if (value instanceof Double) {
DoubleLiteral l = (DoubleLiteral) fact.createNode(NodeKind.ndkDoubleLiteral);
l.setDoubleValue(((double) value));
l.setValue(value.toString());
ret = l.getId();
} else if (value instanceof Compound) {
ret = visitCompound((Compound) value);
} else if (value instanceof ClassType) {
ClassLiteral l = (ClassLiteral) fact.createNode(NodeKind.ndkClassLiteral);
l.setComponentType(visitTypeExpression(((ClassType) value).tsym.type));
ret = l.getId();
} else if (value instanceof List) {
List<?> list = (List<?>) value;
if (list.size() == 0) {
ret = fact.createNode(NodeKind.ndkNewArray).getId();
} else if (list.size() == 1) {
ret = createAnnotationElementValue(list.get(0), type);
} else if (list.size() > 1) {
NewArray newArrayNode = (NewArray) fact.createNode(NodeKind.ndkNewArray);
ret = newArrayNode.getId();
for (Object o : list) {
int init_id = createAnnotationElementValue(o, type);
newArrayNode.addInitializers(init_id);
symMaps.addNodeType(type, init_id);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.ExternalClassBuilder.unexpectedListSize", list.size());
}
}
} else if (value instanceof Constant) {
Constant c = (Constant) value;
ret = createAnnotationElementValue(c.value, type);
} else if (value instanceof Attribute.Enum) {
Attribute.Enum aEnum = (com.sun.tools.javac.code.Attribute.Enum) value;
Identifier rightId = (Identifier) fact.createNode(NodeKind.ndkIdentifier);
rightId.setName(aEnum.value.name.toString());
ret = rightId.getId();
symMaps.addToIdMap(rightId.getId(), aEnum.value);
addToSymbolsToBuildSet(aEnum.value.owner);
symMaps.addClassAndInterfaceToFullBuildSet(aEnum.value.owner);
} else if (value instanceof Attribute.Class) {
Attribute.Class aClass = (Attribute.Class) value;
ClassLiteral l = (ClassLiteral) fact.createNode(NodeKind.ndkClassLiteral);
l.setComponentType(visitTypeExpression(aClass.classType));
ret = l.getId();
} else if (value instanceof VarSymbol) {
VarSymbol sym = (VarSymbol) value;
Identifier identifierNode = (Identifier) fact.createNode(NodeKind.ndkIdentifier);
ret = identifierNode.getId();
identifierNode.setName(sym.name.toString());
symMaps.addToIdMap(identifierNode.getId(), sym);
addToSymbolsToBuildSet(sym.owner);
symMaps.addClassAndInterfaceToFullBuildSet(sym.owner);
} else {
Erroneous err = (Erroneous) fact.createNode(NodeKind.ndkErroneous);
ret = err.getId();
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.ExternalClassBuilder.notHandledAnnotElemValue", value.getClass(),
value.toString());
}
}
if (innerPart) {
((Positioned) fact.getRef(ret)).setIsCompilerGenerated(true);
}
} catch (Exception e) {
logger.error("error.jan.ExternalClassBuilder.errorCreatingAnnotElem", e);
}
return ret;
}
private void addToSymbolsToBuildSet(Symbol sym) {
if (sym == null || sym.type == null || sym.type.getKind() == TypeKind.ERROR) {
return;
}
// we will build a typedeclaration in the next round if its not an inner class or its just partly builded
if ((!typeDeclarationSymbolSet.contains(sym) || partlyBuiltTypeDeclarations.contains(sym))
&& !symMaps.getInnerTypeDeclarationMap().containsKey(sym)
&& (sym.getKind().isInterface() || sym.getKind().isClass())) {
// we dont build type declaration for the primitives, or NULL, VOID, NONE symbol
if (!sym.type.isPrimitive() && sym.type.getKind() != TypeKind.VOID && sym.type.getKind() != TypeKind.NULL
&& sym.type.getKind() != javax.lang.model.type.TypeKind.NONE) {
if (even) {
symbolsToBuild.add(sym);
} else {
symbolsToBuild2.add(sym);
}
oneMoreRoundNeeded = true;
}
}
}
private int visitType(Type type) {
int ret = 0;
try {
if (type == null) {
throw new JavaException(logger.formatMessage("ex.jan.ExternalClassBuilder.typeCantBeNull"));
}
switch (type.getKind()) {
case TYPEVAR:
TypeParameter typeParamNode = (TypeParameter) fact.createNode(NodeKind.ndkTypeParameter);
typeParamNode.setName(type.toString());
if (type.tsym != null && type.tsym instanceof TypeVariableSymbol) {
for (Type t : ((TypeVariableSymbol)type.tsym).getBounds()) {
typeParamNode.addBounds(visitTypeExpression(t));
}
}
Integer oldvalue = symMaps.getTypeParameterMap().put(type, typeParamNode.getId());
if (oldvalue != null) {
// System.out.println("TypeParam " + type + " already added, old " + oldvalue + " new " +
// typeParamNode.getId());
}
ret = typeParamNode.getId();
break;
case DECLARED:
ret = visitTypeExpression(type);
break;
case VOID:
ret = visitTypeExpression(type);
break;
case INT:
ret = visitTypeExpression(type);
break;
case NONE:
default:
if (logger.isDebugEnabled()) {
logger.debug("debug.jan.ExternalClassBuilder.notHandledType", type.getKind(), type);
}
break;
}
if (innerPart) {
((Positioned) fact.getRef(ret)).setIsCompilerGenerated(true);
}
} catch (Exception e) {
logger.error("error.jan.ExternalClassBuilder.errorVisitingType", e);
}
return ret;
}
private int visitTypeExpression(Type type) {
ExternalTypeExpression externalTypeExprNode = (ExternalTypeExpression) fact
.createNode(NodeKind.ndkExternalTypeExpression);
try {
if (type == null) {
throw new JavaException(logger.formatMessage("ex.jan.ExternalClassBuilder.typeCantBeNull"));
}
// building the stored class types of arrays, for example: java.lang.Object[]
if (type.getKind() == TypeKind.ARRAY) {
addToSymbolsToBuildSet(((Type.ArrayType) type).elemtype.tsym);
}
if (!type.getTypeArguments().isEmpty() && type.getTypeArguments() != type.tsym.type.getTypeArguments()) {
for (Type t : type.getTypeArguments()) {
if (t.getKind() == TypeKind.WILDCARD) {
Type.WildcardType wt = (Type.WildcardType) t;
if (wt.getExtendsBound() != null)
addToSymbolsToBuildSet(wt.getExtendsBound().tsym);
if (wt.getSuperBound() != null)
addToSymbolsToBuildSet(wt.getSuperBound().tsym);
}
addToSymbolsToBuildSet(t.tsym);
}
}
addToSymbolsToBuildSet(type.tsym);
symMaps.addNodeType(type, externalTypeExprNode.getId());
if (innerPart) {
externalTypeExprNode.setIsCompilerGenerated(true);
}
} catch (Exception e) {
logger.error("error.jan.ExternalClassBuilder.errorVisitinTypeExpr", e);
}
return externalTypeExprNode.getId();
}
}
| 27,508 | 33.08798 | 123 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/JAN/src/main/java/org/jan/ConfigReader.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.jan;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import columbus.logger.LoggerHandler;
public class ConfigReader {
private static final LoggerHandler logger = new LoggerHandler(ConfigReader.class, OptionParser.getLoggerPropertyFile());
public static String getValue(String fileName, String section, String option) {
String ret = null;
try {
List<String> list = getValues(fileName, section, option);
if (list == null || list.size() == 0) {
// error - return null
} else if (list.size() == 1) {
ret = list.get(0);
} else {
logger.warn("warn.jan.ConfigReader.optionHasMultipleValue", option, section);
}
} catch (Exception e) {
logger.error("error.jan.ConfigReader.configReaderEx", e);
}
return ret;
}
public static List<String> getValues(String fileName, String section, String option) {
List<String> values = null;
try {
values = new ArrayList<>();
Map<String, String> sectionMap = readSection(fileName, section);
String valueString = sectionMap.get(option);
if (valueString == null) {
throw new Exception(logger.formatMessage("ex.jan.ConfigReader.cantFindOption", option, fileName, section));
}
StringTokenizer st = new StringTokenizer(valueString, " ");
while (st.hasMoreTokens()) {
String token = st.nextToken();
boolean quation = false;
if (token.startsWith("\"")) {
quation = true;
while (!token.endsWith("\"")) {
String next = st.nextToken();
token += " " + next;
}
}
if (quation) {
token = token.substring(1, token.length() - 1);
}
values.add(token);
}
if (values.size() == 0) {
logger.debug("debug.jan.ConfigReader.optionDontHaveValue", option, section);
}
} catch (FileNotFoundException e) {
logger.error("error.jan.ConfigReader.configReaderEx", e);
} catch (IOException e) {
logger.error("error.jan.ConfigReader.configReaderEx", e);
} catch (Exception e) {
logger.error("error.jan.ConfigReader.configReaderEx", e);
}
return values;
}
public static Map<String, String> readSection(String fileName, String section) throws Exception {
String line;
boolean foundSection = false;
boolean needToRead = false;
Map<String, String> ret = new HashMap<>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(fileName)));
while ((line = br.readLine()) != null) {
line = line.trim();
if (needToRead) {
if (line.startsWith("[") && line.endsWith("]")) {
needToRead = false;
break;
}
if (line.isEmpty() || line.startsWith(";")) {
continue;
}
int firstEquPos = line.indexOf("=");
ret.put(line.substring(0, firstEquPos), line.substring(++firstEquPos, line.length()));
}
if (line.equals("[" + section + "]")) {
foundSection = true;
needToRead = true;
}
}
if (!foundSection) {
throw new Exception(logger.formatMessage("ex.jan.ConfigReader.cantFindSection", section));
}
} catch (Exception e){
logger.error("error.jan.ConfigReader.readingEx", e);
} finally {
br.close();
}
return ret;
}
}
| 4,091 | 28.438849 | 121 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/GraphlibTest/src/columbus/GraphTest.java | package columbus;
import graphlib.Edge;
import graphlib.Graph;
import graphlib.GraphlibException;
import graphlib.Node;
import graphlib.VisitorException;
import java.util.ArrayList;
class TestVisitor implements graphlib.Visitor
{
@Override
public void edgeVisitorFunc(Edge e) throws VisitorException {
String s = e.getFromNode().getUID() + "-" + e.getToNode().getUID();
System.out.println(s);
history.add(s);
}
@Override
public void postNodeVisitorFunc(Node node) throws VisitorException {
String s = "-" + node.getUID();
System.out.println(s);
history.add(s);
}
@Override
public void preNodeVisitorFunc(Node node) throws VisitorException {
String s = "+" + node.getUID();
System.out.println(s);
history.add(s);
}
public ArrayList<String> history = new ArrayList<String>();
};
public class GraphTest {
private static boolean checkResult(String[] expectedResult, ArrayList<String> result)
{
boolean res = true;
if (expectedResult.length != result.size())
{
System.out.println("Length error. Found:" + result.size() + " Expected:" + expectedResult.length);
return false;
}
else
{
for (int i = 0; i < expectedResult.length; ++i)
{
if (expectedResult[i].compareTo(result.get(i)) != 0)
{
System.out.println("Error at:" + i + " Found:" + result.get(i) + " Expected:" + expectedResult[i]);
res = false;
}
}
}
return res;
}
public static void main(String[] args) {
try {
Graph graph = new Graph();
Node node1 = graph.createNode("N1", new Node.NodeType("N"));
Node node2 = graph.createNode("N2", new Node.NodeType("N"));
Node node3 = graph.createNode("N3", new Node.NodeType("N"));
Node node4 = graph.createNode("N4", new Node.NodeType("N"));
Node node5 = graph.createNode("N5", new Node.NodeType("N"));
graph.createDirectedEdge(node1, node2, "E", false);
graph.createDirectedEdge(node1, node3, "E", false);
graph.createDirectedEdge(node1, node2, "E", false);
graph.createDirectedEdge(node2, node4, "E", false);
graph.createDirectedEdge(node2, node4, "E", false);
graph.createDirectedEdge(node3, node1, "E", false);
graph.createDirectedEdge(node3, node4, "E", false);
graph.createDirectedEdge(node3, node4, "E", false);
graph.createDirectedEdge(node4, node1, "E", false);
graph.createDirectedEdge(node4, node5, "E", false);
graph.createDirectedEdge(node4, node1, "E", false);
graph.createDirectedEdge(node4, node5, "E", false);
graph.createDirectedEdge(node4, node1, "E", false);
graph.saveBinary("TestGraph.graph");
graphlib.Edge.EdgeTypeSet edges = new graphlib.Edge.EdgeTypeSet();
edges.add(new Edge.EdgeType("E", Edge.eDirectionType.edtDirectional));
TestVisitor tv = new TestVisitor();
boolean testResultOK = true;
System.out.println("--------------------- Breadth first-------------------");
graph.traverseBreadthFirst(node1, edges, tv);
String[] expectedBFResults = {
"+N1",
"N1-N2",
"N1-N3",
"N1-N2",
"+N2",
"N2-N4",
"N2-N4",
"+N3",
"N3-N1",
"N3-N4",
"N3-N4",
"+N4",
"N4-N1",
"N4-N5",
"N4-N1",
"N4-N5",
"N4-N1",
"+N5"
};
testResultOK &= checkResult(expectedBFResults, tv.history);
System.out.println("--------------------- Depth first -------------------");
tv.history.clear();
graph.traverseDepthFirst(node1, edges, tv);
String[] expectedDFResults = {
"+N1",
"N1-N2",
"N1-N2",
"+N2",
"N2-N4",
"N2-N4",
"+N4",
"N4-N1",
"N4-N1",
"N4-N1",
"N4-N5",
"N4-N5",
"+N5",
"-N5",
"-N4",
"-N2",
"N1-N3",
"+N3",
"N3-N1",
"N3-N4",
"N3-N4",
"-N3",
"-N1"
};
testResultOK &= checkResult(expectedDFResults, tv.history);
System.out.println("--------------------- Depth first pre -------------------");
tv.history.clear();
graph.traverseDepthFirstPreorder(node1, edges, tv);
String[] expectedDFPreResults = {
"+N1",
"N1-N2",
"N1-N2",
"+N2",
"N2-N4",
"N2-N4",
"+N4",
"N4-N1",
"N4-N1",
"N4-N1",
"N4-N5",
"N4-N5",
"+N5",
"N1-N3",
"+N3",
"N3-N1",
"N3-N4",
"N3-N4"
};
testResultOK &= checkResult(expectedDFPreResults, tv.history);
System.out.println("--------------------- Depth first post -------------------");
tv.history.clear();
graph.traverseDepthFirstPostorder(node1, edges, tv);
String[] expectedDFPostResults = {
"N4-N1",
"N4-N1",
"N4-N1",
"-N5",
"N4-N5",
"N4-N5",
"-N4",
"N2-N4",
"N2-N4",
"-N2",
"N1-N2",
"N1-N2",
"N3-N1",
"N3-N4",
"N3-N4",
"-N3",
"N1-N3",
"-N1"
};
testResultOK &= checkResult(expectedDFPostResults, tv.history);
System.out.println("--------------------- Result -------------------");
if (!testResultOK)
{
System.out.println("Test failed!");
System.exit(-1);
}
else
{
System.out.println("Test OK!");
}
} catch (GraphlibException e) {
e.printStackTrace();
} catch (VisitorException e) {
e.printStackTrace();
}
}
}
| 6,166 | 27.159817 | 111 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/GraphExample/src/columbus/VisitorExample.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package columbus;
import java.util.List;
import graphlib.Attribute;
import graphlib.AttributeInt;
import graphlib.AttributeString;
import graphlib.Edge;
import graphlib.Edge.EdgeType;
import graphlib.Graph;
import graphlib.GraphlibException;
import graphlib.Node;
import graphlib.Attribute.aType;
import graphlib.VisitorException;
import graphsupportlib.Metric;
public class VisitorExample implements graphlib.Visitor {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Wrong number of arguments!");
System.out.println("Usage: java -jar GraphExample.jar \"graph file\"");
System.exit(1);
}
String graphFile = args[0];
Graph graph = new Graph();
try {
graph.loadBinary(graphFile);
Node root = graph.findNode(Metric.UID_LOGICAL_ROOT);
Edge.EdgeTypeSet edgeTypeSet = new Edge.EdgeTypeSet();
edgeTypeSet.add(new EdgeType(Metric.ETYPE_LIM_LOGICALTREE, Edge.eDirectionType.edtDirectional));
graph.traverseDepthFirstPreorder(root, edgeTypeSet , new VisitorExample());
} catch (GraphlibException | VisitorException e) {
System.out.println("Error: cannot load binary graph: " + graphFile);
System.exit(1);
}
}
@Override
public void edgeVisitorFunc(Edge arg0) throws VisitorException {
}
@Override
public void postNodeVisitorFunc(Node arg0) throws VisitorException {
}
@Override
public void preNodeVisitorFunc(Node node) throws VisitorException {
if(node.getType().getType().equals(Metric.NTYPE_LIM_CLASS)) {
String className = "";
int LOC = 0;
List<Attribute> attrs = node.findAttribute(aType.atString, Metric.ATTR_NAME, Metric.CONTEXT_ATTRIBUTE);
if (attrs.size() == 1) {
className = ((AttributeString) attrs.get(0)).getValue();
}
attrs = node.findAttribute(aType.atInt, "LOC", Metric.CONTEXT_METRIC);
if (attrs.size() == 1) {
LOC = ((AttributeInt) attrs.get(0)).getValue();
}
System.out.println("Class: " + className + " LOC: " + LOC);
}
}
}
| 2,805 | 29.172043 | 109 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/cl/GraphExample/src/columbus/GraphExample.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package columbus;
import java.util.List;
import graphlib.Attribute;
import graphlib.AttributeInt;
import graphlib.AttributeString;
import graphlib.Graph;
import graphlib.GraphlibException;
import graphlib.Node;
import graphlib.Attribute.aType;
import graphlib.Node.NodeType;
import graphsupportlib.Metric;
public class GraphExample {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Wrong number of arguments!");
System.out.println("Usage: java -jar GraphExample.jar \"graph file\"");
System.exit(1);
}
String graphFile = args[0];
Graph graph = new Graph();
try {
graph.loadBinary(graphFile);
List<Node> classNodes = graph.findNodes(new NodeType(Metric.NTYPE_LIM_CLASS));
for (Node node : classNodes) {
String className = "";
int LOC = 0;
List<Attribute> attrs = node.findAttribute(aType.atString, Metric.ATTR_NAME, Metric.CONTEXT_ATTRIBUTE);
if (attrs.size() == 1) {
className = ((AttributeString) attrs.get(0)).getValue();
}
attrs = node.findAttribute(aType.atInt, "LOC", Metric.CONTEXT_METRIC);
if (attrs.size() == 1) {
LOC = ((AttributeInt) attrs.get(0)).getValue();
}
System.out.println("Class: " + className + " LOC: " + LOC);
}
} catch (GraphlibException e) {
System.out.println("Error: cannot load binary graph: " + graphFile);
System.exit(1);
}
}
}
| 2,214 | 28.932432 | 111 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/ColumbusLogger/src/columbus/logger/LoggerHandler.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package columbus.logger;
import java.util.HashMap;
import java.util.ResourceBundle;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
public class LoggerHandler {
private static class LoggerData {
LoggerData(ResourceBundle rb) {
this.rb = rb;
}
volatile int warnMessages = 0;
volatile int errorMessages = 0;
final ResourceBundle rb;
}
private static HashMap<String, LoggerData> dataMap = new HashMap<>();
private LoggerData data;
private Logger logger;
public LoggerHandler(Class<?> clazz, String path) {
logger = (Logger) LoggerFactory.getLogger(clazz);
data = dataMap.get(path);
if (data == null) {
data = new LoggerData(ResourceBundle.getBundle(path));
dataMap.put(path, data);
}
}
public static void setMessageLevel(int level) {
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
switch (level) {
case 0:
root.setLevel(Level.OFF);
break;
case 1:
root.setLevel(Level.ERROR);
break;
case 2:
root.setLevel(Level.WARN);
break;
case 3:
root.setLevel(Level.INFO);
break;
case 4:
root.setLevel(Level.DEBUG);
break;
case 5:
root.setLevel(Level.TRACE);
break;
case 6:
root.setLevel(Level.ALL);
break;
default:
root.setLevel(Level.INFO);
}
}
public static void initLogback(String logbackXml) {
// assume SLF4J is bound to logback in the current environment
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
// Call context.reset() to clear any previous configuration, e.g. default
// configuration. For multi-step configuration, omit calling context.reset().
context.reset();
configurator.doConfigure(logbackXml);
} catch (JoranException je) {
// StatusPrinter will handle this
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
public String formatMessage(String key, Object... args) {
String ret = "";
try {
FormattingTuple tuple = MessageFormatter.arrayFormat(data.rb.getString(key), args);
ret = tuple.getMessage();
} catch (Exception e) {
logger.error(e.toString());
data.errorMessages++;
}
return ret;
}
public int getWarnMessages() {
return data.warnMessages;
}
public int getErrorMessages() {
return data.errorMessages;
}
public static int getTotalWarnMessages() {
int warnMessages = 0;
for (LoggerData data : dataMap.values()) {
warnMessages += data.warnMessages;
}
return warnMessages;
}
public static int getTotalErrorMessages() {
int errorMessages = 0;
for (LoggerData data : dataMap.values()) {
errorMessages += data.errorMessages;
}
return errorMessages;
}
public void error(String key, Object... args) {
if (logger.isErrorEnabled()) {
try {
logger.error(data.rb.getString(key), args);
} catch (Exception e) {
logger.error(e.toString());
data.errorMessages++;
}
}
data.errorMessages++;
}
public void warn(String key, Object... args) {
if (logger.isWarnEnabled()) {
try {
logger.warn(data.rb.getString(key), args);
} catch (Exception e) {
logger.error(e.toString());
data.errorMessages++;
}
}
data.warnMessages++;
}
public void info(String key, Object... args) {
if (logger.isInfoEnabled()) {
try {
logger.info(data.rb.getString(key), args);
} catch (Exception e) {
logger.error(e.toString());
data.errorMessages++;
}
}
}
public void infoMsg(String msg, Object... args) {
if (logger.isInfoEnabled()) {
try {
logger.info(msg, args);
} catch (Exception e) {
logger.error(e.toString());
data.errorMessages++;
}
}
}
public void debug(String key, Object... args) {
if (logger.isDebugEnabled()) {
try {
logger.debug(data.rb.getString(key), args);
} catch (Exception e) {
logger.error(e.toString());
data.errorMessages++;
}
}
}
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
}
| 5,156 | 23.557143 | 86 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphsupportlib/src/main/java/graphsupportlib/Metric.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphsupportlib;
import graphlib.Attribute;
import graphlib.AttributeComposite;
import graphlib.AttributeInt;
import graphlib.AttributeString;
import graphlib.Edge;
import graphlib.Edge.eDirectionType;
import graphlib.Node;
import java.util.ArrayList;
import java.util.List;
/**
* The Graphsupportlib contains the OpenStaticAnalyzer specific constants and methods of the general Graphlib.
*
*/
public class Metric {
// Context constants
public static final String CONTEXT_WARNING = "warning";
public static final String CONTEXT_METRIC = "metric";
public static final String CONTEXT_METRICGROUP = "metricgroup";
public static final String CONTEXT_ATTRIBUTE = "attribute";
public static final String CONTEXT_RUL = "rul";
// Attribute name constants
public static final String ATTR_WARNINGTEXT = "WarningText";
public static final String ATTR_POSITION = "Position";
public static final String ATTR_NAME = "Name";
public static final String ATTR_LONGNAME = "LongName";
public static final String ATTR_PATH = "Path";
public static final String ATTR_LINE = "Line";
public static final String ATTR_COLUMN = "Column";
public static final String ATTR_ENDLINE = "EndLine";
public static final String ATTR_ENDCOLUMN = "EndColumn";
public static final String ATTR_REALIZATIONLEVEL = "RealizationLevel";
public static final String ATTR_RUL_DESCRIPTION = "Description";
public static final String ATTR_RUL_DISPLAYNAME = "DisplayName";
public static final String ATTR_RUL_ENABLED = "Enabled";
public static final String ATTR_RUL_GROUPTYPE = "GroupType";
public static final String ATTR_RUL_HELPTEXT = "HelpText";
public static final String ATTR_RUL_SETTINGS = "Settings";
public static final String ATTR_RUL_PRIORITY = "Priority";
public static final String ATTR_RUL_WARNING = "Warning";
public static final String ATTR_RUL_CALCULATED = "Calculated";
public static final String ATTR_RUL_CALCULATEDFOR = "CalculatedFor";
public static final String ATTR_DCF_CLONESMELLTYPE = "CloneSmellType";
public static final String ATTR_UUID = "UUID";
public static final String ATTR_TUID = "TUID";
// Node type constants
public static final String NTYPE_ROOT = "TreeRoot";
public static final String NTYPE_RUL_METRIC = "RulMetric";
public static final String NTYPE_RUL_TOOL = "RulTool";
public static final String NTYPE_LIM_COMPONENT = "Component";
public static final String NTYPE_LIM_MODULE = "Module";
public static final String NTYPE_LIM_NAMESPACE = "Namespace";
public static final String NTYPE_LIM_PACKAGE = "Package";
public static final String NTYPE_LIM_ROOT = "Root";
public static final String NTYPE_LIM_CLASS = "Class";
public static final String NTYPE_LIM_STRUCTURE = "Strucutre";
public static final String NTYPE_LIM_UNION = "Union";
public static final String NTYPE_LIM_INTERFACE = "Interface";
public static final String NTYPE_LIM_ENUM = "Enum";
public static final String NTYPE_LIM_ANNOTATION = "Annotation";
public static final String NTYPE_LIM_SOURCEFILE = "SourceFile";
public static final String NTYPE_LIM_CLASSDEF = "ClassDef";
public static final String NTYPE_LIM_FUNCTION = "Function";
public static final String NTYPE_LIM_METHOD = "Method";
public static final String NTYPE_LIM_FUNCTIONMEMBER = "FunctionMember";
public static final String NTYPE_LIM_PROCEDURE = "Procedure";
public static final String NTYPE_LIM_FUNCTIONDEF = "FunctionDef";
public static final String NTYPE_LIM_METHODDEF = "MethodDef";
public static final String NTYPE_LIM_ATTRIBUTE = "Attribute";
public static final String NTYPE_LIM_FILESYSTEM = "FileSystem";
public static final String NTYPE_LIM_FOLDER = "Folder";
public static final String NTYPE_LIM_FILE = "File";
public static final String NTYPE_DCF_CLONECLASS = "CloneClass";
public static final String NTYPE_DCF_CLONEINSTANCE = "CloneInstance";
// Edge type constants
public static final String ETYPE_RUL_GROUPCONTAINS = "RulGroupContains";
public static final String ETYPE_RUL_TREE = "RulTree";
public static final String ETYPE_LIM_LOGICALTREE = "LogicalTree";
public static final String ETYPE_LIM_PHYSICALTREE = "PhysicalTree";
public static final String ETYPE_LIM_COMPONENTTREE = "ComponentTree";
public static final String ETYPE_LIM_COMPONENT = "Component";
public static final String ETYPE_LIM_VARIANT = "Variant";
public static final String ETYPE_LIM_AGGREGATED = "Aggregated";
public static final String ETYPE_LIM_INSTANCE = "Instance";
public static final String ETYPE_LIM_DECLARES = "Declares";
public static final String ETYPE_DCF_CLONETREE = "CloneTree";
public static final String ETYPE_DCF_HASCLONE = "Clone";
// Attribute value constants
public static final String ATTRVALUE_INVALID = "__INVALID__";
public static final String ATTRVALUE_LIM_RELDECLARES = "declaration";
public static final String ATTRVALUE_LIM_RELDEFINES = "definition";
// Node UID constans
public static final String UID_RUL_ROOT = "__RulRoot__";
public static final String UID_CLONE_ROOT = "__CloneRoot__";
public static final String UID_LOGICAL_ROOT = "__LogicalRoot__";
public static final String UID_PHYSICAL_ROOT = "__PhysicalRoot__";
// Header Attributes
public static final String HEADER_ASG_KEY = "asg";
public static final String HEADER_ASG_VALUE_JAVA = "java";
public static final String HEADER_ASG_VALUE_CPP = "cpp";
public static final String HEADER_ASG_VALUE_C = "c";
/**
* Position of a specific SourceCodeElement like a method or warning.
* It has path, line, endline, column and endcolumn attributes.
*
*/
public static class Position {
public Position(String path, int line, int col, int endline, int endcol) {
this.path = path;
this.line = line;
this.col = col;
this.endline = endline;
this.endcol = endcol;
}
public String path;
public int line;
public int col;
public int endline;
public int endcol;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + col;
result = prime * result + endcol;
result = prime * result + endline;
result = prime * result + line;
result = prime * result + ((path == null) ? 0 : path.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Position other = (Position) obj;
if (col != other.col)
return false;
if (endcol != other.endcol)
return false;
if (endline != other.endline)
return false;
if (line != other.line)
return false;
if (path == null) {
if (other.path != null)
return false;
} else if (!path.equals(other.path))
return false;
return true;
}
};
/**
* gives back node Metrics attributes in the node
*
* @param node the node
* @return the Metric attributes of the given node
*/
public static List<Attribute> getMetricAttributes(Node node) {
return node.findAttributeByContext(CONTEXT_METRIC);
}
/**
* gives back node Warning attributes in the node
*
* @param node the node
* @return the Metric attributes of the given node
*/
public static List<Attribute> getWarningAttributes(Node node) {
return node.findAttributeByContext(CONTEXT_WARNING);
}
/**
* get a position composite attribute from a node.
*
* @param node the node
* @return list of positions in the node
*/
public static ArrayList<Position> getPositionAttributes(Node node) {
ArrayList<Position> positions = new ArrayList<Position>();
int line = 0, col = 0, endline = 0, endcol = 0;
String path = "";
for (Attribute nodePositionAttributes : node.findAttribute(Attribute.aType.atComposite, ATTR_POSITION,
CONTEXT_ATTRIBUTE)) {
AttributeComposite nodePositionAttribute = (AttributeComposite) nodePositionAttributes;
path = ((AttributeString) nodePositionAttribute.findAttributeByName(ATTR_PATH).get(0)).getValue();
line = ((AttributeInt) nodePositionAttribute.findAttributeByName(ATTR_LINE).get(0)).getValue();
col = ((AttributeInt) nodePositionAttribute.findAttributeByName(ATTR_COLUMN).get(0)).getValue();
endline = ((AttributeInt) nodePositionAttribute.findAttributeByName(ATTR_ENDLINE).get(0)).getValue();
endcol = ((AttributeInt) nodePositionAttribute.findAttributeByName(ATTR_ENDCOLUMN).get(0)).getValue();
Position position = new Position(path, line, col, endline, endcol);
positions.add(position);
}
return positions;
}
/**
* Gives back an Attribute object of the node with the given attribute name
*
* @param node The node.
* @param attr The name of the attribute.
* @return Attribute Teh attribute with the given name in the node, null if it was not found.
*/
public static Attribute getNodeAttribute(Node node, String attr) {
for (Attribute attribute : node.getAttributes()) {
if (attribute.getName().equals(attr)) {
return attribute;
}
}
return null;
}
/**
* Gives back the first position of a node.
*
* @param node The node.
* @return position The first position of the node.
*/
public static Position getFirstPositionAttribute(Node node) {
AttributeComposite posAttr = (AttributeComposite) getNodeAttribute(node, ATTR_POSITION);
if (posAttr == null) {
return null;
} else {
String path = null;
int line = 0, col = 0, endline = 0, endcol = 0;
for (Attribute attr : posAttr.getAttributes()) {
if (ATTR_PATH.equals(attr.getName())) {
path = ((AttributeString) attr).getValue();
} else if (ATTR_LINE.equals(attr.getName())) {
line = ((AttributeInt) attr).getValue();
} else if (ATTR_COLUMN.equals(attr.getName())) {
col = ((AttributeInt) attr).getValue();
} else if (ATTR_ENDLINE.equals(attr.getName())) {
endline = ((AttributeInt) attr).getValue();
} else if (ATTR_ENDCOLUMN.equals(attr.getName())) {
endcol = ((AttributeInt) attr).getValue();
}
}
return new Position(path, line, col, endline, endcol);
}
}
/**
* Gives back the first node by edgeType
*
* @param node The node.
* @param edgeType Default is LogicalTree
* @return the first node by edgeType, null if cant find any node
*/
public static Node getFirstNodeByEdgeType(Node node, String edgeType) {
if (getNodesByEdgeType(node, edgeType, eDirectionType.edtDirectional).isEmpty()) {
return null;
} else {
return getNodesByEdgeType(node, edgeType, eDirectionType.edtDirectional).get(0);
}
}
/**
* Gives back the first node by edgetype
*
* @param node The node.
* @param edgeType Default is LogicalTree
* @return null if cant find any node
*/
public static Node getFirstNodeByEdgeType(Node node, String edgeType, eDirectionType directionType) {
if (getNodesByEdgeType(node, edgeType, directionType).isEmpty()) {
return null;
} else {
return getNodesByEdgeType(node, edgeType, directionType).get(0);
}
}
/**
* Gives back the children of the node
*
* @param node he node.
* @param edgeType The types of the nodes.
* @return list of children
*/
public static List<Node> getNodesByEdgeType(Node node, String edgeType, eDirectionType directionType) {
List<Node> result = new ArrayList<Node>();
for (Edge cloneEdge : node.getOutEdges()) {
if (cloneEdge.getType().getType().equals(edgeType) && cloneEdge.getType().getDirectionType().equals(directionType)) {
result.add(cloneEdge.getToNode());
}
}
return result;
}
}
| 12,719 | 36.857143 | 129 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/columbus/WarningMessages.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package columbus;
public class WarningMessages {
public static final String INVALID_IO_MODE = "Invalid IO mode!";
public static final String STRING_LENGTH = "The string length is greater than 65535";
public static final String EOF_REACHED = "Unexpected EOF detected";
public static final String BUCKET_FULL = "Bucket is full!";
public static final String WRONG_FILE_FORMAT = "Wrong file format!";
public static final String NODE_ALREADY_EXIST = "Node already exists!";
}
| 1,211 | 35.727273 | 86 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/columbus/StrTable.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package columbus;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* StrTable class is responsible for storing/loading/saving strings.
*/
public class StrTable {
public static enum StrType {
strDefault, strTmp, strToSave
}
public StrTable() {
this(511);
}
@SuppressWarnings("unchecked")
public StrTable(int buckets) {
noBuckets = buckets;
strTable = new TreeMap[noBuckets];
count = new int[noBuckets];
for (int i = 0; i < noBuckets; i++) {
strTable[i] = new TreeMap<Integer, Pair>();
count[i] = 1;
}
}
private int hash(String string) {
int hashHi = 0;
int hashLow = 0;
if (string == null)
return 0;
if (string.length() == 0)
return 0;
char[] convertedString = string.toCharArray();
for (int i = 0; i < convertedString.length; i++) {
convertedString[i] &= 0xFF;
hashHi = randomNumbers[hashHi ^ convertedString[i]];
}
convertedString[0]++;
convertedString[0] &= 0xFF;
for (int i = 0; i < convertedString.length; i++)
hashLow = randomNumbers[hashLow ^ convertedString[i]];
return (hashHi << 8) | hashLow;
}
private int get(String s, int hashValue, int bucketIndex) {
SortedMap<Integer, Pair> bucket = strTable[bucketIndex];
SortedMap<Integer, Pair> sm = bucket.subMap(hashValue << 16, (hashValue << 16) + 0xFFFF);
for (Iterator<Map.Entry<Integer, Pair>> it = sm.entrySet().iterator(); it.hasNext();) {
Map.Entry<Integer, Pair> entry = it.next();
if (entry.getValue().string.equals(s))
return entry.getKey();
}
Pair entry = bucket.get((hashValue + 1) << 16);
if (entry != null && entry.string.equals(s))
return ((hashValue + 1) << 16);
return 0;
}
public int get(String s) {
if (s == null)
return 0;
if (s.length() == 0)
return 0;
int hashValue = hash(s);
int bucketIndex = hashValue % noBuckets;
return get(s, hashValue, bucketIndex);
}
public String get(int key) {
if (key == 0)
return "";
int bucketIndex = (key >>> 16) % noBuckets;
Pair value = strTable[bucketIndex].get(key);
if (value != null)
return value.string;
return "";
}
public int set(String s) throws ColumbusException {
if (s == null)
return 0;
if (s.length() == 0)
return 0;
int key = 0;
int hashValue = hash(s);
int bucketIndex = hashValue % noBuckets;
if ((key = get(s, hashValue, bucketIndex)) == 0) {
key = (hashValue << 16) | count[bucketIndex]++;
if (count[bucketIndex] == 0xFFFF) {
throw new ColumbusException(WarningMessages.BUCKET_FULL);
}
strTable[bucketIndex].put(key, new Pair(s, StrType.strDefault));
}
return key;
}
public void setType(String s, StrType type) throws ColumbusException {
if (s == null)
return;
if (s.length() == 0)
return;
int key = 0;
int hashValue = hash(s);
int bucketIndex = hashValue % noBuckets;
if ((key = get(s, hashValue, bucketIndex)) == 0) {
key = (hashValue << 16) | count[bucketIndex]++;
if (count[bucketIndex] == 0xFFFF) {
throw new ColumbusException(WarningMessages.BUCKET_FULL);
}
strTable[bucketIndex].put(key, new Pair(s, StrType.strDefault));
} else
strTable[bucketIndex].get(key).type = type;
}
public void setType(int key, StrType type) {
int bucket_index = (key >>> 16) % noBuckets;
Pair value = strTable[bucket_index].get(key);
if (value != null)
value.type = type;
}
public void save(IO io, StrType filterType) throws ColumbusException {
io.writeString("STRTBL");
io.writeInt4(noBuckets);
for (int i = 0; i < noBuckets; i++)
io.writeUShort2(count[i]);
// write out each element
for (int i = 0; i < noBuckets; i++) {
save(io, filterType, i, false);
save(io, filterType, i, true);
}
// Write out the end of StringTable sign
io.writeInt4(0);
}
private void save(IO io, StrType filterType, int bucketIndex, boolean negative) throws ColumbusException {
for (Map.Entry<Integer, Pair> entry : strTable[bucketIndex].entrySet()) {
if (negative && entry.getKey() >= 0)
continue;
else if (!negative && entry.getKey() < 0)
continue;
if (filterType == StrType.strTmp) { // In tmp mode nodes with tmp flag will be skipped.
if (entry.getValue().type == StrType.strTmp)
continue;
} else if (filterType == StrType.strToSave) { // In save mode only nodes with save flag will be written out.
if (entry.getValue().type != StrType.strToSave)
continue;
}
io.writeInt4(entry.getKey()); // The key (4)
io.writeLongString(entry.getValue().string); // Size and characters of the string (4 + n)
}
}
@SuppressWarnings("unchecked")
public void load(IO io) throws ColumbusException {
String id = io.readString(6);
if (!"STRTBL".equals(id)) {
throw new ColumbusException(WarningMessages.WRONG_FILE_FORMAT);
}
noBuckets = io.readInt4();
strTable = new TreeMap[noBuckets];
count = new int[noBuckets];
for (int i = 0; i < noBuckets; i++) {
strTable[i] = new TreeMap<Integer, Pair>();
count[i] = io.readUShort2();
}
int key;
String str;
int bucketIndex;
while ((key = io.readInt4()) != 0) {
str = io.readLongString();
bucketIndex = (key >>> 16) % noBuckets;
strTable[bucketIndex].put(key, new Pair(str, StrType.strDefault));
}
}
protected static class Pair {
String string;
StrType type;
public Pair(String s, StrType st) {
string = s;
type = st;
}
}
protected static final int randomNumbers[] = { 1, 14, 110, 25, 97, 174, 132, 119, 138, 170, 125, 118, 27, 233, 140, 51,
87, 197, 177, 107, 234, 169, 56, 68, 30, 7, 173, 73, 188, 40, 36, 65, 49, 213, 104, 190, 57, 211, 148, 223,
48, 115, 15, 2, 67, 186, 210, 28, 12, 181, 103, 70, 22, 58, 75, 78, 183, 167, 238, 157, 124, 147, 172, 144,
176, 161, 141, 86, 60, 66, 128, 83, 156, 241, 79, 46, 168, 198, 41, 254, 178, 85, 253, 237, 250, 154, 133,
88, 35, 206, 95, 116, 252, 192, 54, 221, 102, 218, 255, 240, 82, 106, 158, 201, 61, 3, 89, 9, 42, 155, 159,
93, 166, 80, 50, 34, 175, 195, 100, 99, 26, 150, 16, 145, 4, 33, 8, 189, 121, 64, 77, 72, 208, 245, 130,
122, 143, 55, 105, 134, 29, 164, 185, 194, 193, 239, 101, 242, 5, 171, 126, 11, 74, 59, 137, 228, 108, 191,
232, 139, 6, 24, 81, 20, 127, 17, 91, 92, 251, 151, 225, 207, 21, 98, 113, 112, 84, 226, 18, 214, 199, 187,
13, 32, 94, 220, 224, 212, 247, 204, 196, 43, 249, 236, 45, 244, 111, 182, 153, 136, 129, 90, 217, 202, 19,
165, 231, 71, 230, 142, 96, 227, 62, 179, 246, 114, 162, 53, 160, 215, 205, 180, 47, 109, 44, 38, 31, 149,
135, 0, 216, 52, 63, 23, 37, 69, 39, 117, 146, 184, 163, 200, 222, 235, 248, 243, 219, 10, 152, 131, 123,
229, 203, 76, 120, 209 };
protected int noBuckets;
protected int count[];
protected TreeMap<Integer, Pair> strTable[];
}
| 7,500 | 26.781481 | 120 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/columbus/ColumbusException.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package columbus;
/**
* Exception class for graphlib.
*/
@SuppressWarnings("serial")
public class ColumbusException extends Exception {
public ColumbusException() {
super();
}
public ColumbusException(String message) {
super(message);
}
public ColumbusException(String message, Throwable cause) {
super(message, cause);
}
public ColumbusException(Throwable cause) {
super(cause);
}
}
| 1,139 | 23.782609 | 85 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/columbus/IO.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package columbus;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.zip.InflaterInputStream;
/**
* IO class is responsible for reading/writing fix size data from/to files.
*/
public class IO {
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
public enum IOMode {
READ, WRITE
}
private FilterInputStream in;
private BufferedOutputStream out;
public IO(String name, IOMode mode) throws ColumbusException {
try {
if (mode == IOMode.READ) {
in = new BufferedInputStream(new FileInputStream(name));
} else if (mode == IOMode.WRITE) {
out = new BufferedOutputStream(new FileOutputStream(name));
} else {
throw new ColumbusException(WarningMessages.INVALID_IO_MODE);
}
} catch (FileNotFoundException e) {
throw new ColumbusException(e);
}
}
public void close() throws ColumbusException {
try {
if (in != null)
in.close();
else if (out != null)
out.close();
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeUByte1(int n) throws ColumbusException {
try {
out.write((n >>> 0) & 0xFF);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeUShort2(int n) throws ColumbusException {
try {
out.write((n >>> 0) & 0xFF);
out.write((n >>> 8) & 0xFF);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeBoolean1(boolean n) throws ColumbusException {
try {
out.write(n ? 1 : 0);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeByte1(byte n) throws ColumbusException {
try {
out.write((n >>> 0) & 0xFF);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeShort2(short n) throws ColumbusException {
try {
out.write((n >>> 0) & 0xFF);
out.write((n >>> 8) & 0xFF);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeChar2(char n) throws ColumbusException {
try {
out.write((n >>> 0) & 0xFF);
out.write((n >>> 8) & 0xFF);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeInt4(int n) throws ColumbusException {
try {
out.write((n >>> 0) & 0xFF);
out.write((n >>> 8) & 0xFF);
out.write((n >>> 16) & 0xFF);
out.write((n >>> 24) & 0xFF);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeLong8(long n) throws ColumbusException {
try {
out.write((byte) ((n >>> 0) & 0xFF));
out.write((byte) ((n >>> 8) & 0xFF));
out.write((byte) ((n >>> 16) & 0xFF));
out.write((byte) ((n >>> 24) & 0xFF));
out.write((byte) ((n >>> 32) & 0xFF));
out.write((byte) ((n >>> 40) & 0xFF));
out.write((byte) ((n >>> 48) & 0xFF));
out.write((byte) ((n >>> 56) & 0xFF));
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeFloat4(float n) throws ColumbusException {
writeInt4(Float.floatToIntBits(n));
}
public void writeDouble8(double n) throws ColumbusException {
writeLong8(Double.doubleToLongBits(n));
}
public void writeShortString(String s) throws ColumbusException {
try {
byte[] bytes = s.getBytes(UTF8_CHARSET);
int size = bytes.length;
if (size > 0xFFFF)
throw new ColumbusException(WarningMessages.STRING_LENGTH);
writeUShort2(size);
out.write(bytes, 0, size);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeLongString(String s) throws ColumbusException {
try {
byte[] bytes = s.getBytes(UTF8_CHARSET);
writeInt4(bytes.length);
out.write(bytes, 0, bytes.length);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void writeString(String s) throws ColumbusException {
try {
byte[] bytes = s.getBytes(UTF8_CHARSET);
out.write(bytes, 0, bytes.length);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public short readUByte1() throws ColumbusException {
try {
long n = in.read();
return (short) n;
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public int readUShort2() throws ColumbusException {
try {
long n = in.read();
n |= in.read() << 8;
return (int) n;
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public long readUInt4() throws ColumbusException {
try {
long n = in.read();
n |= in.read() << 8;
n |= in.read() << 16;
n |= (long) in.read() << 24;
return n;
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public boolean readBoolean1() throws ColumbusException {
try {
int n = in.read();
return n != 0;
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public byte readByte1() throws ColumbusException {
try {
int n = in.read();
return (byte) n;
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public short readShort2() throws ColumbusException {
try {
int n = in.read();
n |= in.read() << 8;
return (short) n;
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public char readChar2() throws ColumbusException {
try {
int n = in.read();
n |= in.read() << 8;
return (char) n;
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public int readInt4() throws ColumbusException {
try {
int n = in.read();
n |= in.read() << 8;
n |= in.read() << 16;
n |= in.read() << 24;
return n;
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public long readLong8() throws ColumbusException {
try {
long n = in.read();
n |= in.read() << 8;
n |= in.read() << 16;
n |= (long) in.read() << 24;
n |= (long) in.read() << 32;
n |= (long) in.read() << 40;
n |= (long) in.read() << 48;
n |= (long) in.read() << 56;
return n;
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public float readFloat4() throws ColumbusException {
return Float.intBitsToFloat(readInt4());
}
public double readDouble8() throws ColumbusException {
return Double.longBitsToDouble(readLong8());
}
public String readShortString() throws ColumbusException {
return readString(readUShort2());
}
public String readLongString() throws ColumbusException {
return readString(readInt4());
}
public String readString(int size) throws ColumbusException {
try {
byte[] array = new byte[size];
int offset = 0;
int read = in.read(array, offset, size);
while (read != size) {
size -= read;
offset += read;
read = in.read(array, offset, size);
if (read == -1)
throw new ColumbusException(WarningMessages.EOF_REACHED);
}
return new String(array, UTF8_CHARSET);
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void skip(long bytes) throws ColumbusException {
try {
long skipped = in.skip(bytes);
while (skipped != bytes) {
bytes -= skipped;
skipped = in.skip(bytes);
}
} catch (IOException e) {
throw new ColumbusException(e);
}
}
public void setZipedReadMode() {
if (in != null)
in = new InflaterInputStream(in);
}
}
| 8,097 | 22.95858 | 85 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/AttributeComposite.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
/**
* An attribute which can not have value, it just stores other attributes.
*
*/
public class AttributeComposite extends Attribute {
AttributeComposite(String name, aType type, String context) {
super(name, type, context);
}
@Override
public String toString() {
return "AttributeString [name=" + name + ", context=" + context + ", type=" + type + "]";
}
}
| 1,124 | 27.846154 | 91 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/GraphlibException.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
/**
* Exception class for graphlib.
*/
@SuppressWarnings("serial")
public class GraphlibException extends Exception {
public GraphlibException() {
super();
}
public GraphlibException(String message) {
super(message);
}
public GraphlibException(String message, Throwable cause) {
super(message, cause);
}
public GraphlibException(Throwable cause) {
super(cause);
}
}
| 1,139 | 23.782609 | 85 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/Visitor.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
public interface Visitor {
/**
* Edge visitor
*/
public void edgeVisitorFunc(Edge e) throws VisitorException;
/**
* Post node visitor(will be called when using: traverseDepthFirstPostorder, traverseDepthFirst)
*/
public void postNodeVisitorFunc(Node node) throws VisitorException;
/**
* Pre node visitor (will be called when using: traverseBreadthFirst, traverseDepthFirstPreorder,
* traverseDepthFirst)
*/
public void preNodeVisitorFunc(Node node) throws VisitorException;
}
| 1,251 | 28.116279 | 98 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/Edge.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
import java.util.HashSet;
/**
* The edge between the nodes.
*
*/
public class Edge extends AttributeOwner {
public static class EdgeTypeSet extends HashSet<EdgeType> {
private static final long serialVersionUID = 3655474231108644180L;
}
private final Node fromNode;
private final Node toNode;
private final EdgeType type;
private Graph graph;
Edge(Node fromNode, Node toNode, EdgeType type) {
super();
this.fromNode = fromNode;
this.toNode = toNode;
this.type = type;
}
public Node getFromNode() {
return fromNode;
}
public Node getToNode() {
return toNode;
}
void setGraph(Graph graph) {
this.graph = graph;
}
public String getName() {
final String A = getFromNode().getUID();
final String B = getToNode().getUID();
switch (type.getDirectionType()) {
case edtBidirectional: {
return A + getType().getType() + B;
}
case edtDirectional: {
return A + getType().getType() + B;
}
case edtReverse: {
return B + getType().getType() + A;
}
default:
return "";
}
}
public EdgeType getType() {
return type;
}
/**
* If the type of the edge is edtDirectional and it has a reverse pair, it will return the reverse pair.
* Otherwise it will return null.
*/
public Edge getReversePair() {
return graph.getReversePair(this);
}
public static enum eDirectionType {
/**
* it has one edge to each directions
*/
edtBidirectional,
/**
* it has one edge to one direction
*/
edtDirectional,
/**
* it belongs to a directional edge
*/
edtReverse
};
public static class EdgeType {
String type; // type of the edge
eDirectionType direction; // direction of the edge
/**
* Creates empty EdgeType object
*/
protected EdgeType() {
}
/**
* Creates EdgeType object
*/
protected EdgeType(String type, int dtype) {
this.type = type;
this.direction = eDirectionType.values()[dtype];
}
/**
* Creates EdgeType object
*/
public EdgeType(String type, eDirectionType dtype) {
this.type = type;
this.direction = dtype;
}
/**
* Gives back the type name of edge
*/
public String getType() {
return this.type;
}
/**
* Gives back the direction of the edge
*/
public eDirectionType getDirectionType() {
return this.direction;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((direction == null) ? 0 : direction.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EdgeType other = (EdgeType) obj;
if (direction != other.direction)
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((fromNode == null) ? 0 : fromNode.getUID().hashCode());
result = prime * result + ((toNode == null) ? 0 : toNode.getUID().hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Edge other = (Edge) obj;
if (fromNode == null) {
if (other.fromNode.getUID() != null)
return false;
} else if (!fromNode.getUID().equals(other.fromNode.getUID()))
return false;
if (toNode == null) {
if (other.toNode != null)
return false;
} else if (!toNode.getUID().equals(other.toNode.getUID()))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
@Override
public String toString() {
return "Edge [fromNode=" + fromNode.getUID() + ", toNode=" + toNode.getUID() + ", type=" + type + "]";
}
}
| 4,895 | 21.254545 | 105 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/VisitorException.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
/**
* Exception class for graphlib.
*/
@SuppressWarnings("serial")
public class VisitorException extends Exception {
public VisitorException() {
super();
}
public VisitorException(String message) {
super(message);
}
public VisitorException(String message, Throwable cause) {
super(message, cause);
}
public VisitorException(Throwable cause) {
super(cause);
}
}
| 1,134 | 23.673913 | 85 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/AttributeInt.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
/**
* Attribute for storing integer values.
*
*/
public class AttributeInt extends Attribute {
AttributeInt(String name, aType type, String context) {
super(name, type, context);
}
int value;
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
public void incValue(int value) {
this.value += value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + value;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AttributeInt other = (AttributeInt) obj;
if (value != other.value)
return false;
return true;
}
@Override
public String toString() {
return "AttributeInt [value=" + value + ", name=" + name + ", context=" + context + ", type=" + type + "]";
}
}
| 1,716 | 21.893333 | 109 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/Node.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
public class Node extends AttributeOwner {
class NodeTypeSet extends HashSet<NodeType> {
private static final long serialVersionUID = 7379373638545944057L;
}
private final String UID;
private NodeType type;
private final List<Edge> edges = new LinkedList<Edge>();
void addEdge(Edge edge) {
edges.add(edge);
}
void deleteEdge(Edge edge) {
edges.remove(edge);
}
public Node(String UID, NodeType nodeType) {
super();
this.type = nodeType;
this.UID = UID;
}
public Node() {
UID = null;
}
public NodeType getType() {
return type;
}
void setType(NodeType nodeType) {
this.type = nodeType;
}
public String getUID() {
return UID;
}
public static class NodeType {
private String type;
/**
* Create empty NodeType
*/
protected NodeType() {
}
public NodeType(String type) {
this.type = type;
}
public String getType() {
return type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NodeType other = (NodeType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
/**
* It returns every out edge of the graph in a List.
*
* @return Out edges of the node.
*/
public List<Edge> getOutEdges() {
List<Edge> ret = new ArrayList<Edge>();
for (Edge edge : edges) {
ret.add(edge);
}
return ret;
}
/**
* It returns every out edge of the graph in a List with the given EdgeType.
*
* @param type Type of the outedges we would like to find.
* @return Out edges of the node with the given type.
*/
public List<Edge> findOutEdges(Edge.EdgeType type) {
List<Edge> ret = new ArrayList<Edge>();
for (Edge edge : edges) {
if (edge.getType().equals(type)) {
ret.add(edge);
}
}
return ret;
}
/**
* It returns every outedge of the graph in a List with the given types.
*
* @param typeset Types of the outedges we would like to find.
* @return Out edges of the node with the given type.
*/
public List<Edge> findOutEdges(Edge.EdgeTypeSet typeset) {
List<Edge> ret = new ArrayList<Edge>();
for (Edge edge : edges) {
if (typeset.contains(edge.getType())) {
ret.add(edge);
}
}
return ret;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((UID == null) ? 0 : UID.hashCode());
result = prime * result + ((edges == null) ? 0 : edges.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (UID == null) {
if (other.UID != null)
return false;
} else if (!UID.equals(other.UID))
return false;
if (edges == null) {
if (other.edges != null)
return false;
} else if (!edges.equals(other.edges))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 4,316 | 20.693467 | 85 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/AttributeFloat.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
/**
* Attribute for storing float values.
*
*/
public class AttributeFloat extends Attribute {
AttributeFloat(String name, aType type, String context) {
super(name, type, context);
}
float value;
public float getValue() {
return this.value;
}
public void setValue(float value) {
this.value = value;
}
public void incValue(float value) {
this.value += value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Float.floatToIntBits(value);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AttributeFloat other = (AttributeFloat) obj;
if (Float.floatToIntBits(value) != Float.floatToIntBits(other.value))
return false;
return true;
}
@Override
public String toString() {
return "AttributeString [value=" + value + ", name=" + name + ", context=" + context + ", type=" + type + "]";
}
}
| 1,802 | 22.723684 | 112 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/AttributeOwner.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* An abstract class which can store attributes.
*
*/
public abstract class AttributeOwner {
protected final List<Attribute> attributes = new LinkedList<Attribute>();
/**
* The given attribute will be added to the attribute owner.
*
* @param attribute The attribute we would like to add to the current attribute.
* @return The added attribute.
*/
public Attribute addAttribute(Attribute attribute) {
attributes.add(attribute);
return attribute;
}
/**
* The given attribute will be removed from the attribute owner.
*
* @param attribute The attribute we would like to remove.
* @return True if the deletion was happened, false otherwise.
*/
public boolean deleteAttribute(Attribute attribute) {
return attributes.remove(attribute);
}
/**
* The given attribute with the type and name will be removed from the attribute owner.
*
* @param type Type of the attribute we would like to delete.
* @param name Name of the attribute we would like to delete.
* @return True if the deletion was happened, false otherwise.
*/
public boolean deleteAttribute(Attribute.aType type, String name) {
boolean thereWasDelete = false;
for (Attribute attribute : attributes) {
if (attribute.getType().equals(type) && name.equals(attribute.getName())) {
thereWasDelete = deleteAttribute(attribute);
}
}
return thereWasDelete;
}
/**
* The given attribute with the type will be removed from the attribute owner.
*
* @param type Type of the attributes we would like to delete.
* @return True if the deletion was happened, false otherwise.
*/
public boolean deleteAttribute(Attribute.aType type) {
boolean thereWasDelete = false;
for (Attribute attribute : attributes) {
if (attribute.getType().equals(type)) {
thereWasDelete = deleteAttribute(attribute);
}
}
return thereWasDelete;
}
/**
* Returns with the attributes of the current attribute.
*
* @return The attributes of the current attribute.
*/
public List<Attribute> getAttributes() {
List<Attribute> ret = new ArrayList<Attribute>();
for (Attribute attribute : attributes) {
ret.add(attribute);
}
return ret;
}
/**
* It returns the attributes with the given type, name and context.
*
* @param type Type of the attributes we would like to find.
* @param name Name of the attributes we would like to find.
* @param context Context of the attributes we would like to find.
* @return List of the attributes were found.
*/
public List<Attribute> findAttribute(Attribute.aType type, String name, String context) {
List<Attribute> ret = new ArrayList<Attribute>();
for (Attribute attribute : attributes) {
if (attribute.getType().equals(type) && name.equals(attribute.getName())
&& attribute.getContext().equals(context)) {
ret.add(attribute);
}
}
return ret;
}
/**
* It returns the attributes with the given type.
*
* @param type Type of the attributes we would like to find.
* @return List of the attributes were found.
*/
public List<Attribute> findAttributeByType(Attribute.aType type) {
List<Attribute> ret = new ArrayList<Attribute>();
for (Attribute attribute : attributes) {
if (attribute.getType().equals(type)) {
ret.add(attribute);
}
}
return ret;
}
/**
* It returns the attributes with the given name.
*
* @param name Name of the attributes we would like to find.
* @return List of the attributes were found.
*/
public List<Attribute> findAttributeByName(String name) {
List<Attribute> ret = new ArrayList<Attribute>();
for (Attribute attribute : attributes) {
if (attribute.getName().equals(name)) {
ret.add(attribute);
}
}
return ret;
}
/**
* It returns the attributes with the given context.
*
* @param context Context of the attributes we would like to find.
* @return List of the attributes were found.
*/
public List<Attribute> findAttributeByContext(String context) {
List<Attribute> ret = new ArrayList<Attribute>();
for (Attribute attribute : attributes) {
if (attribute.getContext().equals(context)) {
ret.add(attribute);
}
}
return ret;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AttributeOwner other = (AttributeOwner) obj;
if (attributes == null) {
if (other.attributes != null)
return false;
} else if (!attributes.equals(other.attributes))
return false;
return true;
}
}
| 5,561 | 27.377551 | 90 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/Attribute.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
/**
* An abstract attribute class, it has name, context and type attribute, but does not have value.
* Their descendants extends it with a specific value type.
*
*/
public abstract class Attribute extends AttributeOwner {
final protected String name;
final protected String context;
final protected aType type;
Attribute(String name, aType type, String context) {
this.name = name;
this.type = type;
this.context = context;
}
public enum aType {
atInt, atFloat, atString, atComposite;
}
public String getName() {
return name;
}
public String getContext() {
return context;
}
public aType getType() {
return type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((context == null) ? 0 : context.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Attribute other = (Attribute) obj;
if (context == null) {
if (other.context != null)
return false;
} else if (!context.equals(other.context))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type != other.type)
return false;
return true;
}
}
| 2,269 | 23.945055 | 97 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/AttributeString.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
/**
* An attribute for storing String values.
*
*/
public class AttributeString extends Attribute {
AttributeString(String name, aType type, String context) {
super(name, type, context);
}
String value;
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
/**
* Appends the given string to the current value of the attribute.
* @param value The new appended value.
*/
public void incValue(String value) {
StringBuffer sb = new StringBuffer(this.value);
sb.append(value);
this.value = sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AttributeString other = (AttributeString) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public String toString() {
return "AttributeString [value=" + value + ", name=" + name + ", context=" + context + ", type=" + type + "]";
}
}
| 2,058 | 23.511905 | 112 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/graphlib/src/main/java/graphlib/Graph.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package graphlib;
import graphlib.Attribute.aType;
import graphlib.Edge.EdgeType;
import graphlib.Edge.EdgeTypeSet;
import graphlib.Edge.eDirectionType;
import graphlib.Node.NodeType;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import columbus.ColumbusException;
import columbus.IO;
import columbus.IO.IOMode;
import columbus.StrTable;
import columbus.StrTable.StrType;
import columbus.WarningMessages;
public class Graph extends AttributeOwner {
private final Map<String, String> header = new TreeMap<String, String>();
private final StrTable strTable = new StrTable();
private final Map<String, Node> nodeMap = new HashMap<String, Node>();
private final Map<String, NodeType> nodeTypeMap = new HashMap<String, NodeType>();
private final Map<String, EdgeType> edgeTypeMap = new HashMap<String, EdgeType>();
private final Map<Edge, Edge> edgePairMap = new HashMap<Edge, Edge>();
/**
* It return true if the node is exists with given UID in the graph.
*/
public boolean nodeIsExist(String UID) {
return nodeMap.containsKey(UID);
}
/**
* It creates a node with the given UID and type.
* It throws GraphlibException if the node is already in the graph.
* @throws GraphlibException If the given UID is not found exception will be thrown.
*/
public Node createNode(String UID, NodeType NTYPE) throws GraphlibException { // O(log(N))
if (nodeIsExist(UID)) {
throw new GraphlibException(WarningMessages.NODE_ALREADY_EXIST);
}
Node newNode = new Node(UID, NTYPE);
return newNode;
}
/**
* It adds the node to the graph.
* It throws GraphlibException if the node is already in the graph.
*
* @param node The node we would like to add.
* @return The added node.
* @throws GraphlibException If the given UID is already in the graph exception will be thrown.
*/
public Node addNode(Node node) throws GraphlibException { // O(log(N))
if (nodeMap.containsKey(node.getUID())) {
throw new GraphlibException(WarningMessages.NODE_ALREADY_EXIST);
}
return nodeMap.put(node.getUID(), node);
}
/**
* It deletes the node from the graph with the given UID.
*
* @param UID The UID of the node we would like to delete.
* @return If the deletion was success it returns true, otherwise false.
*/
public boolean deleteNode(String UID) { // O(log(N) + E))
Node node = nodeMap.get(UID);
if (node == null) {
return false;
}
return deleteNode(nodeMap.get(UID));
}
/**
* It deletes the node from the graph.
*
* @param node The node we would like to delete.
* @return If the deletion was success it returns true, otherwise false.
*/
public boolean deleteNode(Node node) {
node = nodeMap.get(node.getUID());
if (node == null) {
return false;
}
for(Edge edge : node.getOutEdges()){
deleteNode(edge.getToNode());
}
nodeMap.remove(node.getUID());
return true;
}
/**
*
* It deletes the node from the graph with the given NodeType..
*
* @param NTYPE The NodeType of the nodes we would like to delete.
* @return If the deletion was success it returns true, otherwise false.
*/
public boolean deleteNode(Node.NodeType NTYPE) {
boolean thereWasDelete = false;
for (Node node : getNodes()) {
if (node.getType().equals(NTYPE)) {
thereWasDelete = true;
nodeMap.remove(node.getUID());
}
}
return thereWasDelete;
}
/**
* It creates an edge from 'fromNode' to 'toNode' with the given type.
* If createReverse parameter is true it will create the reverse edge as well.
*
* @param fromNode The from node.
* @param toNode The to node.
* @param type The type of edge.
* @param createReverse If it is true it will create the reverse edge as well.
* @return The new edge.
*/
public Edge createDirectedEdge(Node fromNode, Node toNode, String type, boolean createReverse) {
if (!edgeTypeMap.containsKey(type)) {
edgeTypeMap.put(type, new EdgeType(type, eDirectionType.edtDirectional));
}
Edge edge = new Edge(fromNode, toNode, edgeTypeMap.get(type));
fromNode.addEdge(edge);
if (createReverse) {
Edge reverseEdge = new Edge(toNode, fromNode, new EdgeType(type, eDirectionType.edtReverse));
toNode.addEdge(reverseEdge);
}
return edge;
}
/**
* It creates an edge from 'fromUID' node to 'toUID' node with the given type.
* If createReverse parameter is true it will create the reverse edge as well.
*
*
* @param fromUID The UID of the from node.
* @param toUID The UID of the to node.
* @param type The type of edge.
* @param createReverse If it is true it will create the reverse edge as well.
* @return The new edge.
*/
public Edge createDirectedEdge(String fromUID, String toUID, String type, boolean createReverse) { // O(log(N))
return createDirectedEdge(nodeMap.get(fromUID), nodeMap.get(toUID), type, createReverse);
}
/**
* It creates an edge from 'fromNode' to 'toNode' with the given type.
* It also creates the reverse edge.
*
* @param fromNode The from node.
* @param toNode The to node.
* @param type The type of edge.
* @return The new edge.
*/
public Edge createBidirectedEdge(Node fromNode, Node toNode, String type) {
return createDirectedEdge(fromNode, toNode, type, true);
}
/**
* It creates an edge from 'fromUID' node to 'toUID' node with the given type.
* It also creates the reverse edge.
*
* @param fromUID The UID of the from node.
* @param toUID The UID of the to node.
* @param type The type of edge.
* @return The new edge.
*/
public Edge createBidirectedEdge(String fromUID, String toUID, String type) { // O(log(N))
return createBidirectedEdge(nodeMap.get(fromUID), nodeMap.get(toUID), type);
}
/**
*
* It returns the node with the given UID.
* If the node not exists, it will return null.
*
* @param UID The UID of the node would like to find.
* @return The node if was found, otherwise null.
*/
public Node findNode(String UID) { // O(log(N))
return nodeMap.get(UID);
}
/**
* Returns every node with the given NodeType.
*
* @param NTYPE The type of the node.
* @return The nodes with the given type.
*/
public List<Node> findNodes(Node.NodeType NTYPE) { // O(N)
List<Node> nodes = new ArrayList<Node>();
for (Node node : nodeMap.values()) {
if (node.getType().equals(NTYPE)) {
nodes.add(node);
}
}
return nodes;
}
/**
* Deletes the given edge from the graph.
*
* @param edge The edge we would like to delete.
*/
public void deleteEdge(Edge edge) {
edge.getFromNode().deleteEdge(edge);
}
/**
* Deletes the edges from the graph with the given type.
*
* @param type The type of edges we would like to delete.
*/
public void deleteEdge(Edge.EdgeType type) {
for (Node node : nodeMap.values()) {
for (Edge edge : node.findOutEdges(type)) {
deleteEdge(edge);
}
}
}
/**
* Deletes the edges from the graph with the given type and direction.
*
* @param type The type of edges we would like to delete.
* @param direction The direction of edges we would like to delete.
*/
protected void deleteEdge(String type, int direction) {
deleteEdge(new EdgeType(type, direction));
}
/**
* Deletes the edges from the graph between the two nodes.
*
* @param fromNode The from node of edges we would like to delete.
* @param toNode The to node of edges we would like to delete.
*/
public void deleteEdge(Node fromNode, Node toNode) {
for (Edge edge : fromNode.getOutEdges()) {
if (edge.getToNode().equals(toNode)) {
deleteEdge(edge);
}
}
}
/**
* It saves the graph in binary format to the given path.
*
* @param filename The path where we would like to save the binary graph file.
* @throws GraphlibException It throws exception if something went wrong during the io process.
*/
public void saveBinary(String filename) throws GraphlibException {
IO io = null;
try {
io = new IO(filename, IOMode.WRITE);
strTable.save(io, StrType.strDefault);
// header
io.writeInt4(header.size());
for (Entry<String, String> e : header.entrySet()) {
io.writeInt4(strTable.get(e.getKey()));
io.writeInt4(strTable.get(e.getValue()));
}
// nodes
for (Node node : nodeMap.values()) {
io.writeInt4(strTable.get(node.getUID()));
io.writeInt4(strTable.get(node.getType().getType()));
io.writeInt4(node.attributes.size());
for (Attribute att : node.getAttributes()) {
saveAttribute(io, att);
}
// edges
for (Edge edge : node.getOutEdges()) {
if (!edge.getFromNode().getUID().equals(node.getUID())
|| edge.getType().direction == eDirectionType.edtReverse) {
continue;
}
io.writeInt4(strTable.get(edge.getType().getType()));
io.writeInt4(edge.getType().getDirectionType().ordinal());
io.writeInt4(strTable.get(edge.getToNode().getUID()));
boolean pair = edgePairMap.containsKey(edge);
io.writeBoolean1(pair);
io.writeInt4(edge.attributes.size());
for (Attribute att : edge.getAttributes()) {
saveAttribute(io, att);
}
if (pair) {
Edge edgePair = edgePairMap.get(edge);
io.writeInt4(edgePair.attributes.size());
for (Attribute att : edgePair.getAttributes()) {
saveAttribute(io, att);
}
}
}
io.writeInt4(0);
io.writeInt4(0);
io.writeInt4(0);
}
io.writeInt4(0);
io.writeInt4(0);
io.close();
} catch (ColumbusException e) {
throw new GraphlibException(e);
}
}
private void saveAttribute(IO io, Attribute attr) throws GraphlibException {
try {
int attrType = attr.getType().ordinal();
io.writeInt4(attrType);
io.writeInt4(strTable.get(attr.getName()));
io.writeInt4(strTable.get(attr.getContext()));
switch (attrType) {
case 0:
io.writeInt4(((AttributeInt) attr).getValue());
break;
case 1:
io.writeFloat4(((AttributeFloat) attr).getValue());
break;
case 2:
io.writeInt4(strTable.get(((AttributeString) attr).getValue()));
break;
case 3:
List<Attribute> itA = attr.getAttributes();
io.writeInt4(attr.attributes.size());
for(Attribute att : itA) {
saveAttribute(io, att);
}
break;
default:
break;
}
} catch (ColumbusException e) {
throw new GraphlibException(e);
}
}
private void loadAttributes(IO io, AttributeOwner parent) throws GraphlibException {
try{
int attrTypeKey = (int) io.readUInt4();
aType type = aType.values()[attrTypeKey];
int attrNameKey = (int) io.readUInt4();
String name = getFromStringTable(attrNameKey);
int contextKey = (int) io.readUInt4();
String context = getFromStringTable(contextKey);
switch (attrTypeKey) {
case 0: {
int value = io.readInt4();
AttributeInt attribute = new AttributeInt(name, type, context);
attribute.setValue(value);
parent.addAttribute(attribute);
break;
}
case 1: {
float value = io.readFloat4();
AttributeFloat attribute = new AttributeFloat(name, type, context);
attribute.setValue(value);
parent.addAttribute(attribute);
break;
}
case 2: {
String value = getFromStringTable((int) io.readUInt4());
AttributeString attribute = new AttributeString(name, type, context);
attribute.setValue(value);
parent.addAttribute(attribute);
break;
}
case 3:
AttributeComposite attribute = new AttributeComposite(name, type, context);
parent.addAttribute(attribute);
int numberOfComposites = (int) io.readUInt4();
for (int i = 0; i < numberOfComposites; i++) {
loadAttributes(io, attribute);
}
break;
default:
}
} catch (ColumbusException e) {
throw new GraphlibException(e);
}
}
private String getFromStringTable(long value) {
return strTable.get((int) value);
}
/**
* It loads the binary with the given filepath.
*
* @param filename The name of the binary graph file.
* @throws GraphlibException It throws exception if something went wrong during the io process.
*/
public void loadBinary(String filename) throws GraphlibException {
File file = new File(filename);
if (!file.exists()) {
throw new GraphlibException("File " + filename + " not found!");
}
IO io = null;
try {
io = new IO(filename, IOMode.READ);
strTable.load(io);
int num = (int) io.readUInt4();
for (int i = 0; i < num; i++) {
header.put(getFromStringTable(io.readUInt4()), getFromStringTable(io.readUInt4()));
}
// read the nodes
while (true) {
long UIDKey = io.readUInt4();
long nodeTypeKey = io.readUInt4();
// finished reading nodes
if (UIDKey == 0 && nodeTypeKey == 0) {
break;
}
// store the node in the HashMap
String nodeUID = getFromStringTable(UIDKey);
Node node = nodeMap.get(nodeUID);
if (node == null) {
String nodeTypeString = getFromStringTable(nodeTypeKey);
if (!nodeTypeMap.containsKey(nodeTypeString)) {
nodeTypeMap.put(nodeTypeString, new NodeType(nodeTypeString));
}
node = createNode(nodeUID, nodeTypeMap.get(getFromStringTable(nodeTypeKey)));
nodeMap.put(nodeUID, node);
} else if (node.getType() == null) {
String nodeTypeString = getFromStringTable(nodeTypeKey);
if (!nodeTypeMap.containsKey(nodeTypeString)) {
nodeTypeMap.put(nodeTypeString, new NodeType(nodeTypeString));
}
node.setType(nodeTypeMap.get(nodeTypeString));
}
// Read the attributes of the node
int numberOfAttrs = (int) io.readUInt4();
for (int i = 0; i < numberOfAttrs; i++) {
loadAttributes(io, node);
}
while (true) {
// Read the edges of the node
int edgeTypeInt = (int) io.readUInt4();
int dirTypeInt = (int) io.readUInt4();
int toNodeInt = (int) io.readUInt4();
// Finish reading the edges
if (edgeTypeInt == 0 && dirTypeInt == 0 && toNodeInt == 0) {
break;
}
String toNodeUID = getFromStringTable(toNodeInt);
Node toNode = nodeMap.get(toNodeUID);
if (toNode == null) {
toNode = new Node(toNodeUID, null);
nodeMap.put(toNodeUID, toNode);
}
String edgeType = getFromStringTable(edgeTypeInt);
Edge edge = createDirectedEdge(node, toNode, edgeType,
Edge.eDirectionType.edtReverse.ordinal() == dirTypeInt);
boolean pair = io.readBoolean1();
int numberOfEdgeAttributs = io.readInt4();
for (int i = 0; i < numberOfEdgeAttributs; i++) {
loadAttributes(io, edge);
}
if (pair) {
createReversePair(edge);
int numberOfEdgePairAttributes = io.readInt4();
for (int i = 0; i < numberOfEdgePairAttributes; i++) {
loadAttributes(io, edge);
}
}
}
}
io.close();
} catch (ColumbusException e) {
throw new GraphlibException(e);
}
}
private Edge createReversePair(Edge edge) {
String type = edge.getType().getType();
if (!edgeTypeMap.containsKey(type)) {
edgeTypeMap.put(type, new EdgeType(type, eDirectionType.edtDirectional.ordinal()));
}
Edge reverseEdge = new Edge(edge.getToNode(), edge.getFromNode(), new EdgeType(type,
eDirectionType.edtReverse.ordinal()));
for (Attribute att : edge.getAttributes()) {
reverseEdge.addAttribute(att);
}
reverseEdge.setGraph(this);
edge.getToNode().addEdge(reverseEdge);
edgePairMap.put(edge, reverseEdge);
edgePairMap.put(reverseEdge, edge);
return reverseEdge;
}
/**
* Executes a Breadth-First Traversal for the graph from startNode along the edges with types in the EdgeTypeSet.
* It will call edgeVisitorFunc function to every edge and the preNodeVisitorFunc to every node.
*
* @param startNode The start node where we would like to start the traversing.
* @param edgetypeset Types of the edges we would like to traverse.
* @param visitor The implemented visitor.
* @throws VisitorException Throws exception if something went wrong in the visitor.
*/
public void traverseBreadthFirst(Node startNode, EdgeTypeSet edgetypeset, Visitor visitor) throws VisitorException {
List<Node> nodes = new ArrayList<Node>();
Set<String> visitedNode = new TreeSet<String>();
nodes.add(startNode);
while (!nodes.isEmpty()) {
Node node = nodes.remove(0);
if (visitedNode.contains(node.getUID()))
{
continue;
}
visitedNode.add(node.getUID());
visitor.preNodeVisitorFunc(node);
for (Edge edge : node.getOutEdges()) {
if (!edgetypeset.contains(edge.getType())) {
continue;
}
visitor.edgeVisitorFunc(edge);
nodes.add(edge.getToNode());
}
}
}
/**
* Executes a Depth-First Traversal for the graph from startNode along the edges with types in the EdgeTypeSet.
* It will call edgeVisitorFunc function to every edge and the postNodeVisitorFunc to every node.
*
* @param startNode The start node where we would like to start the traversing.
* @param edgetypeset Types of the edges we would like to traverse.
* @param visitor The implemented visitor.
* @throws VisitorException Throws exception if something went wrong in the visitor.
*/
public void traverseDepthFirstPostorder(Node startNode, Edge.EdgeTypeSet edgetypeset, Visitor visitor) throws VisitorException {
Set<String> visitedNodes = new TreeSet<String>();
traverseDepthFirst(startNode, edgetypeset, visitor, visitedNodes, false, true, false);
}
/**
* Executes a Depth-First Traversal for the graph from startNode along the edges with types in the EdgeTypeSet.
* It will call edgeVisitorFunc function to every edge and the preNodeVisitorFunc to every node.
*
* @param startNode The start node where we would like to start the traversing.
* @param edgetypeset Types of the edges we would like to traverse.
* @param visitor The implemented visitor.
* @throws VisitorException Throws exception if something went wrong in the visitor.
*/
public void traverseDepthFirstPreorder(Node startNode, Edge.EdgeTypeSet edgetypeset, Visitor visitor) throws VisitorException {
Set<String> visitedNodes = new TreeSet<String>();
traverseDepthFirst(startNode, edgetypeset, visitor, visitedNodes, true, false, true);
}
/**
* Executes a Depth-First Traversal for the graph from startNode along the edges with types in the EdgeTypeSet.
* It will call edgeVisitorFunc function to every edge and the preNodeVisitorFunc and postNodeVisitorFunc to every node.
*
* @param startNode The start node where we would like to start the traversing.
* @param edgetypeset Types of the edges we would like to traverse.
* @param visitor The implemented visitor.
* @throws VisitorException Throws exception if something went wrong in the visitor.
*/
public void traverseDepthFirst(Node startNode, Edge.EdgeTypeSet edgetypeset, Visitor visitor) throws VisitorException {
Set<String> visitedNodes = new TreeSet<String>();
traverseDepthFirst(startNode, edgetypeset, visitor, visitedNodes, true, true, true);
}
protected void traverseDepthFirst(Node startNode, Edge.EdgeTypeSet edgetypeset, Visitor visitor, Set<String> visitedNodes, boolean preNode, boolean postNode, boolean preEdge) throws VisitorException {
if (visitedNodes.contains(startNode.getUID()))
return;
visitedNodes.add(startNode.getUID());
if (preNode)
{
visitor.preNodeVisitorFunc(startNode);
}
Map<String, List<Edge>> orderedEdges = new TreeMap<String, List<Edge>>();
for (Edge edge : startNode.getOutEdges()) {
List<Edge> edges = null;
String toNode = edge.getToNode().getUID();
if (!orderedEdges.containsKey(toNode))
{
edges = new ArrayList<Edge>();
orderedEdges.put(toNode, edges);
}
else
{
edges = orderedEdges.get(toNode);
}
edges.add(edge);
}
for (List<Edge> edgeList : orderedEdges.values()) {
if (!preEdge)
{
traverseDepthFirst(edgeList.get(0).getToNode(), edgetypeset, visitor, visitedNodes, preNode, postNode, preEdge);
}
for (Edge edge : edgeList)
{
if (!edgetypeset.contains(edge.getType()))
{
continue;
}
visitor.edgeVisitorFunc(edge);
}
if (preEdge)
{
traverseDepthFirst(edgeList.get(0).getToNode(), edgetypeset, visitor, visitedNodes, preNode, postNode, preEdge);
}
}
if (postNode)
{
visitor.postNodeVisitorFunc(startNode);
}
}
/**
* It finds every root node from the graph by edgeType
*/
public Set<Node> getRootByEdgeType(Edge.EdgeType edgeType) {
Set<Node> rootNodes = new HashSet<Node>();
Set<Node> toNodes = new HashSet<Node>();
Set<Node> fromNodes = new HashSet<Node>();
for (Node node : getNodes()) {
List<Edge> edges = node.findOutEdges(edgeType);
if (!edges.isEmpty()) {
fromNodes.add(node);
}
for (Edge edge : edges) {
toNodes.add(edge.getToNode());
}
}
for (Node node : toNodes) {
if (!fromNodes.contains(node)) {
rootNodes.add(node);
}
}
return rootNodes;
}
protected Set<Node> getRootByEdgeType(String type, int direction) {
return getRootByEdgeType(new EdgeType(type, direction));
}
/**
* Add or update the headerinfo with the given key and value.
*
* @param key The key of the headerinfo.
* @param value The value of the headerinfo.
* @throws GraphlibException Throws exception if we could not map the given String to to StringTable.
*/
public void setHeaderInfo(String key, String value) throws GraphlibException {
try{
strTable.set(key);
strTable.set(value);
header.put(key, value);
} catch (ColumbusException e) {
throw new GraphlibException(e);
}
}
/**
* Get the headerinfo with the given key.
*
* @param key The key of the headerinfo.
* @return The value of the headerinfo with the given key.
*/
public String getHeaderInfo(String key) {
return header.get(key);
}
/**
* Delete information from the header with the given key.
*
* @param key The key of the headerinfo
* @return True if the deletion was success, false otherwise.
*/
public boolean deleteHeaderInfo(String key) {
if (header.remove(key) != null) {
return true;
}
return false;
}
/**
* Delete all information from header
*/
public void clearHeaderInfo() {
header.clear();
}
/**
* Get every node in the graph in a list.
* @return Every node in the graph in a list.
*/
public List<Node> getNodes() {
List<Node> nodes = new ArrayList<Node>();
for (Node node : nodeMap.values()) {
nodes.add(node);
}
return nodes;
}
Edge getReversePair(Edge edge) {
return edgePairMap.get(edge);
}
}
| 23,328 | 29.655716 | 201 | java |
OpenStaticAnalyzer | OpenStaticAnalyzer-master/java/lib/revision/src/columbus/revision/Revision.java | /*
* This file is part of OpenStaticAnalyzer.
*
* Copyright (c) 2004-2018 Department of Software Engineering - University of Szeged
*
* Licensed under Version 1.2 of the EUPL (the "Licence");
*
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence in the LICENSE file or at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
/* DO NOT MODIFY THIS FILE! IT IS USED TO GENERATE REVISION INFORMATION! */
package columbus.revision;
public class Revision {
private static String revision = "@GIT_HASH@";
private static String branchNumber = "";
public static String getRevision(){
return revision;
}
public static String getBranchNumber(){
return branchNumber;
}
}
| 1,102 | 29.638889 | 85 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.