https://dzone.com/articles/the-best-of-java-collections-tutorials
http://falkhausen.de/Java-10/java.util/Collection-Hierarchy.html hyerarchy
https://dzone.com/articles/a-deep-dive-into-collections
https://dzone.com/articles/the-developers-guide-to-collections-lists
https://dzone.com/articles/the-developers-guide-to-collections-sets
https://dzone.com/articles/the-developers-guide-to-collections-queues
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Tuesday, December 31, 2019
Tuesday, April 9, 2019
Effective Java third edition
the source code:
https://github.com/jbloch/effective-java-3e-source-code
*clone (p. 86)
copy constructor/ copy factory
compareTo()
java.util.Comparator.comparingInt + thenComparingInt
immutable objects
composition over inheritance
default methods
generics and collections
unbounded wildcard types (<?>)
PECS producer extends consumer super
isAnnotationPresent
@ExceptionTest
@Repeatable
java.util.function
Operator
Predicate
Function
Supplier
Consumer
Monday, April 8, 2019
Generics and collections
this one has no compilation errors:
but if I use
Set<Object> b;
Set<?> c;
then "c = b" gives compilation error
Error:(26, 13) java: incompatible types: java.util.Set cannot be converted to java.util.Set
This is interesting, since ? means "any Object and subclasses"... while "? super Object" means "Object and its superclasses"
but Object has no superclasses, so effectively it's only Object.
If I use:
b = new HashSet<>();
Set<?? extends Object> c;
then
b = c;
fails with the same error:
Error:(26, 13) java: incompatible types: java.util.Set cannot be converted to java.util.Set
The raw type a can be assigned all the time to all the others.
similarly, collections are INVARIANT:
but arrays are COVARIANT:
Set a; Set<Object> b; Set<? super Object> c; a = new HashSet(); b = new HashSet<>(); c = new HashSet<>(); c = a; c = b; b = a; b = c; a = c; a = b;
but if I use
Set<Object> b;
Set<?> c;
then "c = b" gives compilation error
Error:(26, 13) java: incompatible types: java.util.Set
This is interesting, since ? means "any Object and subclasses"... while "? super Object" means "Object and its superclasses"
but Object has no superclasses, so effectively it's only Object.
If I use:
b = new HashSet<>();
Set<?? extends Object> c;
then
b = c;
fails with the same error:
Error:(26, 13) java: incompatible types: java.util.Set
The raw type a can be assigned all the time to all the others.
similarly, collections are INVARIANT:
Set<Number> numset = new HashSet<>(); Set<Integer> intset = new HashSet<>(); Set<?> allset = new HashSet<>(); numset = intset; // INVALID intset = numset; // INVALID allset = numset; // VALID numset = allset; // INVALID
but arrays are COVARIANT:
Number[] numarr = new Number[1]; Integer[] intarr = new Integer[1]; numarr = intarr; // VALID intarr = numarr; // INVALID
Monday, March 25, 2019
Book: java by comparison by Simon Harrer, Jörg Lenhard, Linus Dietz
Interesting book, concise and a breeze to read
https://pragprog.com/book/javacomp/java-by-comparison
Source code is here https://pragprog.com/titles/javacomp/source_code
My first (not very functional) implementation of FizzBuzz:
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
Avoid Unnecessary Comparisons
Avoid Negations
Return Boolean Expressions Directly
Simplify Boolean Expressions
Avoid NullPointerException in Conditionals
Avoid Switch Fallthrough
Always Use Braces
Ensure Code Symmetry
Replace Magic Numbers with Constants
Favor Enums Over Integer Constants
Favor For-Each Over For Loops
Avoid Collection Modification During Iteration
Avoid Compute-Intense Operations During Iteration
Group with New Lines
Favor Format Over Concatenation
Favor Java API Over DIY
Remove Superfluous Comments
Remove Commented-Out Code
Replace Comments with Constants
Replace Comments with Utility Methods
Document Implementation Decisions
Document Using Examples
Structure JavaDoc of Packages
Structure JavaDoc of Classes and Interfaces
Structure JavaDoc of Methods
Structure JavaDoc of Constructors
Use Java Naming Conventions
Follow Getter/Setter Conventions for Frameworks
Avoid Single-Letter Names
Avoid Abbreviations
Avoid Meaningless Terms
Use Domain Terminology
Fail Fast
Always Catch Most Specific Exception
Explain Cause in Message
Avoid Breaking the Cause Chain
Expose Cause in Variable
Always Check Type Before Cast
Always Close Resources
Always Close Multiple Resources
Explain Empty Catch
Structure Tests Into Given-When-Then
Use Meaningful Assertions
Expected Before Actual Value
Use Reasonable Tolerance Values
Let JUnit Handle Exceptions
Describe Your Tests @DisplayName @Disabled
Favor Standalone Tests
Parametrize Your Tests @ParameterizedTest @ValueSource
Cover the Edge Cases
Split Method with Optional Parameters
Favor Abstract Over Concrete Types
Favor Immutable Over Mutable State
Combine State and Behavior
Avoid Leaking References (defensive copying)
Avoid Returning Null
Favor Lambdas Over Anonymous Classes
Favor Method References Over Lambdas
Avoid Side Effects
Use Collect for Terminating Complex Streams
Avoid Exceptions in Streams
Favor Optional Over Null (Optional.ofNullable())
Avoid Optional Fields or Parameters
Use Optionals as Streams
Google Java Style Guide https://google.github.io/styleguide/javaguide.html
Automate Your Build
Favor Logging Over Console Output
Minimize and Isolate Multithreaded Code
Use High-Level Concurrency Abstractions
Speed Up Your Program
https://pragprog.com/book/javacomp/java-by-comparison
Source code is here https://pragprog.com/titles/javacomp/source_code
My first (not very functional) implementation of FizzBuzz:
import java.util.stream.IntStream;
public class ConsoleBasedFizzBuzz implements FizzBuzz {
public static void main(String[] args) {
FizzBuzz fizzBuzz = new ConsoleBasedFizzBuzz();
fizzBuzz.print(1, 100);
}
private static void accept(int i) {
StringBuffer result = new StringBuffer();
if (i % 3 == 0) result.append("Fizz");
if (i % 5 == 0) result.append("Buzz");
if (result.length() == 0) result.append(i);
System.out.println(result);
}
@Override
public void print(int from, int to) {
IntStream.range(from, to).forEach(ConsoleBasedFizzBuzz::accept);
}
}
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
Avoid Unnecessary Comparisons
Avoid Negations
Return Boolean Expressions Directly
Simplify Boolean Expressions
Avoid NullPointerException in Conditionals
Avoid Switch Fallthrough
Always Use Braces
Ensure Code Symmetry
Replace Magic Numbers with Constants
Favor Enums Over Integer Constants
Favor For-Each Over For Loops
Avoid Collection Modification During Iteration
Avoid Compute-Intense Operations During Iteration
Group with New Lines
Favor Format Over Concatenation
Favor Java API Over DIY
Remove Superfluous Comments
Remove Commented-Out Code
Replace Comments with Constants
Replace Comments with Utility Methods
Document Implementation Decisions
Document Using Examples
Structure JavaDoc of Packages
Structure JavaDoc of Classes and Interfaces
Structure JavaDoc of Methods
Structure JavaDoc of Constructors
Use Java Naming Conventions
Follow Getter/Setter Conventions for Frameworks
Avoid Single-Letter Names
Avoid Abbreviations
Avoid Meaningless Terms
Use Domain Terminology
Fail Fast
Always Catch Most Specific Exception
Explain Cause in Message
Avoid Breaking the Cause Chain
Expose Cause in Variable
Always Check Type Before Cast
Always Close Resources
Always Close Multiple Resources
Explain Empty Catch
Structure Tests Into Given-When-Then
Use Meaningful Assertions
Expected Before Actual Value
Use Reasonable Tolerance Values
Let JUnit Handle Exceptions
Describe Your Tests @DisplayName @Disabled
Favor Standalone Tests
Parametrize Your Tests @ParameterizedTest @ValueSource
Cover the Edge Cases
Split Method with Optional Parameters
Favor Abstract Over Concrete Types
Favor Immutable Over Mutable State
Combine State and Behavior
Avoid Leaking References (defensive copying)
Avoid Returning Null
Favor Lambdas Over Anonymous Classes
Favor Method References Over Lambdas
Avoid Side Effects
Use Collect for Terminating Complex Streams
Avoid Exceptions in Streams
Favor Optional Over Null (Optional.ofNullable())
Avoid Optional Fields or Parameters
Use Optionals as Streams
Google Java Style Guide https://google.github.io/styleguide/javaguide.html
Automate Your Build
Favor Logging Over Console Output
Minimize and Isolate Multithreaded Code
Use High-Level Concurrency Abstractions
Speed Up Your Program
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.io.IOException;
public class JunitAssertionsTest {
@Test
public void testException() {
Executable when = () -> pippo();
Assertions.assertThrows(IOException.class, when);
}
private void pippo() throws IOException {
System.out.println("running");
throw new IOException("ciao");
}
}
Sunday, March 10, 2019
Kubernetes Java client to generate yaml files for you
If you - like me - hate having to type YAML by hand, you can take advantage of a pre-built K8S Model and YAML serialization tool:
https://github.com/fabric8io/kubernetes-client
The model is incredibly rich.... one has only to learn how to use it...
https://github.com/fabric8io/kubernetes-client
<dependency>
<groupId>io.fabric8</groupId>
<artifactId>kubernetes-client</artifactId>
<version>4.1.3</version>
</dependency>
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.internal.SerializationUtils;
public class KubernetesClientTest {
public static void main(String[] args) throws JsonProcessingException {
String yaml = SerializationUtils.dumpAsYaml(new DeploymentBuilder().withNewSpec().endSpec().build());
System.out.println(yaml);
KubernetesClient client = new DefaultKubernetesClient();
Pod pod = new Pod();
System.out.println(pod);
String podyaml = SerializationUtils.dumpAsYaml(pod);
System.out.println(podyaml);
}
}
The model is incredibly rich.... one has only to learn how to use it...
Labels:
java,
kubernetes
Thursday, November 29, 2018
java showSettings
This is a priceless feature to display all the settings of the JVM, together with -XX:+PrintCommandLineFlags it can show a world of hidden stuff.
java -XX:+PrintCommandLineFlags -version
java -XshowSettings:all -version
java -XX:+PrintCommandLineFlags -version
-XX:InitialHeapSize=261069952 -XX:MaxHeapSize=4177119232 -XX:+PrintCommandLineFlags -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseParallelGC openjdk version "1.8.0_191" OpenJDK Runtime Environment (build 1.8.0_191-b12) OpenJDK 64-Bit Server VM (build 25.191-b12, mixed mode)
java -XshowSettings:all -version
VM settings:
Max. Heap Size (Estimated): 3.46G
Ergonomics Machine Class: server
Using VM: OpenJDK 64-Bit Server VM
Property settings:
awt.toolkit = sun.awt.X11.XToolkit
file.encoding = UTF-8
file.encoding.pkg = sun.io
file.separator = /
java.awt.graphicsenv = sun.awt.X11GraphicsEnvironment
java.awt.printerjob = sun.print.PSPrinterJob
java.class.path = .
java.class.version = 52.0
java.endorsed.dirs = /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/endorsed
java.ext.dirs = /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/ext
/usr/java/packages/lib/ext
java.home = /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre
java.io.tmpdir = /tmp
java.library.path = /usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
java.runtime.name = OpenJDK Runtime Environment
java.runtime.version = 1.8.0_191-b12
java.specification.name = Java Platform API Specification
java.specification.vendor = Oracle Corporation
java.specification.version = 1.8
java.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
java.version = 1.8.0_191
java.vm.info = mixed mode
java.vm.name = OpenJDK 64-Bit Server VM
java.vm.specification.name = Java Virtual Machine Specification
java.vm.specification.vendor = Oracle Corporation
java.vm.specification.version = 1.8
java.vm.vendor = Oracle Corporation
java.vm.version = 25.191-b12
line.separator = \n
os.arch = amd64
os.name = Linux
os.version = 2.6.32-754.el6.x86_64
path.separator = :
sun.arch.data.model = 64
sun.boot.class.path = /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/resources.jar
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/rt.jar
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/sunrsasign.jar
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/jsse.jar
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/jce.jar
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/charsets.jar
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/jfr.jar
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/classes
sun.boot.library.path = /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-0.el6_10.x86_64/jre/lib/amd64
sun.cpu.endian = little
sun.cpu.isalist =
sun.io.unicode.encoding = UnicodeLittle
sun.java.launcher = SUN_STANDARD
sun.jnu.encoding = UTF-8
sun.management.compiler = HotSpot 64-Bit Tiered Compilers
sun.os.patch.level = unknown
user.country = US
user.dir = /root
user.home = /root
user.language = en
user.name = root
user.timezone =
Locale settings:
default locale = English
default display locale = English (United States)
default format locale = English (United States)
available locales = , ar, ar_AE, ar_BH, ar_DZ, ar_EG, ar_IQ, ar_JO,
ar_KW, ar_LB, ar_LY, ar_MA, ar_OM, ar_QA, ar_SA, ar_SD,
ar_SY, ar_TN, ar_YE, be, be_BY, bg, bg_BG, ca,
ca_ES, cs, cs_CZ, da, da_DK, de, de_AT, de_CH,
de_DE, de_GR, de_LU, el, el_CY, el_GR, en, en_AU,
en_CA, en_GB, en_IE, en_IN, en_MT, en_NZ, en_PH, en_SG,
en_US, en_ZA, es, es_AR, es_BO, es_CL, es_CO, es_CR,
es_CU, es_DO, es_EC, es_ES, es_GT, es_HN, es_MX, es_NI,
es_PA, es_PE, es_PR, es_PY, es_SV, es_US, es_UY, es_VE,
et, et_EE, fi, fi_FI, fr, fr_BE, fr_CA, fr_CH,
fr_FR, fr_LU, ga, ga_IE, hi, hi_IN, hr, hr_HR,
hu, hu_HU, in, in_ID, is, is_IS, it, it_CH,
it_IT, iw, iw_IL, ja, ja_JP, ja_JP_JP_#u-ca-japanese, ko, ko_KR,
lt, lt_LT, lv, lv_LV, mk, mk_MK, ms, ms_MY,
mt, mt_MT, nl, nl_BE, nl_NL, no, no_NO, no_NO_NY,
pl, pl_PL, pt, pt_BR, pt_PT, ro, ro_RO, ru,
ru_RU, sk, sk_SK, sl, sl_SI, sq, sq_AL, sr,
sr_BA, sr_BA_#Latn, sr_CS, sr_ME, sr_ME_#Latn, sr_RS, sr_RS_#Latn, sr__#Latn,
sv, sv_SE, th, th_TH, th_TH_TH_#u-nu-thai, tr, tr_TR, uk,
uk_UA, vi, vi_VN, zh, zh_CN, zh_HK, zh_SG, zh_TW
openjdk version "1.8.0_191"
OpenJDK Runtime Environment (build 1.8.0_191-b12)
OpenJDK 64-Bit Server VM (build 25.191-b12, mixed mode)
Labels:
java
Friday, January 5, 2018
CentOS install JDK
which java
java -version
ls -ltr /usr/bin/java
ls -ltr /etc/alternatives/java
sudo yum update
yum list installed | grep "java"
sudo yum install java-1.8.0-openjdk-devel
cd /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.151-5.b12.el7_4.x86_64/
sudo ln -sf /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.151-5.b12.el7_4.x86_64/bin/java /etc/alternatives/java
java -version
ls -ltr /usr/bin/java
ls -ltr /etc/alternatives/java
sudo yum update
yum list installed | grep "java"
sudo yum install java-1.8.0-openjdk-devel
cd /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.151-5.b12.el7_4.x86_64/
sudo ln -sf /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.151-5.b12.el7_4.x86_64/bin/java /etc/alternatives/java
Thursday, March 2, 2017
bad class file, bad signature
We had an interesting case of an invalid class failing with version 12.1.3 of WebLogic (it was working with previous release)
See also this previous post http://www.javamonamour.org/2016/01/weblogic-deployment-fails.html
Problem is that WebLogic doesn't tell us which class is failing, so I had to patch this class
adding a System.out.println(it's horrible but it works)
To check if the class is REALLY invalid I use this tester (bad class is com.pippo.web.util.Properties ):
With Java 8 I get this:
parsing method setProperty All annotations for method setProperty parsing method getProperty All annotations for method getProperty parsing method getProperty All annotations for method getProperty parsing method load All annotations for method load parsing method load All annotations for method load parsing method save Exception in thread "main" java.lang.reflect.GenericSignatureFormatError: Signature Parse error: Expected Field Type Signature Remaining input: = at sun.reflect.generics.parser.SignatureParser.error(SignatureParser.java:124) at sun.reflect.generics.parser.SignatureParser.parseFieldTypeSignature(SignatureParser.java:297) at sun.reflect.generics.parser.SignatureParser.parseFieldTypeSignature(SignatureParser.java:283) at sun.reflect.generics.parser.SignatureParser.parseTypeSignature(SignatureParser.java:485) at sun.reflect.generics.parser.SignatureParser.parseTypeSig(SignatureParser.java:188) at sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:436) at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:241) at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120) at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72) at java.lang.reflect.Executable.declaredAnnotations(Executable.java:599) at java.lang.reflect.Executable.declaredAnnotations(Executable.java:597) at java.lang.reflect.Executable.getDeclaredAnnotations(Executable.java:588) at java.lang.reflect.Method.getDeclaredAnnotations(Method.java:630) at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:207) at TestAnnotations.main(TestAnnotations.java:16)
With Java 7 and 6 I get this when compiling:
TestAnnotations.java:1: cannot access com.pippo.web.util.Properties bad class file: com/pippo/web/util/Properties.class(com/pippo/web/util:Properties.class) bad signature: = ¿I ^ Please remove or make sure it appears in the correct subdirectory of the classpath. import com.pippo.web.util.Properties; ^
As a workaround, to avoid all this class scanning, you can try using -Dweblogic.servlet.DIDisabled=true or setting the metadata-complete attribute to true in the web.xml :
https://docs.oracle.com/cd/E24329_01/web.1211/e21049/annotateservlet.htm#WBAPP225
####<Feb 27, 2017 7:46:40 AM CET> <Error> <Deployer> <myserver.pippo.com> <pippodomain> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1488178000430> <BEA-149205> <Failed to initialize the application "PIPPO" due to error weblogic.application.ModuleException: String index out of range: -1
String index out of range: -1
weblogic.application.ModuleException: String index out of range: -1
String index out of range: -1
at weblogic.servlet.internal.WebAppModule.createModuleException(WebAppModule.java:1824)
at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:270)
at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:682)
at weblogic.application.internal.flow.ScopedModuleDriver.init(ScopedModuleDriver.java:162)
at weblogic.application.internal.ExtensibleModuleWrapper.init(ExtensibleModuleWrapper.java:98)
at weblogic.application.internal.flow.ModuleListenerInvoker.init(ModuleListenerInvoker.java:84)
at weblogic.application.internal.flow.InitModulesFlow.initModule(InitModulesFlow.java:288)
at weblogic.application.internal.flow.InitModulesFlow.initModules(InitModulesFlow.java:301)
at weblogic.application.internal.flow.InitModulesFlow.prepare(InitModulesFlow.java:329)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:706)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:237)
at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:61)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:158)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:61)
at weblogic.deploy.internal.targetserver.AppDeployment.prepare(AppDeployment.java:155)
at weblogic.management.deploy.internal.DeploymentAdapter$1.doPrepare(DeploymentAdapter.java:39)
at weblogic.management.deploy.internal.DeploymentAdapter.prepare(DeploymentAdapter.java:191)
at weblogic.management.deploy.internal.AppTransition$1.transitionApp(AppTransition.java:21)
at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:240)
at weblogic.management.deploy.internal.ConfiguredDeployments.prepare(ConfiguredDeployments.java:165)
at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:122)
at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:211)
at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:119)
at weblogic.server.AbstractServerService.postConstruct(AbstractServerService.java:78)
at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1017)
at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:388)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:430)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:225)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:82)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2488)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:98)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:606)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:77)
at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:231)
at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:254)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:413)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:225)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:82)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2488)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:98)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1162)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1147)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$UpOneLevel.run(CurrentTaskFuture.java:753)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:553)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
Caused By: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1911)
at weblogic.application.utils.annotation.ClassInfoImpl$MethodVisitorImpl.visitAnnotation(ClassInfoImpl.java:472)
at com.bea.objectweb.asm.ClassReader.b(Unknown Source)
at com.bea.objectweb.asm.ClassReader.accept(Unknown Source)
at com.bea.objectweb.asm.ClassReader.accept(Unknown Source)
at weblogic.application.utils.annotation.ClassInfoImpl.<init>(ClassInfoImpl.java:86)
at weblogic.application.utils.annotation.ClassInfoImpl.<init>(ClassInfoImpl.java:79)
at weblogic.application.utils.annotation.ClassfinderClassInfos.getClassInfoFromSource(ClassfinderClassInfos.java:325)
at weblogic.application.utils.annotation.ClassfinderClassInfos.populateClassInfos(ClassfinderClassInfos.java:278)
at weblogic.application.utils.annotation.ClassfinderClassInfos.<init>(ClassfinderClassInfos.java:72)
at weblogic.servlet.internal.War.initializeClassInfosIfNecessary(War.java:446)
at weblogic.servlet.internal.War.getAnnotatedClasses(War.java:376)
at weblogic.servlet.utils.WarUtils.isJsfApplication(WarUtils.java:260)
at weblogic.servlet.internal.WebAppModule.detectJsfApplication(WebAppModule.java:277)
at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:262)
at weblogic.servlet.internal.WebAppModule.init(WebAppModule.java:682)
at weblogic.application.internal.flow.ScopedModuleDriver.init(ScopedModuleDriver.java:162)
at weblogic.application.internal.ExtensibleModuleWrapper.init(ExtensibleModuleWrapper.java:98)
at weblogic.application.internal.flow.ModuleListenerInvoker.init(ModuleListenerInvoker.java:84)
at weblogic.application.internal.flow.InitModulesFlow.initModule(InitModulesFlow.java:288)
at weblogic.application.internal.flow.InitModulesFlow.initModules(InitModulesFlow.java:301)
at weblogic.application.internal.flow.InitModulesFlow.prepare(InitModulesFlow.java:329)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:706)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:237)
at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:61)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:158)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:61)
at weblogic.deploy.internal.targetserver.AppDeployment.prepare(AppDeployment.java:155)
at weblogic.management.deploy.internal.DeploymentAdapter$1.doPrepare(DeploymentAdapter.java:39)
at weblogic.management.deploy.internal.DeploymentAdapter.prepare(DeploymentAdapter.java:191)
at weblogic.management.deploy.internal.AppTransition$1.transitionApp(AppTransition.java:21)
at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:240)
at weblogic.management.deploy.internal.ConfiguredDeployments.prepare(ConfiguredDeployments.java:165)
at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:122)
at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:211)
at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:119)
at weblogic.server.AbstractServerService.postConstruct(AbstractServerService.java:78)
at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.hk2.utilities.reflection.ReflectionHelper.invoke(ReflectionHelper.java:1017)
at org.jvnet.hk2.internal.ClazzCreator.postConstructMe(ClazzCreator.java:388)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:430)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:225)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:82)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2488)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:98)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:606)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:77)
at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:231)
at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:254)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:413)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
at org.glassfish.hk2.runlevel.internal.AsyncRunLevelContext.findOrCreate(AsyncRunLevelContext.java:225)
at org.glassfish.hk2.runlevel.RunLevelContext.findOrCreate(RunLevelContext.java:82)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2488)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:98)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.oneJob(CurrentTaskFuture.java:1162)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$QueueRunner.run(CurrentTaskFuture.java:1147)
at org.glassfish.hk2.runlevel.internal.CurrentTaskFuture$UpOneLevel.run(CurrentTaskFuture.java:753)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:553)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
>
See also this previous post http://www.javamonamour.org/2016/01/weblogic-deployment-fails.html
Problem is that WebLogic doesn't tell us which class is failing, so I had to patch this class
package weblogic.utils.classloaders;
import java.io.IOException;
import java.security.cert.Certificate;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
public class JarSource
extends ZipSource
{
private final JarFile jarFile;
private final JarEntry jarEntry;
public JarSource(JarFile jf, JarEntry je)
{
super(jf, je);
this.jarFile = jf;
this.jarEntry = je;
System.out.println("JarSource, jf=" + jf.getName() + " je=" + je);
}
public Manifest getManifest()
throws IOException
{
return this.jarFile.getManifest();
}
public Certificate[] getCertificates()
{
return this.jarEntry.getCertificates();
}
}
adding a System.out.println(it's horrible but it works)
To check if the class is REALLY invalid I use this tester (bad class is com.pippo.web.util.Properties ):
import com.pippo.web.util.Properties;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
public class TestAnnotations {
public static void main(String[] args) throws Exception {
Class propertiesClass = com.pippo.web.util.Properties.class;
Annotation annos[] = propertiesClass.getAnnotations();
for (Annotation a : annos)
System.out.println(a);
for (Method m : propertiesClass.getMethods()) {
System.out.println("parsing method " + m.getName());
annos = m.getAnnotations();
System.out.println("All annotations for method " + m.getName());
for (Annotation a : annos) System.out.println(a);
}
}
}
With Java 8 I get this:
parsing method setProperty All annotations for method setProperty parsing method getProperty All annotations for method getProperty parsing method getProperty All annotations for method getProperty parsing method load All annotations for method load parsing method load All annotations for method load parsing method save Exception in thread "main" java.lang.reflect.GenericSignatureFormatError: Signature Parse error: Expected Field Type Signature Remaining input: = at sun.reflect.generics.parser.SignatureParser.error(SignatureParser.java:124) at sun.reflect.generics.parser.SignatureParser.parseFieldTypeSignature(SignatureParser.java:297) at sun.reflect.generics.parser.SignatureParser.parseFieldTypeSignature(SignatureParser.java:283) at sun.reflect.generics.parser.SignatureParser.parseTypeSignature(SignatureParser.java:485) at sun.reflect.generics.parser.SignatureParser.parseTypeSig(SignatureParser.java:188) at sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:436) at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:241) at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120) at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72) at java.lang.reflect.Executable.declaredAnnotations(Executable.java:599) at java.lang.reflect.Executable.declaredAnnotations(Executable.java:597) at java.lang.reflect.Executable.getDeclaredAnnotations(Executable.java:588) at java.lang.reflect.Method.getDeclaredAnnotations(Method.java:630) at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:207) at TestAnnotations.main(TestAnnotations.java:16)
With Java 7 and 6 I get this when compiling:
TestAnnotations.java:1: cannot access com.pippo.web.util.Properties bad class file: com/pippo/web/util/Properties.class(com/pippo/web/util:Properties.class) bad signature: = ¿I ^ Please remove or make sure it appears in the correct subdirectory of the classpath. import com.pippo.web.util.Properties; ^
As a workaround, to avoid all this class scanning, you can try using -Dweblogic.servlet.DIDisabled=true or setting the metadata-complete attribute to true in the web.xml :
https://docs.oracle.com/cd/E24329_01/web.1211/e21049/annotateservlet.htm#WBAPP225
Labels:
java
Sunday, April 3, 2016
ExceptionInInitializerError , NoClassDefFoundError and ClassNotFoundException
https://docs.oracle.com/javase/7/docs/api/java/lang/ExceptionInInitializerError.html
"an exception occurred during evaluation of a static initializer or the initializer for a static variable."
https://docs.oracle.com/javase/7/docs/api/java/lang/NoClassDefFoundError.html
"no definition of the class could be found"
the above 2 are LinkageError (Error). The one below is an Exception:
https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html
Difference between NoClassDefFoundError and ClassNotFoundException is well explained here:
http://www.javaroots.com/2013/02/classnotfoundexception-vs.html "This is thrown when at compile time the required classes are present, but at run time the classes are changed or removed or class's static initializes threw exceptions. It means the class which is getting loaded is present in classpath, but one of the classes which are required by this class are either removed or failed to load by compiler. So you should see the classes which are dependent on this class."
Examples: this will throw a
If I compile this:
then I delete Test1.class, I get this:
"an exception occurred during evaluation of a static initializer or the initializer for a static variable."
https://docs.oracle.com/javase/7/docs/api/java/lang/NoClassDefFoundError.html
"no definition of the class could be found"
the above 2 are LinkageError (Error). The one below is an Exception:
https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html
Thrown when an application tries to load in a class through its string name using:
The forName method in class Class.
The findSystemClass method in class ClassLoader .
The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.
Difference between NoClassDefFoundError and ClassNotFoundException is well explained here:
http://www.javaroots.com/2013/02/classnotfoundexception-vs.html "This is thrown when at compile time the required classes are present, but at run time the classes are changed or removed or class's static initializes threw exceptions. It means the class which is getting loaded is present in classpath, but one of the classes which are required by this class are either removed or failed to load by compiler. So you should see the classes which are dependent on this class."
Examples: this will throw a
Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.ArithmeticException: / by zero at com.pierre.pvtest.Test.(Test.java:4)
package com.pierre.pvtest;
public class Test {
static int a = 1 / 0;
public static void main(String[] args) {
System.out.println("hello");
}
}
If I compile this:
package com.pierre.pvtest;
public class Test {
public static void main(String[] args) {
Test1 test1 = new Test1();
test1.hello();
System.out.println("hello");
}
}
package com.pierre.pvtest;
public class Test1 {
public void hello() {
System.out.println("Test1 hello");
}
}
then I delete Test1.class, I get this:
java com.pierre.pvtest.Test
Exception in thread "main" java.lang.NoClassDefFoundError: com/pierre/pvtest/Test1
at com.pierre.pvtest.Test.main(Test.java:6)
Caused by: java.lang.ClassNotFoundException: com.pierre.pvtest.Test1
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
Labels:
exceptions,
java
Friday, December 4, 2015
java.lang.ArrayStoreException
When creating an array, remember that it will be not of the type declared for the variable, but of the type decided in the initializer:
this is the output:
so if you initialize an Animal[] as a Cat[], you can't assign to a member a variable of type Dog, even if a Dog is an Animal...
public class ArrayStoreExceptinTest {
public static void main(String[] args) {
System.out.println("starting");
// test 1: all ok
Object[] myarray1 = new Object[2];
System.out.println("myarray1 " + myarray1.getClass().getName());
myarray1[0] = new Integer(0);
myarray1[1] = new String("");
myarray1[1] = new Integer(0);
// test 2: fails with java.lang.ArrayStoreException
try {
Object[] myarray2 = new String[2];
System.out.println("myarray2 " + myarray2.getClass().getName());
myarray2[0] = new Integer(0);
} catch (Exception e) {
e.printStackTrace();
}
// test 3: all ok
Animal[] myarray3 = new Animal[] { new Cat(), new Dog() };
System.out.println("myarray3 " + myarray3.getClass().getName());
myarray3[0] = new Dog();
try {
// test 4: fails with java.lang.ArrayStoreException
Animal[] myarray4 = new Cat[] { new Cat(), new Cat() };
System.out.println("myarray4 " + myarray4.getClass().getName());
myarray4[0] = new Dog();
} catch (Exception e) {
e.printStackTrace();
}
}
}
interface Animal {
}
class Dog implements Animal {
}
class Cat implements Animal {
}
this is the output:
starting myarray1 [Ljava.lang.Object; myarray2 [Ljava.lang.String; java.lang.ArrayStoreException: java.lang.Integer at ArrayStoreExceptinTest.main(ArrayStoreExceptinTest.java:18) myarray3 [LAnimal; myarray4 [LCat; java.lang.ArrayStoreException: Dog at ArrayStoreExceptinTest.main(ArrayStoreExceptinTest.java:32)
so if you initialize an Animal[] as a Cat[], you can't assign to a member a variable of type Dog, even if a Dog is an Animal...
Labels:
java
Thursday, November 26, 2015
Find all Java classes implementing a given interface.... reflections!
https://code.google.com/p/reflections/
Download the ÜBER JAR here https://code.google.com/p/reflections/downloads/detail?name=reflections-0.9.9-RC1-uberjar.jar&can=2&q=
This version will load only classes under the "oracle" package:
Download the ÜBER JAR here https://code.google.com/p/reflections/downloads/detail?name=reflections-0.9.9-RC1-uberjar.jar&can=2&q=
package pierre.reflections;
import java.net.URL;
import java.util.Set;
import org.reflections.Reflections;
public class FindInterfaceImplementations {
public static void main(String[] args) {
Reflections reflections = new Reflections();
Set<URL> urls = reflections.getConfiguration().getUrls();
for (URL item : urls) {
System.out.println(item.toString());
}
Set<Class<? extends javax.enterprise.inject.spi.InjectionTargetFactory>> classes = reflections.getSubTypesOf(javax.enterprise.inject.spi.InjectionTargetFactory.class);
System.out.println(classes.size());
}
}
This version will load only classes under the "oracle" package:
package com.pierre.typequerylanguage;
import java.io.File;
import java.util.Set;
import org.reflections.Reflections;
import oracle.ucp.ConnectionAffinityCallback;
public class FindInterfaceImplementation {
public static boolean VERBOSE = true;
public static void main(String[] args) {
if (VERBOSE) {
System.out.println("searching in the following jars:");
System.out.println(System.getProperty("java.class.path").replace(File.pathSeparatorChar, '\n'));
}
Reflections reflections = new Reflections("oracle");
System.out.println("searching now");
Set<Class<? extends ConnectionAffinityCallback>> classes = reflections.getSubTypesOf(oracle.ucp.ConnectionAffinityCallback.class);
for (Class clazz : classes) {
System.out.println("found: " + clazz.getCanonicalName());
}
System.out.println("searching done");
}
}
Thursday, November 6, 2014
Java: what is your default timezone?
cat MyTimezone.java
javac MyTimezone.java
java MyTimezone
on one machine I have:
The second machine has timezone "Europe/Vaduz", and the Oracle DB doesn't recognize it:
This explains why your JVM might get in trouble with the Oracle DB and you have to set explicitly the timezone yourself...
See also http://www.javamonamour.org/2014/11/ora-01882-timezone-region-not-found.html
Funnily:
these 2 files are identical.
How does Java determine its default timezone from the Linux machine it's running on?
on RHEL, use redhat-config-date system-config-time timeconfig tzselect
import java.util.TimeZone;
public class MyTimezone {
public static void main(String[] args) throws Exception {
TimeZone timeZone = TimeZone.getDefault();
System.out.println(timeZone);
}
}
javac MyTimezone.java
java MyTimezone
on one machine I have:
sun.util.calendar.ZoneInfo[id="Europe/Zurich",offset=3600000,dstSavings=3600000,useDaylight=true, transitions=119,lastRule=java.util.SimpleTimeZone[id=Europe/Zurich,offset=3600000,dstSavings=3600000, useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2, endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]on another machine I have:
sun.util.calendar.ZoneInfo[id="Europe/Vaduz",offset=3600000,dstSavings=3600000,useDaylight=true, transitions=119,lastRule=java.util.SimpleTimeZone[id=Europe/Vaduz,offset=3600000,dstSavings=3600000, useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2, endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
The second machine has timezone "Europe/Vaduz", and the Oracle DB doesn't recognize it:
SELECT * FROM V$TIMEZONE_NAMES where TZNAME = 'Europe/Vaduz';nothing!
This explains why your JVM might get in trouble with the Oracle DB and you have to set explicitly the timezone yourself...
See also http://www.javamonamour.org/2014/11/ora-01882-timezone-region-not-found.html
Funnily:
diff /usr/share/zoneinfo/Europe/Vaduz /etc/localtime diff /usr/share/zoneinfo/Europe/Zurich /etc/localtime
these 2 files are identical.
How does Java determine its default timezone from the Linux machine it's running on?
on RHEL, use redhat-config-date system-config-time timeconfig tzselect
Thursday, August 7, 2014
HTTP GET in Java, performance issues
My first version was:
The above code proved to be EXTREMELY slow. The below version is MUCH faster:
import java.net.*;
URL url = new URL(theURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String wholeInput = "";
String inputLine = null;
while ((inputLine = in.readLine()) != null)
{ wholeInput += inputLine; }
The above code proved to be EXTREMELY slow. The below version is MUCH faster:
URL url = new URL(theURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String wholeInput = "";
String inputLine = null;
while ((inputLine = in.readLine()) != null)
{ wholeInput += inputLine; }
in.close();
SOAP With Attachment with Java, working example
This code actually works , and produces a SOAM message with attachment of type application/octet-stream - which is totally acceptable, even if I would have preferred application/pdf.
I had tried this one before:
but it was failing with this error
For more info see:
http://docs.oracle.com/javaee/5/tutorial/doc/bnbhr.html
http://docs.oracle.com/javase/6/docs/api/javax/activation/FileDataSource.html
http://docs.oracle.com/javase/6/docs/api/javax/activation/DataHandler.html
I would rather say that it could be all a LOT simpler.... Java Java...too verbose...
import javax.xml.soap.*;
import java.net.URL;
import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.activation.*;
// now all the SOAP code
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder builder = dbFactory.newDocumentBuilder();
// add the SOAP body as from text
StringReader sr = new StringReader(textToSend);
InputSource is = new InputSource(sr);
Document document = builder.parse(is);
SOAPBody body = envelope.getBody();
SOAPBodyElement docElement = body.addDocument(document);
// add attachment from file
String filename = theBUSINESSIDVALUE.split("\\^")[0];
File fileAttachment = new File(rootFolderForMSS + filename + ".pdf");
FileDataSource fds = new FileDataSource(fileAttachment);
DataHandler dh = new DataHandler(fds);
out.write("content-type=" + dh.getContentType() + "
");
AttachmentPart attachment = message.createAttachmentPart(dh);
String contentId = "<" + filename + ".pdf>";
attachment.setContentId(contentId);
message.addAttachmentPart(attachment);
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
java.net.URL endpoint = new URL(POSTTOURL);
SOAPMessage soapResponse = connection.call(message, endpoint);
I had tried this one before:
AttachmentPart attachment = message.createAttachmentPart();
String filename = theBUSINESSIDVALUE.split("\\^")[0];
File fileAttachment = new File(rootFolderForMSS + filename + ".pdf");
byte[] fileData = new byte[(int) fileAttachment.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(fileAttachment));
dis.readFully(fileData);
dis.close();
String contentId = "<" + filename + ".pdf>";
attachment.setContent(new ByteArrayInputStream(fileData), "application/pdf");
attachment.setContentId(contentId);
message.addAttachmentPart(attachment);
but it was failing with this error
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/pdf
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:877)
at javax.activation.DataHandler.writeTo(DataHandler.java:302)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1403)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:874)
at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:444)
at weblogic.xml.saaj.SOAPMessageImpl.writeMimeMessage(SOAPMessageImpl.java:959)
at weblogic.xml.saaj.SOAPMessageImpl.writeTo(SOAPMessageImpl.java:832)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.post(HttpSOAPConnection.java:237)
at com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection.call(HttpSOAPConnection.java:144)
For more info see:
http://docs.oracle.com/javaee/5/tutorial/doc/bnbhr.html
http://docs.oracle.com/javase/6/docs/api/javax/activation/FileDataSource.html
http://docs.oracle.com/javase/6/docs/api/javax/activation/DataHandler.html
I would rather say that it could be all a LOT simpler.... Java Java...too verbose...
Thursday, April 24, 2014
the crazy story of securerandom.source=file:/dev/./urandom
More or less everybody know that if SSL encryption operations are slow, the culprit must be the source of entropy from /dev/random, and that you can replace it with /dev/urandom.
Everybody know that you can do this in 2 equivalent ways:
What really is striking is that although this value might already be set by default on Windows, one should actually set as a value "/dev/./urandom" on Linux systems, otherwise APPARENTLY the setting is not actually accepted by Java and it defaults again to /dev/random
How in 2014 we still have to manually take care of these things, it's a mystery. And whether this is actually true, another mystery.
Apparently this is intended - and not a bug http://bugs.java.com/view_bug.do?bug_id=6202721, however it's disheartening. See also Oracle Doc "Long Delay During Startup of SOA Managed Server (Doc ID 1336411.1)" and
http://download.oracle.com/docs/cd/E14571_01/doc.1111/e14772/weblogic_server_issues.htm#ASRSS2066
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6202721
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6521844
However, it says "Note that this workaround should not be used in production environments because it uses pseudo-random numbers instead of genuine random numbers."
Everybody know that you can do this in 2 equivalent ways:
- either you enter securerandom.source=file:/dev/urandom in $JAVA_HOME/jre/lib/security/java.security
- or you start the JVM with the argument -Djava.security.egd=file:/dev/urandom
What really is striking is that although this value might already be set by default on Windows, one should actually set as a value "/dev/./urandom" on Linux systems, otherwise APPARENTLY the setting is not actually accepted by Java and it defaults again to /dev/random
How in 2014 we still have to manually take care of these things, it's a mystery. And whether this is actually true, another mystery.
Apparently this is intended - and not a bug http://bugs.java.com/view_bug.do?bug_id=6202721, however it's disheartening. See also Oracle Doc "Long Delay During Startup of SOA Managed Server (Doc ID 1336411.1)" and
http://download.oracle.com/docs/cd/E14571_01/doc.1111/e14772/weblogic_server_issues.htm#ASRSS2066
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6202721
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6521844
However, it says "Note that this workaround should not be used in production environments because it uses pseudo-random numbers instead of genuine random numbers."
Labels:
java
Monday, April 14, 2014
intercept all java JVM calls
Good man David wrote a script to log all the calls to Java with the parameters passed:
mv /usr/lib/jvm/jre-1.7.0-oracle.x86_64/bin/java /usr/lib/jvm/jre-1.7.0-oracle.x86_64/bin/java_
vi /usr/lib/jvm/jre-1.7.0-oracle.x86_64/bin/java
chmod 775 /usr/lib/jvm/jre-1.7.0-oracle.x86_64/bin/java
At this point, all calls will be logged to /tmp/log_puppet_weblogic/log.txt and the stdout of each command will go into a separate file in /tmp/log_puppet_weblogic/ folder. This is particularly useful to trace all the WLST calls.
mv /usr/lib/jvm/jre-1.7.0-oracle.x86_64/bin/java /usr/lib/jvm/jre-1.7.0-oracle.x86_64/bin/java_
vi /usr/lib/jvm/jre-1.7.0-oracle.x86_64/bin/java
#! /bin/bash
LOG_DIR=/tmp/log_puppet_weblogic
LOG_FILE=$LOG_DIR/log.txt
echo "+++++++++++++++++++++++++++++" | tee -a $LOG_FILE
echo "+++ EXECUTING JAVA. CMD: java" "$@" | tee -a $LOG_FILE
java=$(readlink -f $0)
echo "+++ EXECUTING JAVA. time: "`date +"%Y%m%d-%H%M%S"` | tee -a $LOG_FILE
echo "+++ EXECUTING JAVA. java: $java" | tee -a $LOG_FILE
echo "+++ EXECUTING JAVA. cp: $CLASSPATH" | tee -a $LOG_FILE
for arg; do
# if [[ ${arg: -3} == ".py" ]] || [[ ${arg: -4} == ".xml" ]]; then
if [[ ${arg: -3} == ".py" ]]; then
echo "+++ EXECUTING JAVA. cat $arg. START." | tee -a $LOG_FILE
cat $arg | tee -a $LOG_FILE
echo "+++ EXECUTING JAVA. cat $arg. END." | tee -a $LOG_FILE
f=file-$(basename $arg)-$(date +"%Y%m%d-%H%M%S")
cp $arg $LOG_DIR/$f
fi
done
f=$LOG_DIR/log-$(date +"%Y%m%d-%H%M%S").txt
echo "+++ EXECUTING JAVA. running. log: $f" | tee -a $LOG_FILE
original_java=${java}_
set -e
(($original_java "$@") 2>&1 ) | tee $f
EXIT_CODE=${PIPESTATUS[0]}
echo "+++ EXECUTING JAVA. cat $f. START." | tee -a $LOG_FILE
cat $f | tee -a $LOG_FILE
echo "+++ EXECUTING JAVA. cat $f. END." | tee -a $LOG_FILE
echo "+++ EXECUTING JAVA. exit code: $EXIT_CODE" | tee -a $LOG_FILE
echo "+++ EXECUTING JAVA. END." | tee -a $LOG_FILE
exit $EXIT_CODE
chmod 775 /usr/lib/jvm/jre-1.7.0-oracle.x86_64/bin/java
At this point, all calls will be logged to /tmp/log_puppet_weblogic/log.txt and the stdout of each command will go into a separate file in /tmp/log_puppet_weblogic/ folder. This is particularly useful to trace all the WLST calls.
Labels:
java
Tuesday, January 28, 2014
difference between java and javaw
create this file JavaConsole.java:
compile it:
javac JavaConsole.java
run it:
java JavaConsole > outputjava.txt
javaw JavaConsole > outputjavaw.txt
in the second case, the console object is null, because javaw has not associate a Console to allow for stdin and stdout. We can't even print to a console output, that's why I had to redirect to a file in order to observe the result of the println.
When should I use javaw? Well, frankly, I guess when you don't want a console output, like in most server side applications. Why WebLogic uses java and not javaw? Good question.... in fact, you always want to redirect the stdout of WebLogic to a file (hoping that nothing is written to it...)...
import java.io.Console;
public class JavaConsole {
public static void main(String[] args) {
Console console = System.console();
System.out.println("the console is " + console);
}
}
compile it:
javac JavaConsole.java
run it:
java JavaConsole > outputjava.txt
javaw JavaConsole > outputjavaw.txt
in the second case, the console object is null, because javaw has not associate a Console to allow for stdin and stdout. We can't even print to a console output, that's why I had to redirect to a file in order to observe the result of the println.
When should I use javaw? Well, frankly, I guess when you don't want a console output, like in most server side applications. Why WebLogic uses java and not javaw? Good question.... in fact, you always want to redirect the stdout of WebLogic to a file (hoping that nothing is written to it...)...
Labels:
java
Tuesday, January 21, 2014
Garbage Collection: testing the GC plugin for VisualVM
Watch the excellent tutorial
Install VisualVm GC plugin (I had to download it locally to install it, I could not install directly...) (beware, you should use visualvm for java 7, otherwise the plugin installation will fail)
I run this test code:
I run it with Java 7 and I get this:
Install VisualVm GC plugin (I had to download it locally to install it, I could not install directly...) (beware, you should use visualvm for java 7, otherwise the plugin installation will fail)
I run this test code:
package com.pierre.gctests;
import java.util.ArrayList;
public class PVOOM {
public static void main(String[] args) throws InterruptedException {
ArrayList al = new ArrayList();
for (int i = 0; i < 1000000; i++) {
for (int j = 0; j< 1000; j++) {
al.add(new Animal(Integer.toString(i)));
}
Thread.sleep(1);
}
}
}
class Animal {
public Animal(String name) {
super();
this.name = name;
}
String name;
}
I run it with Java 7 and I get this:
Sunday, August 4, 2013
Escaping strings in Java or Groovy
Working with Strings in Java is a pain, because Java does its best to prevent you from using characters like " or \ in a string.
Escaping is a pain but there is no way around it - apart from ditching Java in favor of Groovy which is a lot more flexible.
Either you use http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html apache commons library escapeJava(), or Groovy escapeUtils http://groovy.codehaus.org/gapi/groovy/json/StringEscapeUtils.html , or just write a little function:
def escapeString(theString) {
return theString.replace('\\', '\\\\').replaceAll('"',"'").replaceAll('\n', '" +\n"')
//this is the list of all replace you need to implement: {"'", "\\'"}, {"\"", "\\\""}, {"\\", "\\\\"},{"/", "\\/"}
}
Escaping is a pain but there is no way around it - apart from ditching Java in favor of Groovy which is a lot more flexible.
Either you use http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html apache commons library escapeJava(), or Groovy escapeUtils http://groovy.codehaus.org/gapi/groovy/json/StringEscapeUtils.html , or just write a little function:
def escapeString(theString) {
return theString.replace('\\', '\\\\').replaceAll('"',"'").replaceAll('\n', '" +\n"')
//this is the list of all replace you need to implement: {"'", "\\'"}, {"\"", "\\\""}, {"\\", "\\\\"},{"/", "\\/"}
}
and good luck.
Labels:
java
Tuesday, April 23, 2013
download java 6 update 33
It took me some googling to find out where to download an older version of Java: http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase6-419409.html .
Well hidden, indeed.
Well hidden, indeed.
Labels:
java
Subscribe to:
Posts (Atom)

