'java.io.ObjectOutputStream' is deprecated - an error in Intellij IDEA - java

I have this code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
public class EmployeeProcessor {
public static void main(String[] args) {
Employee employee = new Employee();
employee.lastName = "Smith";
employee.firstName = "Adam";
employee.id = 123456789;
employee.salary = 50000;
try(FileOutputStream fileOutStr = new FileOutputStream("Employee.ser");
ObjectOutputStream objectOutStr = new ObjectOutputStream(fileOutStr)) {
objectOutStr.writeObject(employee);
System.out.println("An employee is externalized into the file Employee.ser");
} catch (IOException ioError){
ioError.printStackTrace();
}
}
}
But in Intellij IDEA ObjectOutputStream class is strikethrough Like this:
screenshot. When pointing mouse pointer over - this message appears: 'java.io.ObjectOutputStream' is deprecated. What does it mean?
When I run this code, IntelliJ opens "Edit Configurations" windows asking me to introduce VM options. But I leave it blank and run anyway.

IntelliJ IDEA has an intention action to annotate library classes as Deprecated using the External Annotations support. You've probably triggered this intention action by accident.
For the classes deprecated this way there supposed to be the reverse action: Deannotate, but it may not work (bug reported).
To fix it manually, find the annotations.xml file in a directory that is configured in the SDK Annotations tab and edit/remove it.
UPDATE: Deannoate action should work now, but only while inside the annotated class itself, not from its reference.

Related

Why won't createNewFile() recognize it's import?

I made this class in a NetBeans project and cannot figure out why the createNewFile method will not recognize it's import. NetBeans is giving the "cannot find symbol" error for that line. "createNewFile" is the only part underlined in red on that line. It also gives warning on "import java.io.File" saying that it is never used.
I've added try and catch blocks around the method but they make no difference. Got rid of them in the example below for the sake of simplicity.
import java.util.Scanner;
import java.io.File;
public class Bleh {
Scanner in = new Scanner(System.in);
User u = new User();
public void setUserName() {
System.out.print("Name: ");
u.setName(in.nextLine());
}
public void checkForAccount() {
createNewFile(u.getName());
}
}
Your import of java.io.File imports exactly that, the class itself, into your namespace. It doesn't import all of File's methods, and even if it did, there is no such method File.createNewFile(String); you need to create a File object and call the method on it:
new File(u.getName()).createNewFile();

Why am I getting deprecation error on Button? [duplicate]

I have this code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
public class EmployeeProcessor {
public static void main(String[] args) {
Employee employee = new Employee();
employee.lastName = "Smith";
employee.firstName = "Adam";
employee.id = 123456789;
employee.salary = 50000;
try(FileOutputStream fileOutStr = new FileOutputStream("Employee.ser");
ObjectOutputStream objectOutStr = new ObjectOutputStream(fileOutStr)) {
objectOutStr.writeObject(employee);
System.out.println("An employee is externalized into the file Employee.ser");
} catch (IOException ioError){
ioError.printStackTrace();
}
}
}
But in Intellij IDEA ObjectOutputStream class is strikethrough Like this:
screenshot. When pointing mouse pointer over - this message appears: 'java.io.ObjectOutputStream' is deprecated. What does it mean?
When I run this code, IntelliJ opens "Edit Configurations" windows asking me to introduce VM options. But I leave it blank and run anyway.
IntelliJ IDEA has an intention action to annotate library classes as Deprecated using the External Annotations support. You've probably triggered this intention action by accident.
For the classes deprecated this way there supposed to be the reverse action: Deannotate, but it may not work (bug reported).
To fix it manually, find the annotations.xml file in a directory that is configured in the SDK Annotations tab and edit/remove it.
UPDATE: Deannoate action should work now, but only while inside the annotated class itself, not from its reference.

GWT generator to get compile time

I am trying to understand GWT generators but facing few issues. I am trying to display the compile time in an app using generators and running into this error -
Rebind result 'com.example.client.Function' must be a class
Here is what i have -
This is how i am calling my generated method -
Function b = GWT.create(Function.class);
label.setText(b.getBuildTime());
gwt.xml-
<generate-with class="example.frontend.client.gin.FunctionGenerator">
<when-type-assignable class="com.example.frontend.client.gin.Function" />
</generate-with>
Function.java
package com.example.frontend.client.gin;
public interface Function{
public String getBuildTime();
}
Generator class -
package com.example.frontend.egenerator;
import java.io.PrintWriter;
import java.util.Date;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
import com.example.frontend.client.gin.Function;
public class FunctionGenerator extends Generator {
private static final String IMPL_TYPE_NAME = Function.class.getSimpleName() + "Impl";
private static final String IMPL_PACKAGE_NAME = Function.class.getPackage().getName();
#Override
public String generate(final TreeLogger logger, final GeneratorContext context, final String requestedClass) throws UnableToCompleteException {
TypeOracle typeOracle = context.getTypeOracle();
JClassType functionType = typeOracle.findType(requestedClass);
assert Function.class.equals(functionType.getClass());
ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(IMPL_PACKAGE_NAME, IMPL_TYPE_NAME);
composerFactory.addImport(Function.class.getCanonicalName());
composerFactory.addImplementedInterface(Function.class.getName());
PrintWriter printWriter = context.tryCreate(logger, IMPL_PACKAGE_NAME, IMPL_TYPE_NAME);
SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
if(sourceWriter != null) {
sourceWriter.print("public String getBuildTime() {");
sourceWriter.print(" return \"" + new Date() + "\" ;");
sourceWriter.print("}");
sourceWriter.commit(logger);
}
return IMPL_PACKAGE_NAME + "." + IMPL_TYPE_NAME;
}
}
Any ideas, what I am missing?
I believe you also need to null check the PrintWriter created by tryCreate, as it may return null. On the other hand, createSourceWriter will not return null, so no need to null check that.
Your generate-with is also incorrect, at least for the sample that you have here. It should have a different package (according to your FunctionGenerator source at least), com.example.frontend.egenerator, not com.example.frontend.client.gin:
<generate-with class="com.example.frontend.egenerator.FunctionGenerator">
<when-type-assignable class="com.example.frontend.client.gin.Function" />
</generate-with>
In general, your generators should not be in the client package, if for no other reason than preventing spurious errors which slow down the compiler (and really slow down super dev mode).
Beyond that, the full log could help a lot to track down the issue, though without mapping the generator correctly there wouldn't be much of an error. Also be sure to compile with strict turned on when working on generators to ensure that the compiler fails as soon as possible and you can stop at the very first error.
With all of that said, tend to avoid new Generators at this point - they will slow down Super Dev Mode slightly (since they must be re-run every time you refresh), and they will not be supported in future versions of GWT. Annotation Processors (aka APT) are the preferred way to do this, but in your case you might also just be able to generate the class in ant or maven with a plugin.

Cannot instantiate the type configuration Mirror API

I recently purchased the Book "Programming Google Glass - The Mirror API" By Eric Redmond and in the 2nd chapter we install Freemarker GRE .jar file into the project. There is a part when we have to create a method that renders a template file. I keep getting an error when trying to make a Configuration.
package com.leetinsider.leetfoodfinder;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Random;
import javax.security.auth.login.Configuration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Template;
public class LeetFoodFinder {
public static String getRandomCuisine()
{
String[] lunchOptions = {
"American", "Chineese", "French", "Italian", "Japenese", "Thai"
};
int choice = new Random().nextInt(lunchOptions.length);
return lunchOptions[choice];
}
public static String render(ServletContext ctx, String template, Map<String, Object> data)
throws IOException, ServletException{
Configuration config = new Configuration();
config.setServletContextForTemplateLoading(ctx, "WEB-INF/views");
config.setDefaultEncoding("UTF-8");
Template ftl = config.getTemplate(template);
try{
//use the data to render the template to the servlet output
StringWriter writer = new StringWriter();
ftl.process(data, writer);
return writer.toString();
}
catch (TemplateException e){
throw new ServletException("Problem while processing template", e);
}
}
}
It tells me that Configuration() cannot be instaniated. Is there an import that I am missing? I put the freemarker-gae2.3.2.0.jar file in the war/WEB-INF/lib directory but am not sure if there is something else I am missing.
Trying to follow along with the book but this is holding me back :/
If you look at your import statement, they're referring to non freemarker classes of the same name.
The jar isn't actually in your build path. Right click the project and choose "Properties", then "Java Build Path". If freemarker isn't in the Libraries list, select Add JARs and find the jar in your project.
Delete the "import javax.security.auth.login.Configuration" line. You need to choose the Freemarker configuration.
Hope that helps.

How do I programmatically run all the JUnit tests in my Java application?

From Eclipse I can easily run all the JUnit tests in my application.
I would like to be able to run the tests on target systems from the application jar, without Eclipse (or Ant or Maven or any other development tool).
I can see how to run a specific test or suite from the command line.
I could manually create a suite listing all the tests in my application, but that seems error prone - I'm sure at some point I'll create a test and forget to add it to the suite.
The Eclipse JUnit plugin has a wizard to create a test suite, but for some reason it doesn't "see" my test classes. It may be looking for JUnit 3 tests, not JUnit 4 annotated tests.
I could write a tool that would automatically create the suite by scanning the source files.
Or I could write code so the application would scan it's own jar file for tests (either by naming convention or by looking for the #Test annotation).
It seems like there should be an easier way. What am I missing?
According to a recent thread on the JUnit mailing list, ClasspathSuite can collect and run all JUnit tests on the classpath. It is not precisely what you want, since it is a class-level annotation, but the source is available, so you may be able to extend its internal discovery mechanism.
I ran into a minor problem with my last solution. If I ran "all tests" from Eclipse they ran twice because they ran the individual tests AND the suite. I could have worked around that, but then I realized there was a simpler solution:
package suneido;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class RunAllTests {
public static void run(String jarfile) {
String[] tests = findTests(jarfile);
org.junit.runner.JUnitCore.main(tests);
}
private static String[] findTests(String jarfile) {
ArrayList<String> tests = new ArrayList<String>();
try {
JarFile jf = new JarFile(jarfile);
for (Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements();) {
String name = e.nextElement().getName();
if (name.startsWith("suneido/") && name.endsWith("Test.class")
&& !name.contains("$"))
tests.add(name.replaceAll("/", ".")
.substring(0, name.length() - 6));
}
jf.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return tests.toArray(new String[0]);
}
public static void main(String[] args) {
run("jsuneido.jar");
}
}
Based on http://burtbeckwith.com/blog/?p=52 I came up with the following. It seems to work well.
I can run it from within my code with:
org.junit.runner.JUnitCore.main("suneido.AllTestsSuite");
One weak point is that it relies on a naming convention ("Test" suffix) to identify tests. Another weak point is that the name of the jar file is hard coded.
package suneido;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;
/**
* Discovers all JUnit tests in a jar file and runs them in a suite.
*/
#RunWith(AllTestsSuite.AllTestsRunner.class)
public final class AllTestsSuite {
private final static String JARFILE = "jsuneido.jar";
private AllTestsSuite() {
}
public static class AllTestsRunner extends Suite {
public AllTestsRunner(final Class<?> clazz) throws InitializationError {
super(clazz, findClasses());
}
private static Class<?>[] findClasses() {
List<String> classFiles = new ArrayList<String>();
findClasses(classFiles);
List<Class<?>> classes = convertToClasses(classFiles);
return classes.toArray(new Class[classes.size()]);
}
private static void findClasses(final List<String> classFiles) {
JarFile jf;
try {
jf = new JarFile(JARFILE);
for (Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements();) {
String name = e.nextElement().getName();
if (name.startsWith("suneido/") && name.endsWith("Test.class")
&& !name.contains("$"))
classFiles.add(name.replaceAll("/", ".")
.substring(0, name.length() - 6));
}
jf.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static List<Class<?>> convertToClasses(
final List<String> classFiles) {
List<Class<?>> classes = new ArrayList<Class<?>>();
for (String name : classFiles) {
Class<?> c;
try {
c = Class.forName(name);
}
catch (ClassNotFoundException e) {
throw new AssertionError(e);
}
if (!Modifier.isAbstract(c.getModifiers())) {
classes.add(c);
}
}
return classes;
}
}
}
I have not tried this as of yet, but came across this blog recently: http://burtbeckwith.com/blog/?p=52
The author provides a class that discovers all your junits and runs them, so if you slot this in to your project it may provide the capability required?
Hope this helps.
Get the Java project and pass the project
JUnitLaunchShortcut jUnitLaunchShortcut = new JUnitLaunchShortcut();
jUnitLaunchShortcut.launch("Pass the Java Project containing JUnits Classes", "run");
You also could use ANT which has built-in task.
Write ANT script and run it on target machine.
ANT could create report as result.

Categories

Resources