How to force renaming of variable names in eclipse mars - java

How can I force eclipse mars to rename variable names?
When I try, I get
This refactoring cannot be performed correctly due to syntax errors in
the compilation unit.
The dialog only offers "Cancel".
It was possible to do this in older versions of eclipse, and I used the feature extensively, for example after copy&paste of code snippets found on the net.
Note this is not a duplicate of Refactoring variable names in Eclipse .
Edit 3 (summary of what happened):
In the code (shown below) were not only those common errors like missing imports or undeclared variables, but also a missing ";", thus a true syntax error. This, at first hidden among several other compiling issues, caused eclipse to refuse the refactoring.
As it turned out, this is not a special feature of mars but also of older versions of eclipse.
Edit: here comes my example code. It is mainly based on the examples from tutorialspoint for mongodb but very probably doesn't have anything to do with mongo.
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC2 {
private static String myUserName;
private static String myPassword;
private static String myHost = "localhost";
private static String myDatabaseName = "mydb";
private static MongoDatabase db;
public MongoDBJDBC2() {
initDb();
// TODO Auto-generated constructor stub
}
public static void main(String args[]) {
MongoDBJDBC2 mo = new MongoDBJDBC2();
}
private static void initDb() {
MongoClientURI uri = new MongoClientURI(
"mongodb://" + myUserName + ":" + myPassword + "#" + myHost + "/?authSource=db1");
try (MongoClient mongoClient = new MongoClient(uri);) {
db = mongoClient.getDatabase(myDatabaseName);
System.out.println("Connect to database successfully");
// boolean auth = db.authenticate(myUserName, myPassword);
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
public static void main4( String args[] ) {
try{
// To connect to mongodb server
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Now connect to your databases
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
DBCursor cursor = coll.find();
while (cursor.hasNext()) {
DBObject updateDocument = cursor.next();
updateDocument.put("likes","200")
col1.update(updateDocument);
}
System.out.println("Document updated successfully");
cursor = coll.find();
int i = 1;
while (cursor.hasNext()) {
System.out.println("Updated Document: "+i);
System.out.println(cursor.next());
i++;
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
I try to rename db to myDb in
private static MongoDatabase db;
Previously I used eclipse Helios and never encountered this kind of "feature".
Edit2: I have located the fatal error. In method "main4" a semicolon is missing after
updateDocument.put("likes", "200")
Still don't understand why this upsets eclipse so much that it refuses to refactor, and I still would like to know if there is a way to force refactoring despite of errors.

Compilers issue two kinds of errors: syntax errors and all other kinds of errors, like "type mismatch" and "symbol not found". Eclipse complains about a syntax error. Are you sure that in previous occasions when Eclipse agreed to refactor your code despite the fact that it contained errors, it was syntax errors that your code contained? You see, there is a big difference.
Refactoring symbol names in java is far more involved than a simple text search and replace, the structure of your code has to be taken into account.
But in the case of a syntax error, the compiler has given up parsing your file, so it does not know the structure of your code: it does not know which tokens are variables, which tokens are types, which tokens are methods, etc. so it really cannot do the refactoring that you want.
So, if you must really proceed with your refactoring despite having syntax errors, then I am afraid that text search and replace is the way to go for you in this particular case.
But fixing the syntax errors before attempting to refactor would be the most prudent thing to do.

This happens when there is compilation issue in your code.
Fix the compilation issue than you can refactor your code.Yes this feature is recently introduced in newer version of eclipse.

Related

Non-Terminating Z3Str3 from z3-4.8.9-x64-ubuntu-16.04

I am having a problem when trying to use the Z3Str3 from z3-4.8.9-x64-ubuntu-16.04 notably if I substitute the com.microsoft.z3.jar to the one in z3-4.8.8-x64-ubuntu-16.04 I no longer have that issue. The problem is that the Z3 process never comes back with a result, despite the simplicity of the query. I noticed though that it returns the valid answer when I kill my program. I am not noticing that behavior when I am trying to run the same query on the executable, so I am guessing there is something about using the jar file that I might need to tweak one way or the other.
Here is my code. I am using Ubuntu 16.04 LTS, and IntelliJ version ultimate 2020.3.
Many thanks!
import com.microsoft.z3.*;
public class Z3String3Processor_reduced {
public static void main(String[] args) {
StringBuilder currentQuery = new StringBuilder("\n" +
"(declare-const string0 String)\n" +
"(assert (= (str.indexof string0 \"a\" 1) 6))\n" +
"(check-sat)\n" +
"(get-model)\n" +
"\n");
Context context1 = new Context();
Solver solver1 = context1.mkSolver();
Params params = context1.mkParams();
params.add("smt.string_solver", "z3str3");
solver1.setParameters(params);
StringBuilder finalQuery = new StringBuilder(currentQuery.toString());
// attempt to parse the query, if successful continue with checking satisfiability
try {
// throws z3 exception if malformed or unknown constant/operation
BoolExpr[] assertions = context1.parseSMTLIB2String(finalQuery.toString(), null, null, null, null);
solver1.add(assertions);
// check sat, if so we can go ahead and get the model....
if (solver1.check() == Status.SATISFIABLE) {
System.out.println("sat");
} else
System.out.println("not sat");
context1.close();
} catch (Z3Exception e) {
System.out.println("Z3 exception: " + e.getMessage());
}
}
}
I don't think this has anything to do with Java. Let's extract your query and put it in a file named a.smt2:
$ cat a.smt2
(declare-const string0 String)
(assert (= (str.indexof string0 "a" 1) 6))
(check-sat)
(get-model)
Now, if I run:
$ z3 a.smt2
sat
(
(define-fun string0 () String
"FBCADEaGaa")
)
That's good. But if I run:
$ z3 smt.string_solver=z3str3 a.smt2
... does not terminate ..
So, bottom line, your query (as simple as it looks), gives hard time to the z3str3 solver.
I see that you already reported this as a bug at https://github.com/Z3Prover/z3/issues/5673
Given that the default string-solver can handle the query just fine, why not just use that one? If you have to use z3str3 for some other reason, then you've found a case where it doesn't handle this query well; I'm not sure how inclined the z3 folks will be to fix this given the query is handled by the default solver rather quickly. Please report what you find out!

GraalVM native-image and Oracle ojdbc11-21.1

I am currentliy experimenting with the native-image tool from GraalVM and the Oracle-driver. The source code compiles and generates an exe File without errors. But when I start the program it gets a java.lang.RuntimeException: Missing character set id 170 not loaded at image build time.
I am connecting to a database with characterset NLS_CHARACTERSET = EE8MSWIN1250.
When I use a database with NLS_CHARACTERSET = AL32UTF8 the connection works fine.
I am using GraalVM CE 21.0.0.2 (build 11.0.10+8-jvmci-21.0-b06 and ojdbc11-21.1.0.0.jar on a Windows 10 64bit Computer.
Below ist the error message and the source code. I used the sample code from https://github.com/oracle/oracle-db-examples/blob/master/java/jdbc/ConnectionSamples/DataSourceSample.java
Exception in thread "main" java.lang.RuntimeException: Missing character set id 170 not loaded at image build time at oracle.sql.CharacterSet.make(CharacterSet.java:121) at oracle.jdbc.driver.DBConversion.init(DBConversion.java:184) at oracle.jdbc.driver.DBConversion.(DBConversion.java:137) at oracle.jdbc.driver.T4CConnection.doCharSetNegotiation(T4CConnection.java:2607) at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:2176) at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:644) at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:1069) at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:90) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:681) at oracle.jdbc.datasource.impl.OracleDataSource.getPhysicalConnection(OracleDataSource.java:569) at oracle.jdbc.datasource.impl.OracleDataSource.getConnection(OracleDataSource.java:355) at oracle.jdbc.datasource.impl.OracleDataSource.getConnectionInternal(OracleDataSource.java:2014) at oracle.jdbc.datasource.impl.OracleDataSource.getConnection(OracleDataSource.java:330) at oracle.jdbc.datasource.impl.OracleDataSource.getConnection(OracleDataSource.java:291) at DataSourceSample.main(DataSourceSample.java:24)
DataSourceSample.java
/* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.*/
import java.sql.SQLException;
import java.util.Properties;
import oracle.jdbc.pool.OracleDataSource;
import oracle.jdbc.OracleConnection;
import java.sql.DatabaseMetaData;
public class DataSourceSample {
final static String DB_URL= "jdbc:oracle:thin:#****:1525/****";
final static String DB_USER = "****";
final static String DB_PASSWORD = "****";
public static void main(String args[]) throws SQLException {
Properties info = new Properties();
info.put(OracleConnection.CONNECTION_PROPERTY_USER_NAME, DB_USER);
info.put(OracleConnection.CONNECTION_PROPERTY_PASSWORD, DB_PASSWORD);
info.put(OracleConnection.CONNECTION_PROPERTY_DEFAULT_ROW_PREFETCH, "20");
OracleDataSource ods = new OracleDataSource();
ods.setURL(DB_URL);
ods.setConnectionProperties(info);
try (OracleConnection connection = (OracleConnection) ods.getConnection()) {
DatabaseMetaData dbmd = connection.getMetaData();
System.out.println("Driver Name: " + dbmd.getDriverName());
System.out.println("Driver Version: " + dbmd.getDriverVersion());
System.out.println("Default Row Prefetch Value is: " +
connection.getDefaultRowPrefetch());
System.out.println("Database Username is: " + connection.getUserName());
System.out.println();
}
}
}
I'm not 100% sure that it's the culprit, but here's the general idea about native image and charsets.
Native image doesn't include all possible charsets by default, you can configure it to do so by using the following option:
-H:+AddAllCharsets
Another possible option is to initialize the CharSet onject in a class that is configured to be initialized at build time of the native image. Then the charset object will be saved in the "image heap" and will be available at runtime.
Here's a sample application that illustrates this behavior: https://github.com/shelajev/workshop/tree/main/3
Of course it might be something different, but I think this should solve the problem you're experiencing.

Can't resolve Log Forging Fortify issue

I am having trouble fixing a Log Forging issue in Fortify. The issue, "writes unvalidated user input to the log", is being raised from both of the logging calls in the getLongFromTimestamp() method.
public long getLongFromTimestamp(final String value) {
LOGGER.info("getLongFromTimestamp(" + cleanLogString(value) + ")");
long longVal = 0;
Date tempDate = null;
try {
tempDate = new SimpleDateFormat(FORMAT_YYYYMMDDHHMMSS, Locale.US).parse(value);
} catch (ParseException e) {
LOGGER.warn("Failed to convert to Date: " + cleanLogString(value) + " Exception: " + cleanLogString(e.getMessage()));
throw new Exception(e);
}
if (tempDate != null) {
longVal = tempDate.getTime();
}
return longVal;
}
private cleanLogString(String logString) {
String clean = logString.replaceAll("[^A-Za-z0-9]", "");
if(!logString.equals(clean)) {
clean += " (CLEANED)";
}
return clean;
}
The cleanLogString() method has fixed other Log Forging Fortify issues in my project, however it has no effect on the 2 above.
Any help would be appreciated!
It is possible to use fortify Java annotations to tell Fortify that the data returned from a sanitizing function is now safe.
When looking at my log forging problems I had strings coming in through a web API and thus had the flags XSS and WEB on my strings. I tried to find annotations that would only remove these flags, but couldn't find any way to remove the WEB flag. The only documentation I've found is the Samples/advanced/javaAnnotation directory.
Since my sanitation method does sanitize strings, I choose to remove all flags. This could be a problem though, as it could hide privacy violations.
#FortifyValidate("return")
private String sanitizeString(String taintedString) {
return doSomethingWithTheString(taintedString);
}
Originally when this question was written our team was using log4j v1.2.8, however we noticed that all the log forging issues disappeared after upgrading to log4j v2.6.2.
Once the log4j version is upgraded the Fortify log forging issues should go away. The cleanLogString() method form the question above is also unnecessary. For example:
LOGGER.info("getLongFromTimestamp(" + value + ")");
I know I have run into situations where the complexity of my application would stop any malicious input from working as intended; Fortify does not consider this to be secure. I bet you are running into the same thing.
You are stripping any really useful characters out of the log message, but see what happens if you do some encoding on the output prior to writing to the log.
http://www.jtmelton.com/2010/09/21/preventing-log-forging-in-java/
// ensure no CRLF injection into logs for forging records
String clean = message.replace( '\n', '_' ).replace( '\r', '_' );
if ( ESAPI.securityConfiguration().getLogEncodingRequired() ) {
clean = ESAPI.encoder().encodeForHTML(message);
if (!message.equals(clean)) {
clean += " (Encoded)";
}
}
Use reflect or try-catch.
Its easy to cheat fortify.

How do I set up jsr223 scripting with scala as scripting language

So far I have tried the sling implementation for jsr223 scripting for scala, but was not able to get it set up correctly.
when I do this:
public static void main(String[] args) {
try {
new ScriptEngineManager().getEngineByName("scala").
eval("object HelloWorld {def main(args: Array[String]) {
println(\"Hello, world!\") }}");
} catch (ScriptException e) {
e.printStackTrace();
}
}
I got nothing but:
javax.script.ScriptException: ERROR
org.apache.sling.scripting.scala.Script line 13 : not found: type
Script at org.apache.sling.scripting.scala.ScalaScriptEngine.eval(ScalaScriptEngine.scala:117)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:247)
similar Problems are discussed here:
http://scala-programming-language.1934581.n4.nabble.com/How-to-compile-Scala-code-from-java-using-the-current-ClassLoader-instead-of-a-string-based-classpat-td1955873.html#a1955873
and
http://dev.day.com/discussion-groups/content/lists/sling-dev/2009-12/2009-12-01_Scala_scripting_support_was_Re_And_another_one____Michael_D_rig.html
maybe there is another Implementation that I'm not aware of.
Any help appreciated
Have a look at the test cases in the scala/script module of Apache Sling for a working example. The script and its entry point (that is the object) need to follow certain conventions. I'll provide more information on these if required later.
For a general overview of the scripting engine see my session slides from Scala Days 2010.
Update: Scripts must be of the following form:
package my.cool.script {
class foo(args: fooArgs) {
import args._ // import the bindings
println("bar:" + bar)
}
}
The type of args is generated by the script engine and is named after the simple class name of the script appended with 'Args'. Further the example assumes, that the Bindings passed for script evaluation contains a value for the name 'bar'. For further details see the class comment on ScalaScriptEngine.
You need to pass the name of your script class to the script engine. You do this by putting the fully qualified script name (i.e. my.cool.script.foo) into the ScriptContext by the name 'scala.script.class'.
With the conclusion of https://issues.scala-lang.org/browse/SI-874 in version 2.11, it should be as easy as what is shown in the ticket:
import javax.script.*;
ScriptEngine e = new ScriptEngineManager().getEngineByName("scala");
e.getContext().setAttribute("label", new Integer(4), ScriptContext.ENGINE_SCOPE);
try {
engine.eval("println(2+label)");
} catch (ScriptException ex) {
ex.printStackTrace();
}
Unfortunately my comment was unreadable without linebreaks - so...
To be able to run the Codesnippet mentioned I needed to make the following changes.
I used Scala 2.11.0-M4
public static void main(String args[]){
ScriptEngine engine = new ScriptEngineManager().getEngineByName("scala");
// Set up Scriptenvironment to use the Java classpath
List nil = Nil$.MODULE$;
$colon$colon vals = $colon$colon$.MODULE$.apply((String) "true", nil);
((IMain)engine).settings().usejavacp().tryToSet(vals);ScriptContext.ENGINE_SCOPE);
engine.getContext().setAttribute("labelO", new Integer(4), ScriptContext.ENGINE_SCOPE);
try {
engine.eval("val label = labelO.asInstanceOf[Integer]\n"+
"println(\"ergebnis: \" + (2 + label ))");
} catch (ScriptException ex) {
ex.printStackTrace();
}
}

Easiest way to obtain database metadata in Java?

I'm familiar with the java.sql.DatabaseMetaData interface, but I find it quite clunky to use. For example, in order to find out the table names, you have to call getTables and loop through the returned ResultSet, using well-known literals as the column names.
Is there an easier way to obtain database metadata?
It's easily done using DdlUtils:
import javax.sql.DataSource;
import org.apache.ddlutils.Platform;
import org.apache.ddlutils.PlatformFactory;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.platform.hsqldb.HsqlDbPlatform;
public void readMetaData(final DataSource dataSource) {
final Platform platform = PlatformFactory.createNewPlatformInstance(dataSource);
final Database database = platform.readModelFromDatabase("someName");
// Inspect the database as required; has objects like Table/Column/etc.
}
Take a look at SchemaCrawler (free and open source), which is another API designed for this purpose. Some sample SchemaCrawler code:
// Create the options
final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
// Set what details are required in the schema - this affects the
// time taken to crawl the schema
options.setSchemaInfoLevel(SchemaInfoLevel.standard());
options.setShowStoredProcedures(false);
// Sorting options
options.setAlphabeticalSortForTableColumns(true);
// Get the schema definition
// (the database connection is managed outside of this code snippet)
final Database database = SchemaCrawlerUtility.getDatabase(connection, options);
for (final Catalog catalog: database.getCatalogs())
{
for (final Schema schema: catalog.getSchemas())
{
System.out.println(schema);
for (final Table table: schema.getTables())
{
System.out.print("o--> " + table);
if (table instanceof View)
{
System.out.println(" (VIEW)");
}
else
{
System.out.println();
}
for (final Column column: table.getColumns())
{
System.out.println(" o--> " + column + " (" + column.getType()
+ ")");
}
}
}
}
http://schemacrawler.sourceforge.net/

Categories

Resources