How to Read/convert an InputStream to a String

There are multiple ways .I will list down few of them.

Using Old and standard java solution –

public static String fromStream(InputStream in) throws IOException
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder out = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
    return out.toString();

return sb.toString();

if you using Google-Collections/Guava-

InputStream stream = ...
String content = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));

If you can use Apache Common library..then this is useful –

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

Quick way but only work in deserialization process –

String result = (String)new ObjectInputStream( inputStream ).readObject();

Note:ObjectInputStream is about deserialization, and the stream have to respect the serialization protocol to work, which may not always true in all cases.

In the end, the most efficient solution and only in two lines using java Scanner class –

Tricky is to remember the regex \A, which matches the beginning of input. This effectively tells Scanner to tokenize the entire stream, from beginning to (illogical) next beginning.

public static String convertToString(InputStream in) {
    java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");  
    return s.hasNext() ? : "";

I would love to hear any comment by you for making more simple…

Happy learning by Vinay Kumar in techartifact

How to create custom component in Webcenter Content (UCM)

Requirement – How to Create a UCM custom component

Solutions- Please follow the below steps –

Starting the componentWizard – CD to the path where the component wizard is.
[[email protected] ~]$ cd /oracle/Middleware/user_projects/domains/ucm_domain/ucm/cs/bin // this path will of your weblogic domain
[[email protected] bin]$ ./ComponentWizard

1. Goto Options -> Add
You get the below window.
Fill in the component Name. Click OK.


You get below screen.
Custom component gets created here (path may be different for you)
The component is created and you can add resources by clicking Add.


1. Select service. Click next.


Fill in the Name of the Service, Service class, Template. Fill in access levels.
Add actions by clicking on Add.



Click OK. Click Finish.

Similarly Add a Resource.



Resources created

Modify the resource.htm as below. Give the Service name, handler name and search order.
The handler name is the fully qualified name of the java file where the service method (printTheName()) is created.

Place the compiled java class file in the classes folder inside the custom component.




Build the component to create the manifest.hda file. is created that can now be installed on other UCM and used.
Build by clicking on Build.



Enable the component.


Hit the browser with the service Name and required parameters
My java code is as below. (Calls a standard UCM service from my custom service)


import intradoc.common.ExecutionContext;
import intradoc.common.LocaleUtils;
import intradoc.common.Log;
import intradoc.common.ServiceException;
import intradoc.common.SystemUtils;
import intradoc.provider.Provider;
import intradoc.provider.Providers;
import intradoc.server.Service;
import intradoc.server.ServiceData;
import intradoc.server.ServiceHandler;
import intradoc.server.ServiceManager;
import intradoc.server.UserStorage;
import intradoc.shared.SharedObjects;
import intradoc.shared.UserData;

public class PrintingNames extends ServiceHandler{
	public void printTheName() throws DataException, ServiceException
	{"Start printing name"+ true);
	String Docname = m_binder.getLocal("dDocName");
	String serviceName = "DOC_INFO_BY_NAME";
    String userName = m_binder.getLocal("dUser");"environment "+m_binder.getEnvironment());"shared obj val"+SharedObjects.getEnvironmentValue("IntradocServerPort"));
	DataBinder requestBinder = new DataBinder();
	requestBinder.putLocal("dDocName", Docname);
	requestBinder.putLocal("IdcService", serviceName);
    final ResultSet docinforesultset = requestBinder.getResultSet("DOC_INFO");
    DataResultSet docinfodataresultset = (DataResultSet)requestBinder.getResultSet("DOC_INFO");

	DataResultSet result = new DataResultSet();
	m_binder.putLocal("Message", "Name printed");
	m_binder.addResultSet("demo_resultset1", docinforesultset);
	m_binder.addResultSet("demo_resultset2", docinfodataresultset);"Finished printing name");

	public void executeService(DataBinder binder, String userName, boolean suppressServiceError)
	        throws DataException, ServiceException
	        ServiceException error;
	        Workspace workspace = getSystemWorkspace();
	        String cmd = binder.getLocal("IdcService");
	        if(cmd == null)
	            throw new DataException("!csIdcServiceMissing");
	        ServiceData serviceData = ServiceManager.getFullService(cmd);
	        if(serviceData == null)
	            throw new DataException(LocaleUtils.encodeMessage("!csNoServiceDefined", null, cmd));
	        Service service = ServiceManager.createService(serviceData.m_classID, workspace, null, binder, serviceData);
	        UserData fullUserData = getFullUserData(userName, service, workspace);
	        binder.m_environment.put("REMOTE_USER", userName);
	        error = null;
	            service.setSendFlags(true, true);
	        catch(ServiceException e)
	            error = e;
	        if(error != null)
	                if(binder.getLocal("StatusCode") == null)
	                    binder.putLocal("StatusCode", String.valueOf(error.m_errorCode));
	                    binder.putLocal("StatusMessage", error.getMessage());
	            } else
	                throw new ServiceException(error.m_errorCode, error.getMessage());
	public UserData getFullUserData(String userName, ExecutionContext cxt, Workspace ws)
	        throws DataException, ServiceException
	        if(ws == null)
	            ws = getSystemWorkspace();
	        UserData userData = UserStorage.retrieveUserDatabaseProfileDataFull(userName, ws, null, cxt, true, true);
	        return userData;
	public static Workspace getSystemWorkspace()
        Workspace workspace = null;
        Provider wsProvider = Providers.getProvider("SystemDatabase");
        if (wsProvider != null)
            workspace = (Workspace) wsProvider.getProvider();
        return workspace;

Happy coding with Vinay Kumar in Techartifact…..

How JRE works internally.

Interesting facts about the JRE

Every Java developer use each day classes from the JRE, there are some most used classes like String and Array and others less known like Corba ones. In this article we will discuss about some JRE facts that can be helpful to know.
For that we will analyze the rt.jar package from the JRE 7 with JArchitect to go deep inside it , and to query its code base using CQLinq.
JRE types implementing interfaces or abstract classes
Imagine you ask two developers to declare a class which has one method doing calculation from a file as entry.
Developer A declare it like this

class A
public void calculate(FileStream fs)
And here’s the declaration of the developer B:
class B
public void calculate(InputStream fs)

Which is better and why?

To answer this question let’s take a sample code using this class
A a=new A();
FileInputStream in = new FileInputStream(“data.txt”);

What happen if we want to get data from ByteArrayInputStream or StringBufferInputStream?
The declaration of A don’t allow us to do that unless we change the declaration of the calculate method. However no problem occurs when we use the B class, indeed calculate take as parameter InputStream and can accept any class inheriting from InputStream.
As conclusion the B class protect from changes because it use abstract class instead of the concrete class.
Let’s search in the JRE all types that implement an interface, for that let’s execute the following CQLinq query:
from t in Types where t.IsClass && !t.IsInternal && t.NbInterfacesImplemented>0
select new { t,Interface=t.InterfacesImplemented.FirstOrDefault().Name }

And we can also search for classes inheriting from an abstract class:
from t in Types where t.IsClass && !t.IsInternal && t.BaseClasses.Where(a=>a.IsAbstract).Count()>0
select new { t,t.BaseClasses.Where(a=>a.IsAbstract).FirstOrDefault().Name }

Let’s search now for all classes implementing an interface or inheriting from an abstract class:
from t in Types where t.IsClass && !t.IsInternal && (t.NbInterfacesImplemented>0 || t.BaseClasses.Where(a=>a.IsAbstract).Count()>0)
select new { t }
And to have a better idea of classes concerned, let’s visualize the result in the metric view.
In the Metric View, the code base is represented through a Treemap. Treemapping is a method for displaying tree-structured data by using nested rectangles. The tree structure used in JArchitect treemap is the usual code hierarchy:
– Projects contains packages
– Packages contains types
– Types contains methods and fields
The treemap view provides a useful way to represent the result of CQLinq request, so we can see visually the types concerned by the request.

As we can observe many classes are concerned by the last CQLinq query, so the JRE is designed to help you to protect your code from changes by using interfaces and abstract classes, and it’s better to check as possible if a class implements an interface or inherit from an abstract class.
Immutable types
Basically, an object is immutable if its state doesn’t change once the object has been created. Consequently, a class is immutable if its instances are immutable.
There is one killer argument for using immutable objects: It dramatically simplifies concurrent programming. Think about it, why does writing proper multithreaded programming is a hard task? Because it is hard to synchronize threads accesses to resources (objects or others OS things). Why it is hard to synchronize these accesses? Because it is hard to guarantee that there won’t be race conditions between the multiple write accesses and read accesses done by multiple threads on multiple objects. What if there are no more write accesses? In other words, what if the state of the objects threads are accessing, doesn’t change? There is no more need for synchronization!
Let’s search for all JRE immutable classes
from t in Types where t.IsImmutable select t

The good news is that many classes are immutable, however String is not in the list despite of it’s the well-known immutable class of the JRE. Why this is the case?
The reason is that String contains a not final field named hash that can be modified by the public hashCode() method, but even of the existence of this field the String still immutable, and you can refer to this link to have more details why?
The JRE is designed to protect you as possible in the case of multithreading programming.
Generic types
Generics are a facility of generic programming that was added to the Java programming language in 2004 as part of J2SE 5.0. They allow a type or method to operate on objects of various types while providing compile-time type safety. A common use of this feature is when using a Java Collection that can hold objects of any type, to specify the specific type of object stored in it.
Let’s search all JRE generic types:
from t in Types where t.IsGeneric select t

To enforce type safety prefers using generic collections instead of the classic ones.

Deprecated types
A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists.
Let’s search for deprecated types
from t in Types where t.HasAnnotation(“java.lang.Deprecated”)
select new { t, t.NbBCInstructions }

The good news is that only a few types are deprecated, what makes the JRE cleaner.
Deprecated methods
Let’s search for deprecated methods:
from m in Methods where m.HasAnnotation(“java.lang.Deprecated”)
select new { m, m.NbBCInstructions }

Even if 437 are concerned, it represents only 0.2% of all methods. And many of them are from the awt package.
Classes with lake of cohesion
The single responsibility principle states that a class should have one, and only one, reason to change. Such a class is said to be cohesive. A high LCOM value generally pinpoints a poorly cohesive class. There are several LCOM metrics. The LCOM takes its values in the range [0-1]. The LCOMHS (HS stands for Henderson-Sellers) takes its values in the range [0-2]. Note that the LCOMHS metric is often considered as more efficient to detect non-cohesive types.
LCOMHS value higher than 1 should be considered alarming.
from t in Types where t.LCOMHS>1
select new { t,t.LCOMHS }

Only few types have this problem, and for some of them it just due to a not cleaned code like for the BootstrapServer class, which have a not used field named orb. and because its the only field the class is considered poorly cohesive.
Most complex classes
Complex classes are the more risky to maintain and evolve, let’s search for the more complex JRE classes:
(from t in Types
orderby t.BCCyclomaticComplexity descending
select new { t, t.BCCyclomaticComplexity }).Take(100)

If a class is very complex, there’s more chance that it will be less stable due to bugs generated by the complexity, and the classes using them have to protect their self by not using them directly and use instead if possible interface or abstract class.
We can improve the last CQLinq query and add two other infos: the number of types using them and a flag to know if there’s any interface or abstract class that can we use instead of the concrete classes.

(from t in Types
let HasAbtractType=t.NbInterfacesImplemented>0 || t.BaseClasses.Where(a=>a.IsAbstract).Count()>0
orderby t.BCCyclomaticComplexity descending
select new { t, t.BCCyclomaticComplexity , t.NbTypesUsingMe,HasAbtractType=HasAbtractType}).Take(100)

Many of them have an interface or abstract class, which is a good thing to protect your code from complex types.
The JRE classes are maybe the most used in the java world, they must be well designed and implemented, it’s a good idea to take a look inside a JRE and discover how they are implemented, it can help to have a cleaner source code.

Guest Author of article- Dane . You can find more article from this author on Dane’s blog