StringBuilder to String.

Hi im doing a Open uni course and am getting read to sit my exam so i have downloaded some old test papers and have been going throught them and am stuck on one question that takes a file and the reads from said file one line at a time and changes each char into another char so if i had an A it would change it to an int then add - 3 to it and then take the new string and write it to a new file i have coded.
import ou.*;
import java.io.*;
import java.util.*;
public class cipher
public static void encryptFile()
String pathwayRead = OUFileChooser.getFilename();
String pathwayWrite = OUFileChooser.getFilename();
File readFile = new File(pathwayRead);
File writeFile = new File(pathwayWrite);
BufferedReader bufferedFileReader = null;
BufferedWriter bufferedFileWriter = null;
StringBuilder temp = null;
String currentLine;
int counter = 1;
int letter;
try
   bufferedFileReader = new BufferedReader(new FileReader(readFile));
   bufferedFileWriter = new BufferedWriter(new FileWriter(writeFile));
   currentLine = bufferedFileReader.readLine();
   while (currentLine != null)
         if (counter == 5)
            counter = 1;
          for (int i = 0; i < currentLine.length(); i++)
            temp = new StringBuilder(currentLine);
            letter = temp.charAt(i);
            System.out.println((char)letter);
            letter = letter - counter;
            System.out.println((char)letter);
            temp.deleteCharAt(i);
            temp.insert(i, (char)letter);
            System.out.println(temp.charAt(i));
         counter = counter + 1;
         bufferedFileWriter.write(temp.toString());
         bufferedFileWriter.newLine();
         currentLine = bufferedFileReader.readLine();
catch(Exception anException)
     System.out.println("Error: " + anException);
finally
   try
      bufferedFileWriter.close();
      bufferedFileReader.close();
   catch(Exception anException)
      System.out.println("Error: " + anException);
}the System.out.println show me that the char are being changed as i wish but they are not being written like this.
say in one file i have the work "luke" i read in this file and the output file would have "lukd".

i figured it out i put the temp = new StringBuilder(currentLine); in the for loop when i moved it to the while loop the program work got to love programmer error.
Edited by: LukeD on Jun 8, 2008 8:47 AM

Similar Messages

  • Sorting a String

    Hi,
    I was wondering how would I sort the following String using String class methods and StringTokenizer.
    For example.
    Input: String a = 12hello^25hello^10hello;
    Sort it chronologically
    Output String a = 10hello^12hello^25hello;
    Thanks in advance.

    In Java 5.0, something like the following?
    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class Test {
        public static void main(String[] args) {
            String a = "12hello^25hello^10hello^100hello";
            String[] tokens = a.split("\\^");
            Arrays.sort(tokens, new Comparator<String>() {
                String regexp = "(\\d+)";
                Pattern p = Pattern.compile(regexp);
                public int compare(String s1, String s2) {
                    Matcher m1 = p.matcher(s1);
                    Matcher m2 = p.matcher(s2);
                    if (!m1.find() || !m2.find()) {
                        return s1.compareTo(s2);
                    int i1 = Integer.parseInt(m1.group(1));
                    int i2 = Integer.parseInt(m2.group(1));
                    if (i1 < i2) {
                        return -1;
                    } else if (i1 > i2) {
                        return 1;
                    } else {
                        return s1.compareTo(s2);
            StringBuilder sb = new StringBuilder();
            for (String b : tokens) {
                sb.append("^").append(b);
            String result = sb.toString().substring(1);
            System.out.println(result);
    }Beware, I haven't checked this for bugs. You'd probably want to check the logic of the comparator ;-)
    Cheers, Neil

  • Build XML for Custom Nested Accordian (like Tree View Structure) for SharePoint List Data

    Expected output in Xml:
    <?xml version="1.0" encoding="utf-8" ?>
    - <TopRoot>
    - <Root id="1" Name="Department">
    - <Type id="2" Name="IT">
    - <SubType id="3" Name="Technology">
      <SubSubType id="4" Name="Sharepoint" />
      <SubSubType id="5" Name="ASP.NET" />
      <SubSubType id="6" Name="HTML 5" />
      </SubType>
      </Type>
    </Root>
    </TopRoot>
    List Details:
    list details for storing category / sub category data and code to build tree structure for the same.
    1.Create Custom List named “CategoryDetails”:
    2.Create Column “Category Name” of type single line of text. Make it as required field and check Yes for Enforce Unique values.
    3.Create column “Parent Category” of type lookup. under Additional Column Settings.
    Get information dropdown, select “CategoryDetails”.
    4.Choice column ["SRTypeName"] 1.Root,2.SRTYPE,3.SubSRTYPE, 4.SUBSUBSRTYPE
    In this column dropdown, select “Category Name”:  
    Referance:
    http://www.codeproject.com/Tips/627580/Build-Tree-View-Structure-for-SharePoint-List-Data    -fine but don't want tree view just generate xml string
    i just follwed above link it work perferfectly fine for building tree view but i don't want server control.
    Expected Result:
    My ultimate goal is to generate xml string like above format without building tree view.
    I want to generate xml using web service and using xml i could convert into nested Tree View Accordian in html.
    I developed some code but its not working to generate xml /string.
    My modified Code:
    public const string DYNAMIC_CAML_QUERY =
            "<Where><IsNull><FieldRef Name='{0}' /></IsNull></Where>";
            public const string DYNAMIC_CAML_QUERY_GET_CHILD_NODE =
            "<Where><Eq><FieldRef Name='{0}' /><Value Type='LookupMulti'>{1}</Value></Eq></Where>";
            protected void Page_Load(object sender, EventArgs e)
                if (!Page.IsPostBack)
                 string TreeViewStr= BuildTree();
                 Literal1.Text = TreeViewStr;
            StringBuilder sbRoot= new StringBuilder();
            protected string BuildTree()
                SPList TasksList;
                SPQuery objSPQuery;
                StringBuilder Query = new StringBuilder();
                SPListItemCollection objItems;
                string DisplayColumn = string.Empty;
                string Title = string.Empty;
                string[] valueArray = null;
                try
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                        using (SPWeb web = site.OpenWeb())
                            TasksList = SPContext.Current.Web.Lists["Service"];
                            if (TasksList != null)
                                objSPQuery = new SPQuery();
                                Query.Append(String.Format(DYNAMIC_CAML_QUERY, "Parent_x0020_Service_x0020_Id"));
                                objSPQuery.Query = Query.ToString();
                                objItems = TasksList.GetItems(objSPQuery);
                                if (objItems != null && objItems.Count > 0)
                                    foreach (SPListItem objItem in objItems)
                                        DisplayColumn = Convert.ToString(objItem["Title"]);
                                        Title = Convert.ToString(objItem["Title"]);
                                        int rootId=objItem["ID"].ToString();
                                        sbRoot.Append("<Root id="+rootId+"
    Name="+Title+">");
                                        string SRAndSUBSRTpe = CreateTree(Title, valueArray,
    null, DisplayColumn, objItem["ID"].ToString());
                                        sbRoot.Append(SRAndSUBSRTpe);
                                        SRType.Clear();//make SRType Empty
                                        strhtml.Clear();
                                    SRType.Append("</Root>");
                catch (Exception ex)
                    throw ex;
                return SRType.ToString();
             StringBuilder strhtml = new StringBuilder();
            private string CreateTree(string RootNode, string[] valueArray,
          List<SPListItem> objNodeCollection, string DisplayValue, string KeyValue)
                try
                    strhtml.Appends(GetSRType(KeyValue, valueArray, objNodeCollection);
                catch (Exception ex)
                    throw ex;
                return strhtml;
            StringBuilder SRType = new StringBuilder();
            private string GetSRType(string RootNode,
            string[] valueArray, List<SPListItem> objListItemColn)
                SPQuery objSPQuery;
                SPListItemCollection objItems = null;
                List<SPListItem> objNodeListItems = new List<SPListItem>();
                objSPQuery = new SPQuery();
                string objNodeTitle = string.Empty;
                string objLookupColumn = string.Empty;
                StringBuilder Query = new StringBuilder();
                SPList objTaskList;
                SPField spField;
                string objKeyColumn;
                string SrTypeCategory;
                try
                    objTaskList = SPContext.Current.Web.Lists["Service"];
                    objLookupColumn = "Parent_x0020_Service_x0020_Id";//objTreeViewControlField.ParentLookup;
                    Query.Append(String.Format
                    (DYNAMIC_CAML_QUERY_GET_CHILD_NODE, objLookupColumn, RootNode));
                    objSPQuery.Query = Query.ToString();
                    objItems = objTaskList.GetItems(objSPQuery);
                    foreach (SPListItem objItem in objItems)
                        objNodeListItems.Add(objItem);
                    if (objNodeListItems != null && objNodeListItems.Count > 0)
                        foreach (SPListItem objItem in objNodeListItems)
                            RootNode = Convert.ToString(objItem["Title"]);
                            objKeyColumn = Convert.ToString(objItem["ID"]);
                            objNodeTitle = Convert.ToString(objItem["Title"]);
                            SrTypeCategory= Convert.ToString(objItem["SRTypeName"]);
                           if(SrTypeCategory =="SRtYpe")
                              SRType.Append("<Type  id="+objKeyColumn+" Name="+RootNode+ ">");
                             if (!String.IsNullOrEmpty(objNodeTitle))
                              SRType.Append(GetSRType(objKeyColumn, valueArray, objListItemColn));
                          if(SrTypeCategory =="SRSubTYpe")
                              SRType.Append("<SRSubType  id="+objKeyColumn+" Name="+RootNode+
    ">");  
                             if (!String.IsNullOrEmpty(objNodeTitle))
                              SRType.Append(GetSRType(objKeyColumn, valueArray, objListItemColn));
                          if(SrTypeCategory =="SubSubTYpe")
                              SRType.Append("<SubSubType  id="+objKeyColumn+" Name="+RootNode +"
    ></SubSubType");  
                        SRType.Append("</SubType>");
                        SRType.Append("</Type>");
                catch (Exception ex)
                    throw ex;
                return SRType.ToString();
                // Call method again (recursion) to get the child items

    Hi,
    According to your post, my understanding is that you want to custom action for context menu in "Site Content and Structure" in SharePoint 2010.
    In "SiteManager.aspx", SharePoint use MenuItemTemplate class which represent a control that creates an item in a drop-down menu.
    For example, to create or delete the ECB menu for a list item in
    "Site Content and Structure", we can follow the steps below:
    To add the “My Like” menu, we can add the code below:      
    <SharePoint:MenuItemTemplate
    UseShortId=false
    id="OLListItemLike"
    runat="server"
    Text="My Like"
    ImageUrl="/_layouts/images/DelItem.gif"
    ClientOnClickNavigateUrl="https://www.google.com.hk/"
    />
    To remove the “Delete” menu, we can comment the code below:
    <SharePoint:MenuItemTemplate
    UseShortId=false
    id="OLListItemDelete"
    runat="server"
    Text="<%$Resources:cms,SmtDelete%>"
    ImageUrl="/_layouts/images/DelItem.gif"
    ClientOnClickScript="%SmtObjectDeleteScript%"
    />            
    The result is as below:
    More information:
    MenuItemTemplate Class (Microsoft.SharePoint.WebControls)
    MenuItemTemplate.ClientOnClickScript property (Microsoft.SharePoint.WebControls)
    Best Regards,
    Linda Li
    Linda Li
    TechNet Community Support

  • How to look for a particular phrase in a document???

    Hey guys, I'm a little new at this thing... I need to figure out a way to make Java search through a document looking for instances of particular phrases, and replacing them with something else. For example, have it look for "A B C" and replace each such combination of words with "D E F". The search/replace needs to look for a few different phrases at once.

    String.replaceAll is a fine answer, but you are creating Strings left, right & center, tis best to use a StringBuilder/Buffer.
        private static void replaceAll( StringBuilder sb, String search, String replace ) {
         int index = sb.indexOf( search, 0 );
         while( index >= 0 ) {
             sb.replace( index, index+search.length(), replace );
             index = sb.indexOf( search, index );
        }

  • Date picker for af:inputDate   is not picking up the correct input date

    view source:
    <af:inputDate value="#{bindings.DateField.attributeValue}" label="#{bindings.DateField.hints.label}"
    required="#{bindings.DateField.hints.mandatory}"
    valueChangeListener="#{pageFlowScope.CollectApplicantInformation.datesItemChanged}"
    columns="#{bindings.DateField.hints.displayWidth}" shortDesc="#{CustomTooltip[DateField]}"
    autoSubmit="true" helpTopicId="AppDt" id="DateField" simple="true">
    <f:validator binding="#{bindings.DateField.validator}"/>
    *<f:converter converterId="CustomConverter"/>*
    </af:inputDate>
    Here I am not using <af:ConvertDateTime> insted using customConverter, so what code changes do I need to make sure the date picker always picks the already existind date in the inputDate rather picking the current date?
    Here is my CustomConverter.java
    CustomConverter.java
    public class CustomConverter extends DateTimeConverter implements ClientConverter, Converter
    public Object getAsObject(FacesContext context, UIComponent component, String value)
    String dataType = (String) resolveExpression("#{bindings." + component.getId() + ".attributeDef.javaType.name}");
    if (dataType != null && !dataType.equalsIgnoreCase("oracle.jbo.domain.Date") && !dataType.equalsIgnoreCase("oracle.jbo.domain.Timestamp"))
    String test = null;
    if (context == null || component == null)
    throw new NullPointerException();
    if (value != null)
    // To solve DB transaction dirty issue, Check isEmpty and return null.
    if (value.isEmpty())
    return null;
    // the "value" is stored on the value property of the component.
    // The Unified EL allows us to check the type
    ValueExpression expression = component.getValueExpression("value");
    if (expression != null)
    Class<?> expectedType = expression.getType(context.getELContext());
    if (expectedType != null)
    System.out.println("expectedType Value:::" + expectedType.getName());
    // try to convert the value (Object) to the TYPE of the "value" property
    // of the underlying JSF component
    try
    return TypeFactory.getInstance(expectedType, value);
    catch (DataCreationException e)
    String errorMessage;
    if (expectedType.equals(CustomNumber.class))
    errorMessage = "You can enter only Numbers in this field";
    else
    errorMessage = e.getMessage();
    if (errorMessage != null)
    FacesContext ctx = FacesContext.getCurrentInstance();
    FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Format" , errorMessage);
    ctx.addMessage(component.getClientId(), fm);
    catch (CustomDomainException e)
    int errorCode = e.getErrorMessageCode();
    String[] errorMessage = e.getErrorMessageParams();
    if (errorCode == 7 && errorMessage != null)
    String msg = "Invalid " + errorMessage[0];
    FacesContext ctx = FacesContext.getCurrentInstance();
    FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Application Error: ", msg);
    ctx.addMessage(component.getClientId(), fm);
    catch (JboException e)
    Throwable cause = e.getCause();
    if (cause == null)
    cause = e;
    test = "not good format";
    throw e;
    return null;
    else
    return value != null? value: null;
    public String getAsString(FacesContext context, UIComponent component, Object value)
    return value != null? value.toString(): null;
    public String getClientLibrarySource(FacesContext context)
    return null;
    @Override
    public Collection<String> getClientImportNames()
    return Collections.emptySet();
    @Override
    public String getClientScript(FacesContext context, UIComponent component)
    String formatMask = (String) resolveExpression("#{bindings." + component.getId() + ".format}");
    if (formatMask != null)
    String dataType = (String) resolveExpression("#{bindings." + component.getId() + ".attributeDef.javaType.name}");
    if (dataType.equalsIgnoreCase("oracle.jbo.domain.Date") || dataType.equalsIgnoreCase("oracle.jbo.domain.Timestamp"))
    if (component == null)
    _LOG.severe("The component is null, but it is needed for the client id, so no script written");
    return null;
    // Add a JavaScript Object to store the datefield formats
    // on the client-side. We currently store the format string
    // for each and every field. It'd be more efficient to have
    // an array of formats, then store for each field the
    // index of the format, especially if we could delay outputting
    // these objects to when the <form> closes.
    String clientId = component.getClientId(context);
    if (clientId != null)
    // =-=AEW Only if Javascript...
    Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
    // this fetch could be at the place where we append, but has been
    // moved ahead to optimize use of StringBuilder
    String jsPattern = getJSPattern(context, component);
    String loc = _getLocaleString(context);
    // FIX - figure out size!!!
    // 127 chars for javascript + length of jspattern + locale + 12 chars for
    // tranforming to name in the worst case.
    StringBuilder buff = new StringBuilder(139 + jsPattern.length() + loc.length());
    if (requestMap.get(_PATTERN_WRITTEN_KEY) == null)
    requestMap.put(_PATTERN_WRITTEN_KEY, Boolean.TRUE);
    // only create the _dfs object if it doesn't exist, so we don't
    // wipe out _dfs[xxx] values if we ppr the first date field on a
    // page with multiple date fields.
    buff.append("if(window['_dfs'] == undefined){var _dfs=new Object();}if(window['_dl'] == undefined){var _dl=new Object();}");
    buff.append("_dfs[\"");
    buff.append(clientId);
    buff.append("\"]=");
    buff.append(jsPattern);
    buff.append(";");
    buff.append("_dl[\"");
    buff.append(clientId);
    buff.append("\"]=");
    buff.append(loc);
    buff.append(";");
    return buff.toString();
    else
    LOG.severe("NULLCLINET_ID_NO_SCRIPT_RENDERED");
    return null;
    else
    return null;
    else
    return null;
    private String _getLocaleString(FacesContext context)
    Locale dateTimeConverterLocale = getLocale();
    if (dateTimeConverterLocale != null)
    Locale defaultLocale = RenderingContext.getCurrentInstance().getLocaleContext().getFormattingLocale();
    if (!(dateTimeConverterLocale.equals(defaultLocale)))
    String loc = dateTimeConverterLocale.toString();
    StringBuffer sb = new StringBuffer(2 + loc.length());
    sb.append("'");
    sb.append(loc);
    sb.append("'");
    return (sb.toString());
    return "null";
    @Override
    @Deprecated
    public String getClientConversion(FacesContext context, UIComponent component)
    String formatMask = (String) resolveExpression("#{bindings." + component.getId() + ".format}");
    if (formatMask != null)
    String dataType = (String) resolveExpression("#{bindings." + component.getId() + ".attributeDef.javaType.name}");
    if (dataType.equalsIgnoreCase("oracle.jbo.domain.Date") || dataType.equalsIgnoreCase("oracle.jbo.domain.Timestamp"))
    String jsPattern = getJSPattern(context, component);
    Map<String, String> messages = new HashMap<String, String>();
    if (jsPattern != null)
    Class<?> formatclass = formatMask.getClass();
    System.out.println("FormatClass::" + formatclass);
    System.out.println(" Format Mask : " + formatMask);
    // SimpleDateFormat sdfDestination = new SimpleDateFormat(formatMask);
    String pattern = formatMask; //getPattern();
    if (pattern == null)
    pattern = getSecondaryPattern();
    String key = getViolationMessageKey(pattern);
    Object[] params = new Object[]
    { "{0}", "{1}", "{2}" };
    Object msgPattern = getMessagePattern(context, key, params, component);
    //if hintFormat is null, no custom hint for date, time or both has been specified
    String hintFormat = _getHint();
    FacesMessage msg = null;
    String detailMessage = null;
    if (msgPattern != null)
    msg = MessageFactory.getMessage(context, key, msgPattern, params, component);
    detailMessage = XhtmlLafUtils.escapeJS(msg.getDetail());
    Locale loc = context.getViewRoot().getLocale();
    SimpleDateFormat formatter = new SimpleDateFormat(pattern, loc);
    java.lang.Object obj = resolveExpression("#{bindings." + component.getId() + ".attributeValue}");
    String databaseDate=null;
    if(obj!=null)
    databaseDate = obj.toString();
    DateFormat df = new SimpleDateFormat(pattern,loc);
    System.out.println("DateComponent input value :::::::::::::::::::::::::"+databaseDate);
    Date today;
    try {
    // System.out.println("Before Conversion::::::::::::"+df.parse(databaseDate).toString());
    if(databaseDate!=null)
    today = df.parse(databaseDate);
    else
    today = new Date();
    System.out.println("After Conversion Date :::::::::::::::::::::::::::::"+today.toString());
    //Date today = new Date();
    String dt = formatter.format(today);
    String exampleString = dt;
    String escapedType = XhtmlLafUtils.escapeJS(getType().toUpperCase());
    StringBuilder outBuffer = new StringBuilder();
    outBuffer.append("new TrDateTimeConverter(");
    outBuffer.append(jsPattern);
    // loc = getLocale();
    if (loc != null)
    outBuffer.append(",'");
    outBuffer.append(loc.toString());
    outBuffer.append("','");
    else
    outBuffer.append(",null,'");
    outBuffer.append(exampleString);
    outBuffer.append("','");
    outBuffer.append(escapedType);
    outBuffer.append("'");
    if (msgPattern != null || hintFormat != null)
    messages.put("detail", detailMessage);
    messages.put("hint", hintFormat);
    outBuffer.append(',');
    // try
    // JsonUtils.writeMap(outBuffer, messages, false);
    // catch (IOException e)
    // outBuffer.append("null");
    outBuffer.append(')'); // 2
    return outBuffer.toString();
    catch(ParseException e)
    System.out.println("Parse Exception :::::::::::::::::::::"+e);
    return null;
    else
    // no pattern-matchable date
    return null;
    else
    return null;
    else
    return null;
    protected String getJSPattern(FacesContext context, UIComponent component)
    String jsPattern = null;
    String datePattern = (String) resolveExpression("#{bindings." + component.getId() + ".format}");
    if (datePattern != null)
    String secondaryPattern = getSecondaryPattern();
    if (datePattern != _NO_JS_PATTERN)
    int length = datePattern.length() * 2 + 2;
    if (secondaryPattern != null)
    length = length + 3 + secondaryPattern.length() * 2;
    StringBuilder outBuffer = new StringBuilder(length);
    jsPattern = _getEscapedPattern(outBuffer, datePattern, secondaryPattern);
    else
    jsPattern = datePattern;
    return jsPattern;
    private static void _escapePattern(StringBuilder buffer, String pattern)
    buffer.append('\'');
    XhtmlUtils.escapeJS(buffer, pattern);
    buffer.append('\'');
    private static String _getEscapedPattern(StringBuilder buffer, String pattern, String secondaryPattern)
    if (secondaryPattern != null)
    buffer.append('[');
    _escapePattern(buffer, pattern);
    if (secondaryPattern != null)
    buffer.append(",'");
    XhtmlUtils.escapeJS(buffer, secondaryPattern);
    buffer.append("']");
    return buffer.toString();
    private String _getHint()
    String type = getType();
    if (type.equals("date"))
    return getHintDate();
    else if (type.equals("both"))
    return getHintBoth();
    else
    return getHintTime();
    public static Object resolveExpression(String pExpression)
    FacesContext facesContext = FacesContext.getCurrentInstance();
    Application app = facesContext.getApplication();
    ExpressionFactory elFactory = app.getExpressionFactory();
    ELContext elContext = facesContext.getELContext();
    ValueExpression valueExp = null;
    valueExp = elFactory.createValueExpression(elContext, pExpression, Object.class);
    return valueExp.getValue(elContext);
    private static final String _NO_JS_PATTERN = new String();
    private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(DateTimeConverter.class);
    // RenderingContext key indicating the _dateFormat object
    // has been created
    private static final String _PATTERN_WRITTEN_KEY = "org.apache.myfaces.trinidadinternal.convert.DateTimeConverter._PATTERN_WRITTEN";
    *Problem is if any input date componet is displaying other than current date then the date picker is always picking the current date rather existing date*
    Please suggest me where to make changes?
    Edited by: 858782 on Oct 3, 2011 7:43 AM
    Edited by: 858782 on Oct 3, 2011 11:44 PM

    I need custom date foramts to be applied for different inputDates which are not defined in <af:convertDateTime>
    Thanks
    Edited by: 858782 on Oct 13, 2011 4:59 PM

  • Is there a way to overload the Map's toString() function?

    Hello everyone. I was wondering if its possible to overload the toString() function of the Map datastructure supplied by java.
    I looked it up and it says:
    public class HashMapextends AbstractMapSo I looked up AbstractMap and it says:
    public abstract class AbstractMapextends Objectimplements MapAnd I found a toString() function in the AbstractMap saying:
    toString
    public String toString() Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object). This implementation creates an empty string buffer, appends a left brace, and iterates over the map's entrySet view, appending the string representation of each map.entry in turn. After appending each entry except the last, the string ", " is appended. Finally a right brace is appended. A string is obtained from the stringbuffer, and returned.
    here: http://java.sun.com/j2se/1.3/docs/a...ml#toString()So I did the following:
    package parse;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.io.*;
    //this class should store all the Messages or "Events" and
    //you can access them based on their EntityID key.
    public class MessageDB extends HashMap
         //database to hold the information
         //     holds the Alerts/messages
         public static Map<Integer, List<String>> AlertMap;
         //Constructor
         MessageDB()
              AlertMap = new HashMap<Integer, List<String>>();
         public String toString()
              return ( )//not sure what to put here...
         //print, outputs the contents of the hashMap
         public static void print()
            //want to print out the Key and all the Messages
              //associated with that key
              Set keys = AlertMap.keySet();          // The set of keys in the map.
              Iterator keyIter = keys.iterator();
              System.out.println("The map contains the following associations:");
              while (keyIter.hasNext()) {
                    Object key = keyIter.next();  // Get the next key.
                    Object value = AlertMap.get(key);  // Get the value for that key.
                    System.out.println( "EntityID: " + key + "\n"
                                  + "Message: " + value + "\n" );
         //overloaded print to print to user screen.
         public static void print(PrintWriter out)
              //want to print out the Key and all the Messages
              //associated with that key
              Set keys = AlertMap.keySet();          // The set of keys in the map.
              Iterator keyIter = keys.iterator();
              out.println("The map contains the following associations:");
              out.flush();
              while (keyIter.hasNext()) {
                    Object key = keyIter.next();  // Get the next key.
                    Object value = AlertMap.get(key);  // Get the value for that key.
                   //out.flush();
                   /* out.println( "   (" + key + "," + value + ")" );
                   out.flush();*/
                   // out.println("------------------\n");
                   out.println("EntityID: " + key + "\n"
                                  + "Message: " + value + "\n");
                   //out.println("------------------\n");
                   out.flush();
         void add(Message msg)
              //getting the position of the List by EntityID if avaiable
              List<String> Alert = AlertMap.get(msg.entityID);
              //checking to see if there is a unique Key already in the Map.
              if (Alert == null)
                   //if there isnt a key in the map, add a new key, and a new List mapping
                   //to the key EntityID;
                     Alert = new ArrayList<String>();
                     AlertMap.put(msg.entityID, Alert);
                     Alert.add(msg.message);
              else
              //adding message to List
                   Alert.add(msg.message);
    }Right now the output is like this:
    The map contains the following associations:
    EntityID: 99999
                      Message: [a test ]
    EntityID: 800
                    Message: [this is a test , again a test ]
    EntityID: 801
                    Message: [again a test ]
    EntityID: 111
                    Message: [a test again yes , a test once again ]You see how its automatically doing [message1, message2,...,message x]
    By me calling this line of code:
    out.println("EntityID: " + key + "\n"
                                  + "Message: " + value + "\n");Because I found out it implicity calls the toString() method when concatinating it to a string.
    What I would like it to display would be:
    EntityID: 800
    Message:
    This is a test
    This is a test again
    any ideas would be great!
    Or is there a way to just iterate over the messages, rather than doing it my way?
    Message was edited by:
    lokie

    Hi,
    When you do a String concatenation in java, calls are implicitly done to #toString().
    Means, you are doing this:
    while (keyIter.hasNext()) {
                    Object key = keyIter.next();  /
                    Object value = AlertMap.get(key); 
                    System.out.println( "EntityID: " + key.toString()+ "\n"
                                  + "Message: " + value.toString() + "\n" );
    }The "[ [/b]... [b], ... , ... ]" you can see in your output is created by the implicit call to List#toString() method.
    You can Override it in an anonymous class by doing:
    if (Alert == null)
                   //if there isnt a key in the map, add a new key, and a new List mapping
                   //to the key EntityID;
                     Alert = new ArrayList<String>(){
                              @Override
                               public String toString(){
                                StringBuilder sb = new StringBuilder();
                       for(String s: this){
                        sb.append(s);
                        sb.append("\n");
                               return sb.toString();
                             };PS:
    toString() is usually used for debbuging only...

  • IKM file to file (java) error

    Hi Team,
    I am using IKM file to file (java) to laod the data and am getting the following error at compile step. Please help me out here.
    com.sunopsis.tools.core.exception.SnpsSimpleMessageException: ODI-17517: Error during task interpretation.
    Task: 2
    java.lang.Exception: BeanShell script error: Sourced file: inline evaluation of: ``out.print("OdiOutFile \"-FILE=") ; out.print(snpRef.getSchemaName("CT_Sample", " . . . '' : Unary operation "+" inappropriate for object : at Line: 178 : in file: inline evaluation of: `` /* This function is used to replace at code generation time the column names in . . . '' : + ");" ) ;
    BSF info: Create transformer at line: 0 column: columnNo
    at com.sunopsis.dwg.codeinterpretor.SnpCodeInterpretor.transform(SnpCodeInterpretor.java:485)
    at com.sunopsis.dwg.dbobj.SnpSessStep.createTaskLogs(SnpSessStep.java:711)
    at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java:461)
    at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java:2093)
    at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor$2.doAction(StartSessRequestProcessor.java:366)
    at oracle.odi.core.persistence.dwgobject.DwgObjectTemplate.execute(DwgObjectTemplate.java:216)
    at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor.doProcessStartSessTask(StartSessRequestProcessor.java:300)
    at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor.access$0(StartSessRequestProcessor.java:292)
    at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor$StartSessTask.doExecute(StartSessRequestProcessor.java:855)
    at oracle.odi.runtime.agent.processor.task.AgentTask.execute(AgentTask.java:126)
    at oracle.odi.runtime.agent.support.DefaultAgentTaskExecutor$2.run(DefaultAgentTaskExecutor.java:82)
    at java.lang.Thread.run(Thread.java:662)
    Caused by: org.apache.bsf.BSFException: BeanShell script error: Sourced file: inline evaluation of: ``out.print("OdiOutFile \"-FILE=") ; out.print(snpRef.getSchemaName("CT_Sample", " . . . '' : Unary operation "+" inappropriate for object : at Line: 178 : in file: inline evaluation of: `` /* This function is used to replace at code generation time the column names in . . . '' : + ");" ) ;
    BSF info: Create transformer at line: 0 column: columnNo
    at bsh.util.BeanShellBSFEngine.eval(Unknown Source)
    at bsh.util.BeanShellBSFEngine.exec(Unknown Source)
    at com.sunopsis.dwg.codeinterpretor.SnpCodeInterpretor.transform(SnpCodeInterpretor.java:471)
    ... 11 more
    Text: OdiOutFile "-FILE=<?=snpRef.getSchemaName("CT_Sample", "W") ?>/<?= getOdiClassName() ?>.java"
    import java.io.BufferedWriter;
    import java.io.BufferedReader;
    import java.io.Reader;
    import java.io.FileReader;
    import java.io.FileInputStream;
    import java.io.InputStreamReader;
    import java.io.FileOutputStream;
    import java.io.OutputStreamWriter;
    import java.io.FileWriter;
    import java.io.File;
    import java.io.IOException;
    import java.io.FilenameFilter;
    import java.util.Scanner;
    import java.util.HashMap;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    import java.lang.String;
    import java.lang.StringBuilder;
    import java.lang.RuntimeException;
    import java.text.ParseException;
    import java.text.ParsePosition;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.text.DecimalFormat;
    import java.text.DecimalFormatSymbols;
    import java.math.BigDecimal;
    public class <?= getOdiClassName() ?> {
    /* Number of threads that are to be run in parallel */
    static int NB_THREADS = 1;
      BufferedWriter pBufferedWriter;
    BufferedWriter pBufferedLogWriter;
    BufferedWriter pBufferedBadWriter;
    int nbError;
    int nbErrorInPrevFiles;
    int nbLine;
    int nbTotalLine;
    int nbWarning;
    int nbFiles;
    int nbFilter;
    int nbFilterInPrevFiles;
    int nbHeader;
    int nbInserted;
    boolean doWeContinueBatch = true;
    boolean maxErrorReach = false;
    //boolean warning = false;
    //String warning_txt ="";
    Date debut = new Date();
    Date end =  new Date();
    static int maxError=0;
      * @param pBufferedWriter
      * @param pBufferedLogWriter
      * @param pBufferedBadWriter
      * @param nbError
      * @param nbLine
      * @throws IOException
    public <?= getOdiClassName() ?>(String targF,String logF,String badF) throws IOException {
      super();
      this.pBufferedWriter = new BufferedWriter(new FileWriter(targF, false));
      this.pBufferedLogWriter = new BufferedWriter(new FileWriter(logF, false ));
      this.pBufferedBadWriter = new BufferedWriter(new FileWriter(badF, false )); 
      pBufferedLogWriter.append("Oracle Data Integrator * File to File:\nCopyright (c) Oracle Corporation.  All rights reserved.");
      pBufferedLogWriter.append("\n\nNumber of threads: "+NB_THREADS);
      pBufferedLogWriter.append("\n\nDiscardmax: 1");
      pBufferedLogWriter.append("\n\nOutputFile:\t\t"+targF+"\nBAD file:\t\t"+badF+"\n");
      this.nbError = 0;
      this.nbErrorInPrevFiles = 0;
      this.nbLine = 0;
      this.nbTotalLine=0;
      this.nbWarning=0;
      this.nbFiles=0;
      this.nbHeader=0;
      this.nbFilter=0;
      this.nbFilterInPrevFiles = 0;
      this.nbInserted=0;
    /* A simple object used to synchronize the reads of the source file and avoid overlap between the various threads */
    static Object lock = new Object();
    HashMap<Object, BigDecimal> sequenceMap = new HashMap<Object, BigDecimal>();
    HashMap<Object, BigDecimal> counterMap = new HashMap<Object, BigDecimal>();;
    public boolean getDoWeContinueBatch()
      return doWeContinueBatch;
    public void addInserted()
      synchronized(lock) {
       nbInserted+=1;
    public void addWarning()
      synchronized(lock) {
       nbWarning+=1;
    public void addFilter()
      synchronized(lock) {
       nbFilter+=1;
    public BigDecimal getCounter(Object pFieldValue, long pStartValue) {
      if (counterMap.containsKey(pFieldValue)) {
       return counterMap.get(pFieldValue);
      } else {
       counterMap.put(pFieldValue, new BigDecimal(pStartValue));
       return counterMap.get(pFieldValue);
    public BigDecimal incrementCounter(Object pFieldValue, long pStartValue) {
      if (counterMap.containsKey(pFieldValue)) {
       counterMap.put(pFieldValue, counterMap.get(pFieldValue).add(BigDecimal.ONE));
       return counterMap.get(pFieldValue);
      } else {
       counterMap.put(pFieldValue, new BigDecimal(pStartValue));
       return counterMap.get(pFieldValue);
    public BigDecimal smartSequence(Object pField, Object pValue, long pStartValue) {
      if (pField.equals(pValue)) {
       return incrementCounter(pValue, pStartValue);
      } else {
       return getCounter(pValue, pStartValue);
    public BigDecimal smartSequence(Object pField, Object pValue) {
      return smartSequence(pField, pValue, 0);
    public BigDecimal normalSequence(Object pSequenceName, long pStartValue) {
      if (sequenceMap.containsKey(pSequenceName)) {
       synchronized(sequenceMap.get(pSequenceName)) {
        sequenceMap.put(pSequenceName, sequenceMap.get(pSequenceName).add(BigDecimal.ONE));
        return sequenceMap.get(pSequenceName);
      } else {
       synchronized (sequenceMap) {
        sequenceMap.put(pSequenceName, new BigDecimal(pStartValue));
        return sequenceMap.get(pSequenceName);
    public BigDecimal normalSequence(Object pSequenceName) {
      return normalSequence(pSequenceName, 0);
    /* Utility class used for String processing */
    class OdiStringUtils {
      /* This method is used to write Input String into the StringBuilder that contains the target row and pad with spaces if necessary */
      public void pad(StringBuilder pStringBuilder, String pString, int pLength) {
       pStringBuilder.append(pString);
       for (int i=0;i<pLength-pString.length();i++) {
        pStringBuilder.append(' ');
    /* This class is the formatter for Strings that are to be written to the target file */
    class OdiStringFormatOUT{
      OdiStringUtils myStringUtils;
      String colName;
      String colMandatory;
      String colFormat;
      String colDecSep;
      String colNullIfErr;
      int    colBytes;
      String xString;
      private void check(Warning Odiwarn) throws Exception
       if (xString.length() > colBytes)
        {if (colNullIfErr=="0"){
         throw new Exception ("Column "+ colName+" : "+xString+" Value too long\n");
         if (colNullIfErr=="1")
          Odiwarn.AddWarn("Column "+ colName+" : "+xString+" Value too long\n");
         xString="";
         return;  
        if (xString.length() ==0)
        {if (colNullIfErr=="0"){
         throw new Exception ("Column "+ colName+" : is mandatory\n");
         if (colNullIfErr=="1")
          Odiwarn.AddWarn("Column "+ colName+" : is mandatory\n");
      public OdiStringFormatOUT(String pColName,String pColMandatory, String pColFormat,String pColDecSep, String pColNullIfErr,int pColBytes, OdiStringUtils pStringUtils) {
       myStringUtils = pStringUtils;
       colName = pColName;
       colMandatory = pColMandatory;
       colFormat = pColFormat;
       colDecSep = pColDecSep;
       colNullIfErr = pColNullIfErr;
       colBytes = pColBytes;
      public void format(String pString, StringBuilder pStringBuilder,Warning Odiwarn) throws Exception {
       xString=pString;
       this.check(Odiwarn);
       pStringBuilder.append(xString);
    /* This class is the formatter for Strings that are to be read from the source file */
    class OdiStringFormatIN{
      OdiStringUtils myStringUtils;
      String odiColname;
      String colNullIfErr;
      public OdiStringFormatIN(OdiStringUtils pStringUtils, String pColname, String pColNullIfErr) {
       myStringUtils = pStringUtils;
       odiColname=pColname;
       colNullIfErr=pColNullIfErr;
      public String parse(String pString,Warning Odiwarn) {
       return pString;
    /* This class is the formatter for Numbers that are to be written to the target file.
    Note that some more format() functions should be added to fully support all the possible datatypes (int, etc.) */
    class OdiNumberFormatOUT{
      OdiStringUtils myStringUtils;
      DecimalFormat internalParser;
      String colName;
      String colMandatory;
      String colFormat;
      String colDecSep;
      String colNullIfErr;
      int    colBytes;
      private void check(Number pNumber,Warning Odiwarn) throws Exception
       if (pNumber == null && colMandatory=="1" )
        {if (colNullIfErr=="0"){
         throw new Exception ("Column "+ colName+" is  mandatory\n");
         if (colNullIfErr=="1")
          Odiwarn.AddWarn("Column "+ colName+" is  mandatory\n");
       private void check(double pDouble,Warning Odiwarn) throws Exception
       if (false)
        {if (colNullIfErr=="0"){
         throw new Exception ("Column "+ colName+" : "+pDouble+" Value too long\n");
         if (colNullIfErr=="1")
          Odiwarn.AddWarn("Column "+ colName+" : "+pDouble+" Value too long\n");
       private void check(long pLong,Warning Odiwarn) throws Exception
       if (false)
        {if (colNullIfErr=="0"){
         throw new Exception ("Column "+ colName+" : "+pLong+" Value too long\n");
         if (colNullIfErr=="1")
          Odiwarn.AddWarn("Column "+ colName+" : "+pLong+" Value too long\n");
      public OdiNumberFormatOUT(String pColName,String pColMandatory, String pColFormat,String pColDecSep, String pColNullIfErr,int pColBytes, OdiStringUtils pStringUtils) {
       myStringUtils = pStringUtils;
       colName = pColName;
       colMandatory = pColMandatory;
       colFormat = pColFormat;
       colDecSep = pColDecSep;
       colNullIfErr = pColNullIfErr;
       colBytes = pColBytes;
       if (colDecSep == null) {
        colDecSep = ".";
       if (colDecSep.length() != 1) {
        colDecSep = ".";
       DecimalFormatSymbols mySymbols = new DecimalFormatSymbols();
       mySymbols.setDecimalSeparator(colDecSep.charAt(0));
       internalParser = new DecimalFormat("#.#", mySymbols);
       internalParser.setParseBigDecimal(true);
      public void format(Number pNumber, StringBuilder pStringBuilder,Warning Odiwarn) throws Exception {
       this.check(pNumber,Odiwarn);
       if (pNumber == null) {
        return;
       pStringBuilder.append(internalParser.format(pNumber));
      public void format(double pDouble, StringBuilder pStringBuilder,Warning Odiwarn) throws Exception {
       this.check(pDouble,Odiwarn);
       pStringBuilder.append(internalParser.format(pDouble));
      public void format(long pLong, StringBuilder pStringBuilder,Warning Odiwarn) throws Exception {
       this.check(pLong,Odiwarn);
       pStringBuilder.append(internalParser.format(pLong));
    /* This class is the formatter for Numbers that are to be read from the source file. */
    class OdiNumberFormatIN{
      OdiStringUtils myStringUtils;
      DecimalFormat internalParser;
      ParsePosition internalParsePosition;
      String odiColname;
      String colNullIfErr;
      public OdiNumberFormatIN(String pDecimalSeparator, OdiStringUtils pStringUtils, String pColname, String pColNullIfErr) {
       myStringUtils = pStringUtils;
       odiColname=pColname;
       colNullIfErr=pColNullIfErr;
       if (pDecimalSeparator == null) {
        pDecimalSeparator = ".";
       if (pDecimalSeparator.length() != 1) {
        pDecimalSeparator = ".";
       DecimalFormatSymbols mySymbols = new DecimalFormatSymbols();
       mySymbols.setDecimalSeparator(pDecimalSeparator.charAt(0));
       internalParser = new DecimalFormat("#.#", mySymbols);
       internalParser.setParseBigDecimal(true);
       internalParsePosition = new ParsePosition(0);
      /* This function returns null in case an Exception occurs during the parsing of the String as a Number */
      public Number parse(String pString, Warning Odiwarn) throws Exception {
       internalParsePosition.setIndex(0);
       Number x= internalParser.parse(pString.trim(), internalParsePosition);
       if ((pString.trim().length()>internalParsePosition.getIndex()))
       { x=null;
        if (colNullIfErr=="0"){
        throw new Exception (odiColname+" "+pString.trim()+" Invalid number\n");
        if (colNullIfErr=="1")
         Odiwarn.AddWarn(odiColname+": "+pString.trim()+" Invalid number");
       return x;
    /* This class is the formatter for Dates that are to be read from the source file */
    class OdiDateFormatIN{
      OdiStringUtils myStringUtils;
      SimpleDateFormat internalParser;
      ParsePosition internalParsePosition;
      String odiColname;
      String colNullIfErr;
      String localPattern="";
      public OdiDateFormatIN(String pPattern, OdiStringUtils pStringUtils, String pColname, String pColNullIfErr) {
       myStringUtils = pStringUtils;
       odiColname = pColname;
       colNullIfErr=pColNullIfErr;
       if (pPattern == null) {
        localPattern = "dd/MM/yyyy";
       } else localPattern=pPattern;
       //internalParser = new SimpleDateFormat(pPattern);
       //internalParsePosition = new ParsePosition(0);
      /* This method returns null if an error occurs when parsing the String as a date */
      public Date parse(String pString, Warning Odiwarn) throws Exception {
       internalParser = new SimpleDateFormat(localPattern);
       internalParsePosition = new ParsePosition(0);
       internalParsePosition.setIndex(0);
       internalParser.setLenient(false);
       Date x= internalParser.parse(pString.trim(),internalParsePosition);
       //trace("this is bad file");
       if (internalParsePosition.getErrorIndex() > -1 && pString.length()>0 )
       { x=null;
        if (colNullIfErr=="1") {
         Odiwarn.AddWarn(odiColname+": "+pString.trim()+" Invalid date");
        if (colNullIfErr=="0") {
        throw new Exception (odiColname+" "+pString.trim()+" Invalid date\n");
       return x;
    /* This class is the formatter for Dates that are to be written to the target file */
    class OdiDateFormatOUT{
      OdiStringUtils myStringUtils;
      SimpleDateFormat internalParser;
      String colName;
      String colMandatory;
      String colFormat;
      String colDecSep;
      String colNullIfErr;
      int    colBytes;
      Date xDate;
       private void check(Warning Odiwarn) throws Exception
       if (false)
        {if (colNullIfErr=="0"){
         throw new Exception ("Column "+ colName+" : "+xDate+" Value too long\n");
         if (colNullIfErr=="1")
          Odiwarn.AddWarn("Column "+ colName+" : "+xDate+" Value too long\n");
      public OdiDateFormatOUT(String pColName,String pColMandatory, String pColFormat,String pColDecSep, String pColNullIfErr,OdiStringUtils pStringUtils)
       myStringUtils = pStringUtils;
       colName = pColName;
       colMandatory = pColMandatory;
       colFormat = pColFormat;
       colDecSep = pColDecSep;
       colNullIfErr = pColNullIfErr;
       colBytes = 0;
       if (colFormat == null) {
        colFormat = "dd/MM/yyyy";
       internalParser = new SimpleDateFormat(colFormat);
      public void format(Date pDate, StringBuilder pStringBuilder,Warning Odiwarn) throws Exception {
       xDate=pDate;
       this.check(Odiwarn);
       if (xDate != null) {
        pStringBuilder.append(internalParser.format(xDate));
    class Warning
    boolean warning;
    String warntext;
    int currentLine;
    int nbWarn;
    public Warning ()
      warning=false;
      warntext="";
    public void New (int i)
      warning=false;
      warntext="";
      currentLine=i;
      nbWarn=0;
    public void AddWarn (String txt)
        if (warning) {
        warntext=warntext+"\n"+txt;
         } else {
        warntext=warntext+"\n"+txt;
      warning=true;
      nbWarn+=1;
    /* This class contains the code of the Thread that reads a line from the source file, processes a line and writes the output to the Target */
    class OdiFileTransformer extends Thread {
      OdiStringUtils myStringUtils= new OdiStringUtils();
      Scanner myScanner;
      Warning Odiwarn=new Warning();
      <?
        createInputFormaters();
        createOutputFormaters();
      ?>
      String tmpString;
       String[] srcCols;
      <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C1;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C2;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C3;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C4;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C5;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C6;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C7;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C8;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C9;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C10;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C11;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C12;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C13;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C14;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C15;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C16;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C17;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C18;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C19;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C20;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C21;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C22;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C23;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C24;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C25;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C26;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C27;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C28;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C29;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C30;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C31;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C32;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C33;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C34;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C35;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C36;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C37;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C38;
       <? if ("DATE".equals("STRING")) {?>Date<? } else if ("NUMERIC".equals("STRING")) {?>Number<? } else { ?>String<? } ?> srcColsCTCL_C39;
      String srcRecordSeparator;
      String trgRecordSeparator;
      String trgLineSeparator;
      StringBuilder myStringBuilder;
      public OdiFileTransformer(Scanner pScanner){
       super();
       myScanner = pScanner;
       tmpString = null;
       this.setName("OdiFileTransformer");
        srcCols = new String[1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1];
       srcRecordSeparator = Pattern.quote(",");
       trgRecordSeparator = ",";
       trgLineSeparator = "\n";
       myStringBuilder = new StringBuilder();
      public void run() {
      boolean bad = false;
      try {
       while (doWeContinueBatch){
        /* The calls to the Scanner need to be synchronized manually as it is not threadsafe */
        synchronized(lock) {
         if (myScanner.hasNext()) {
          tmpString=myScanner.next();
          nbLine+=1;
         } else {
          return;
        bad = false;
        Odiwarn.New(nbLine);
        try {
        srcCols = tmpString.split(srcRecordSeparator);
        /* The Filters are generated as if Statements that go to the next row to process if any condition is false */
        /* We start the processing of the line by clearing the StringBuilder */
        myStringBuilder.setLength(0);
        <? createInputFormaters("CTCL.C1"); ?><? createInputFormaters("CTCL.C2"); ?><? createInputFormaters("CTCL.C3"); ?><? createInputFormaters("CTCL.C4"); ?><? createInputFormaters("CTCL.C5"); ?><? createInputFormaters("CTCL.C6"); ?><? createInputFormaters("CTCL.C7"); ?><? createInputFormaters("CTCL.C8"); ?><? createInputFormaters("CTCL.C9"); ?><? createInputFormaters("CTCL.C10"); ?><? createInputFormaters("CTCL.C11"); ?><? createInputFormaters("CTCL.C12"); ?><? createInputFormaters("CTCL.C13"); ?><? createInputFormaters("CTCL.C14"); ?><? createInputFormaters("CTCL.C15"); ?><? createInputFormaters("CTCL.C16"); ?><? createInputFormaters("CTCL.C17"); ?><? createInputFormaters("CTCL.C18"); ?><? createInputFormaters("CTCL.C19"); ?><? createInputFormaters("CTCL.C20"); ?><? createInputFormaters("CTCL.C21"); ?><? createInputFormaters("CTCL.C22"); ?><? createInputFormaters("CTCL.C23"); ?><? createInputFormaters("CTCL.C24"); ?><? createInputFormaters("CTCL.C25"); ?><? createInputFormaters("CTCL.C26"); ?><? createInputFormaters("CTCL.C27"); ?><? createInputFormaters("CTCL.C28"); ?><? createInputFormaters("CTCL.C29"); ?><? createInputFormaters("CTCL.C30"); ?><? createInputFormaters("CTCL.C31"); ?><? createInputFormaters("CTCL.C32"); ?><? createInputFormaters("CTCL.C33"); ?><? createInputFormaters("CTCL.C34"); ?><? createInputFormaters("CTCL.C35"); ?><? createInputFormaters("CTCL.C36"); ?><? createInputFormaters("CTCL.C37"); ?><? createInputFormaters("CTCL.C38"); ?><? createInputFormaters("CTCL.C39"); ?>
        <?= replaceMappings("outC1Formatter.format(CTCL.C1,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC2Formatter.format(CTCL.C2,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC3Formatter.format(CTCL.C3,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC4Formatter.format(CTCL.C4,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC5Formatter.format(CTCL.C5,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC6Formatter.format(CTCL.C6,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC7Formatter.format(CTCL.C7,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC8Formatter.format(CTCL.C8,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC9Formatter.format(CTCL.C9,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC10Formatter.format(CTCL.C10,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC11Formatter.format(CTCL.C11,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC12Formatter.format(CTCL.C12,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC13Formatter.format(CTCL.C13,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC14Formatter.format(CTCL.C14,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC15Formatter.format(CTCL.C15,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC16Formatter.format(CTCL.C16,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC17Formatter.format(CTCL.C17,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC18Formatter.format(CTCL.C18,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC19Formatter.format(CTCL.C19,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC20Formatter.format(CTCL.C20,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC21Formatter.format(CTCL.C21,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC22Formatter.format(CTCL.C22,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC23Formatter.format(CTCL.C23,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC24Formatter.format(CTCL.C24,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC25Formatter.format(CTCL.C25,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC26Formatter.format(CTCL.C26,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC27Formatter.format(CTCL.C27,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC28Formatter.format(CTCL.C28,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC29Formatter.format(CTCL.C29,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC30Formatter.format(CTCL.C30,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC31Formatter.format(CTCL.C31,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC32Formatter.format(CTCL.C32,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC33Formatter.format(CTCL.C33,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC34Formatter.format(CTCL.C34,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC35Formatter.format(CTCL.C35,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC36Formatter.format(CTCL.C36,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC37Formatter.format(CTCL.C37,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC38Formatter.format(CTCL.C38,myStringBuilder,Odiwarn);") ?><?= "myStringBuilder.append(trgRecordSeparator);" ?><?= replaceMappings("outC39Formatter.format(CTCL.C39,myStringBuilder,Odiwarn);") ?>
        myStringBuilder.append(trgLineSeparator);
        pBufferedWriter.write(myStringBuilder.toString());
        if (Odiwarn.warning)
         pBufferedLogWriter.append("\nwarning line: "+Odiwarn.currentLine+"\t"+Odiwarn.warntext);
         addWarning();
        addInserted();
        catch (Exception e) {
         // TODO: handle exception
         pBufferedLogWriter.append("\nError line: "+nbLine+"\t"+e.getMessage());
         e.printStackTrace();
         pBufferedBadWriter.append(tmpString+"\n");
         synchronized(lock) {
          nbError+=1;
          if (nbError >=1)
           {pBufferedLogWriter.append("Maximum number of errors reached \n");
              doWeContinueBatch=false;
              maxErrorReach=true;
           return;}
      catch (Exception e) {
       throw(new RuntimeException(e.getMessage()));
    static class OdiFileFilter implements FilenameFilter {
      Pattern myPattern;
      BufferedWriter myLogWriter;
      public OdiFileFilter (String pPattern,BufferedWriter logWriter) throws IOException {
       File pWorkSchema = new File("<?=snpRef.getSchemaName("CT_Sample", "D") ?>");
       StringBuilder buffer = new StringBuilder();
       pPattern = pWorkSchema.getAbsolutePath().replace("\\", "/") + "/" + pPattern;
       myLogWriter=logWriter;
       char[] chars = pPattern.toCharArray();
       for (int i = 0; i < chars.length; ++i)    {
        buffer.append(chars[i]);
       myPattern = Pattern.compile(buffer.toString());
       myLogWriter.append("\nPattern: " + buffer.toString());
      public boolean accept(File pDir, String pName) {
       Matcher myMatcher = myPattern.matcher(pDir.getAbsolutePath().replace("\\", "/") + "/" + pName);
       System.out.println("" + myMatcher.matches() + pDir.getAbsolutePath().replace("\\", "/") + "/" + pName);
       return myMatcher.matches();
    public static void main(String[] args) throws Exception{
      LOG_FILE =
      BAD_FILE =
       String wbadfile = "<?=snpRef.getObjectName("L", "FILE_OK.csv", "CT_Sample", "", "D") ?>.bad";
       String wlogfile = "<?=snpRef.getObjectName("L", "FILE_OK.csv", "CT_Sample", "", "D") ?>.log";
      <?= getOdiClassName() ?> myIKMFileProcessing = new <?= getOdiClassName() ?>("<?=snpRef.getObjectName("L", "FILE_OK.csv", "CT_Sample", "", "D") ?>",wlogfile,wbadfile);
      File[] inputFileList;
      OdiFileFilter myFileFilter = new OdiFileFilter("<?=snpRef.getObjectShortName("L", "Pfizer_Regional_CT_costs_Aug2013_AP.csv", "CT_Sample", "D") ?>",myIKMFileProcessing.pBufferedLogWriter);
      File inputDir = new File("<?=snpRef.getSchemaName("CT_Sample", "D") ?>");
      inputFileList = inputDir.listFiles(myFileFilter);
      String s="";
      if (inputFileList.length==0) {myIKMFileProcessing.pBufferedLogWriter.append("\n\tError : Source file does not exist");}
      for (int i=0;i<inputFileList.length;i++) {
       if (myIKMFileProcessing.getDoWeContinueBatch()) {
       s=myIKMFileProcessing.processInputFile(inputFileList[i]);
      myIKMFileProcessing.pBufferedLogWriter.append(s);
      myIKMFileProcessing.pBufferedLogWriter.flush();
    public String processInputFile(File pInputFile) throws Exception {
      /* We open the source File by taking the encoder into account if needed */
       Scanner myScanner = new Scanner(new BufferedReader(new FileReader(pInputFile)));
        pBufferedLogWriter.append("\nInput file:\t\t"+pInputFile.getAbsolutePath().replace("\\", "/"));
      /* We use a Scanner as the record separator might not necessarily be \n */
      myScanner.useDelimiter("\n");
      /* We read the first lines in order to ignore them depending on the setting of the source datastore */
      for (int i=0;i < 0;i++){
       if (myScanner.hasNext()) {
        myScanner.next();
        nbLine+=1;
        nbHeader+=1;
      OdiFileTransformer[] odiFileTransformers = new OdiFileTransformer[NB_THREADS];
      for (int i=0;i<NB_THREADS;i++){
       odiFileTransformers[i] = new OdiFileTransformer(myScanner );
      for (int i=0;i<NB_THREADS;i++){
       odiFileTransformers[i].start();
      for (int i=0;i<NB_THREADS;i++){
       odiFileTransformers[i].join();
      end=new Date();
        if (maxErrorReach)
        pBufferedLogWriter.append("\n\tNumber of lines read for this file:\t\t" + nbLine);
        pBufferedLogWriter.append("\n\tNumber of data lines read for this file:\t\t" + (nbLine-1) + "\n\n\n");
        pBufferedLogWriter.append("\n\tNumber of error lines read for this file:\t\t" + (nbError-nbErrorInPrevFiles));
        pBufferedLogWriter.append("\n\tNumber of data lines read and filtered out for this file:\t\t" + (nbFilter-nbFilterInPrevFiles)+"\n");
      else
         pBufferedLogWriter.append("\n\tNumber of lines for this file:\t\t" + nbLine);
         pBufferedLogWriter.append("\n\tNumber of data lines for this file:\t\t" + (nbLine-1));
         pBufferedLogWriter.append("\n\tNumber of error lines for this file:\t\t" + (nbError-nbErrorInPrevFiles));
         pBufferedLogWriter.append("\n\tNumber of data lines filtered out for this file:\t\t" + (nbFilter-nbFilterInPrevFiles)+"\n");
        nbFiles+=1;
        nbTotalLine+=nbLine;
        nbErrorInPrevFiles = nbError;
        nbFilterInPrevFiles = nbFilter;
        nbLine=0;
        String s = "\n\n\n\n************************** TOTAL FIGURES ********************************";
        s = s + "\n\t"+nbFiles+" input file(s) processed.\n";
        s = s + "\n\t"+nbTotalLine+" Rows successfully read.\n" ;
        s = s +"\t"+nbHeader+" Rows skipped (Header).\n" ;
        s = s + "\t"+nbInserted+" Rows successfully loaded.\n" ;
        s = s +"\t\t==>"+nbWarning+" Rows loaded with warning.\n" ;
        s = s +"\t"+nbError+" Rows not loaded due to data errors.\n" ;
        s = s +"\t"+nbFilter+" Rows not loaded because of filter.\n" ;
        s = s + "\n\n\n";
        s = s + "\n\tRun began on "+debut;
        s = s + "\n\tRun ended on "+end;
        //long x=   ;
        s = s + "\n\tElapsed time was:\t"+Math.abs(end.getTime() - debut.getTime())+" milliseconde";
      /* We flush the buffer for any data that has not been written on the disk yet */
      pBufferedWriter.flush();
      pBufferedLogWriter.flush();
      pBufferedBadWriter.flush();
      return s;
    at com.sunopsis.dwg.dbobj.SnpSessStep.createTaskLogs(SnpSessStep.java:738)
    at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java:461)
    at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java:2093)
    at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor$2.doAction(StartSessRequestProcessor.java:366)
    at oracle.odi.core.persistence.dwgobject.DwgObjectTemplate.execute(DwgObjectTemplate.java:216)
    at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor.doProcessStartSessTask(StartSessRequestProcessor.java:300)
    at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor.access$0(StartSessRequestProcessor.java:292)
    at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor$StartSessTask.doExecute(StartSessRequestProcessor.java:855)
    at oracle.odi.runtime.agent.processor.task.AgentTask.execute(AgentTask.java:126)
    at oracle.odi.runtime.agent.support.DefaultAgentTaskExecutor$2.run(DefaultAgentTaskExecutor.java:82)
    at java.lang.Thread.run(Thread.java:662)

    This seems like a lot of code. I would suggest to compile your custom code outside of odi first to debug any syntax errors.

  • Error in getting the servlet response

    Below is my ErrorPage Servlet. Whenever a 404 page not found error is encountered, the error page servlet reads the 404.html, and writes the content to the response. But I am not able to see the content in IE, but works fine in mozilla.
    public class ErrorPageServlet extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String errorPath = request.getAttribute("javax.servlet.error.request_uri").toString();
            int statusCode = Integer.parseInt(request.getAttribute("javax.servlet.error.status_code")
                    .toString());
            String[] errorPathSegment = errorPath.split("/");
            String site = errorPathSegment[2];
            switch (statusCode) {
            case HttpServletResponse.SC_NOT_FOUND:
                writeOutFile(request, response, "/" + site + "/error/404.html");
                break;
            case HttpServletResponse.SC_INTERNAL_SERVER_ERROR:
            case HttpServletResponse.SC_NOT_IMPLEMENTED:
            case HttpServletResponse.SC_BAD_GATEWAY:
            case HttpServletResponse.SC_SERVICE_UNAVAILABLE:
            case HttpServletResponse.SC_GATEWAY_TIMEOUT:
            case HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED:
                writeOutFile(request, response, "/" + site + "/error/500.html");
                break;
        public void writeOutFile(HttpServletRequest request, HttpServletResponse response,
                String fileName) throws IOException {
            ServletContext context = request.getSession().getServletContext();
            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            InputStream resourceStream = context.getResourceAsStream(fileName);
            if (resourceStream != null) {
                InputStreamReader streamReader = new InputStreamReader(resourceStream);
                BufferedReader reader = new BufferedReader(streamReader);
                StringBuilder builder = new StringBuilder();
                for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                    builder.append(line);
                    builder.append('\n');
                writer.write(builder.toString());
                writer.flush();
            } else {
                log.info("Problem occurred with " + fileName);
                response.sendRedirect("/");
        }Also attached is my 404.html
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]">
    <html xmlns="[http://www.w3.org/1999/xhtml]">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="refresh" content="10;URL=/" >
    </head>
    <body>
    <h1>Error</h1>
    <p>A technical error has occurred. You will redirected in 10 seconds</p>
    </body>
    </html>

    Hi..
    Thanks for the comment.
    Below is how my web.xml entry looks like.
    The requirement is to send a 404 error response and that will be handled by a servlet which inturn writes the output to the response object.
         <servlet>
              <servlet-name>ErrorPageServlet</servlet-name>
              <servlet-class>com.test.ErrorPageServlet</servlet-class>
         </servlet>
         <servlet-mapping>
              <servlet-name>ErrorPageServlet</servlet-name>
              <url-pattern>/error</url-pattern>
         </servlet-mapping>
         <error-page>
              <error-code>404</error-code>
              <location>/error</location>
         </error-page>>>
    the first option to turn off the "show friendly html error pages" works fine.
    It would be better if I can get a different solution

  • Threads write and move files

    Hi,
    I'm trying to run the codes below with 200 threads using JMeter simulation (TCP connection). Here's my logic:
    - clients connect to a server, server accepts and creates new thread
    - the thread suppose to write the data into a file, but the file must be less than some size, in the case below is 200 bytes
    - when the 200 bytes size limit is reached, the thread needs to move that file into another folder and then create a new file for the data to be written
    - the writing data part is fine, but the moving data is not (many files aren't being moved)
    - i should also mention, i declared the fname to be static variable (to be shared by threads)
    So would anyone please help me like to give me advices if my codes below will work with the scenario above or if i need to approach the problem differently?
    Thanks
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    while((data = in.readLine()) != null) {
        socket.setSoTimeout(5000);
        // data should be in the form of this regex
        data = (data.replaceAll("[^0-9A-Za-z,.\\-#: ]", "")).trim();
        String [] result = data.split(",");
        if (result.length == 19) {
            if ((fname.trim()).equals("")) {
                DateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmssSSSS");
                Date date = new Date();
                fname = "log_"+dateFormat.format(date)+"_.txt";
            else {
                File outFile = new File("temp\\"+fname);
                //System.out.println("outFile.length(): " + outFile.length());
                // check if file is > filesize
                if (outFile.length() > 200) {
                    fdata = fname;
                    DateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmssSSSS");
                    Date date = new Date();
                    fname = "log_"+dateFormat.format(date)+"_.txt";                               
            synchronized (fname) {
                write(data);
                move(fdata);                           
    }Edited by: xpow on May 16, 2009 2:21 AM

    xpow wrote:
    i think 'SSSS' is fine, because it extends the 'SSS' which is a date placeholder. The files that I try to write to are logs file. I actually having trouble to write it, that's why i need to include the 'SSSS'.If you want each thread to have its own file, 'SSSS' may not be good enough. Java is extremely fast at creating objects, and you could easily have 10 threads competing to write to the same temp file. As I said above, if you don't want this, add the Thread ID to your filename. Remember, just because Java time fields allow milliseconds doesn't mean they provide that accuracy. The clock on my home computer actually ticks over about every 15ms.
    That's indeed one of the problem that I'm facing right now. I thought synchronization will take care of this problem.Only if all threads share the same object. As far as I can see, you are synchronizing on a filename created within the thread itself (I'm assuming your original fragment is part of the run() method) so the only synchronization you'd get would be from the I/O itself.
    Yes, I am aware of this fact too, once the code is decent, it'll be moved to unix systemEven so, make sure you clean up your files after you're done with them. It seems that this setup has the potential to create thousands of files, and even a Unix filesystem has its limits.
    My problem is that: there's a tcp server that listens to clients and receive that from it. The data needs to be inserted to the database. But with the volume of clients that connect to the server at the same time, I was thinking it's better to write it to temp file first (with filesize limitation), then to destination folder. There will be another process whose jobs is to parsing the files and move it into database. OK, so I presume each Thread is listening to output from a specific client, with a time limit for waiting (again, this isn't my forte, but I notice you have a 5 second timeout on the socket).
    A few other problems I see with your code:
    1. You've given each thread a limit of 200 bytes; on a decent size disk, the blocksize will be 4K (or even 8), which means that even if you write a file of 200 bytes, it will take up 4K on the disk.
    2. You create a new File and FileWriter object every time you write a chunk of data, which creates a lot of work for the garbage collector. Create them only when you need to open a new file and simply use them until you want to close it and move it. To facilitate this, pass Files between your methods, not names. In fact, for the write method, you can pass the FileWriter.
    3. The regex you use to filter your data includes "\\-#" which is not a valid range. It may well work, but it's always better to put '-' at the end of a metacharacter if it's not part of a range. Also, is a space (' ') the only valid space character you can receive? If, for example, the data could include tabs, you might be better off using '\s' (in the string you'll need "\\s").
    A few other suggestions (I'm assuming that all data read from a particular socket before a timeout comes from a single client):
    1. Make your size limit much bigger and a multiple of 1000 bytes (this should allow for any extra characters that may be added by the operating system). I'd suggest 4,000.
    2. Split the process of reading and writing into two separate threads. Disk I/O is, almost certainly, by far the slowest part of this process and therefore the most likely to block.
    One possibility for (2) is to append your validated data lines to a StringBuffer or StringBuilder and, when your size limit has been reached, copy the contents, pass the copy to a new writer thread, clear your buffer, and continue the process.
    The advantage of this is that your reader thread will only ever be blocked on input, and each writer thread will have a chunk of data that it knows it can put in one file (and probably directly into the 'inbox' directory).
    It still might not be a bad idea to have the "reader" thread create the filenames (don't forget to include the thread ID) and have it keep a "chunk" counter. The filename then becomes date/time plus reader-thread-ID plus chunk#, which ensures they will always be in sequence for your parser.
    Your code might then be something like:
    public class ReaderThread implements Runnable {
       private static final CHUNK_SIZE = 1000;
       private static final DateFormat dateFormat =
               new SimpleDateFormat("yyMMddHHmmssSSSS");
       private final String timeStamp =
               dateFormat.format(new Date());
       // Give your buffer enough extra capacity to complete a line.
       // (this'll just make it run a bit quicker)
       private Stringbuilder data_chunk = new StringBuilder(CHUNK_SIZE + 100);
       private int chunk_counter = 0;
       public void run() {
          // validate your lines as before, and inside your
          // 'if (result.length == 19)' block...
             data_chunk.append(data);
             if (data_chunk.length() >= CHUNK_SIZE)
                handoff(data_chunk);
          // remove all your filename stuff and the synchronized block
       // this is the method that hands off your data "chunk" to the writer thread
       private void handoff(StringBuilder chunk) {
          StringBuilder chunkCopy = new StringBuilder(chunk);
          String outfile = String.format("%s.%d.%7d",
                      timeStamp, this.getId(), ++chunk_count);
          WriterThread w = new WriterThread(chunkCopy, outfile);
          new Thread(w).start();
          chunk.delete(0, chunk.length());
    }This is just a possibility though, and there may be better ways to do it (such as communicating directly with your parser class via a Pipe).
    I'll leave it to you to write the WriterThread if you do decide to try it this way.
    HIH
    Winston

  • Dynamic update to TextArea?

    Heres a brief scenario
    Stage - Scene has 2 component -
    JTextArea - its text variable is binded to *'textAreaContent'*
    Button.
    On click of a button (onMouseClicked) - I am performing a FTP process - lets say that takes upto 10 seconds.
    during this FTP process - I constantly add log information to *'textAreaContent'* - which is expected to update JTextArea since it is binded.
    But JTextArea is only updated in one shot after completion of onMouseClicked method.
    but i want to show data in JTextArea everytime *'textAreaContent' is updated
    any ideas?

    I did resolve my issue after lots of hours of research.
    Just wanted to post this, if somebody has a better solution or someone might need this.
    Basically Event Dispatch Thread - EDT - was not letting me update any element in GUI dynamically. It would update at the end of the EDT process.
    After reading around few pages of threading in Swing - since javafx is like swing - a single threaded application. I bumped into SwingWorker.
    SwingWorker is used for any background process. And allows dynamic update to GUI element.
    Heres my TaskJava class which extends SwingWorker and is called from EDT
    EDT - onMouseClicked()
    var task = new UploadTask( textArea); - // Here a swing thread is spooned, but i am passing the instance of JTextAreaTaskJava
    package SwingWokerTask
    * @author Abhishek
    public class UploadTask extends SwingWorker<String, String> {
        private JTextArea textArea;
        // A calling application must pass a JTextArea
        public UploadTask(JTextArea textArea) {
            this.textArea = textArea;
        @Override
        protected String doInBackground() throws FTPException, IOException {
            publish("Getting Ready to upload files"); // public will invoke process - which will be update JtextArea
               Thread.sleep(1000);
                publish("Categories retrieved from Cache.");
               Thread.sleep(1000);
                publish("FTP Connection established");
               Thread.sleep(1000);
                publish("Entered incoming folder");
               Thread.sleep(1000);
                publish("--------------------------------");
               Thread.sleep(1000);
            return null;
        @Override
        protected void done() {
            if (isCancelled())
                publish("Cancelled !");
                else
            publish("Done !");
        @Override
        protected void process(List<String> strings) {
            StringBuilder strBuilder = new StringBuilder();
            for (String str : strings) {
                    strBuilder.append(str).append('\n');
            textArea.append(strBuilder.toString());
    }

  • ARRAYLIST comarision failing.

    Hi,
    I am expecting wen arraylist is null any of the cases then then other arraylist sud come in noMatchList.
    but now its is coming blank[].can u figure it out and solve..
    import java.util.ArrayList;
    import java.util.LinkedHashMap;
    import java.util.List;
    public class Demo3 {
    public static void main(String[] args) {
    ArrayList<String> al = new ArrayList<String>();
    al.add("1");al.add("2");al.add("3");al.add("4");al.add("6");
    ArrayList<String> a2 = new ArrayList<String>();
    // a2.add("1");a2.add("6");//a2.add("3");a2.add("4");a2.add("6");
    ArrayList<String> a3 = new ArrayList<String>();
    //a3.add("1");a3.add("2");a3.add("33");a3.add("44");a3.add("5");
    ArrayList<String> a4 = new ArrayList<String>();
    a4.add("1");a4.add("2");a4.add("33");a4.add("44");a4.add("5");
    ArrayList<String> a5 = new ArrayList<String>();
    a5.add("1");a5.add("2");a5.add("33");a5.add("44");a5.add("5");
    ArrayList<String> a6 = new ArrayList<String>();
    a6.add("1");a6.add("2");a6.add("3300");a6.add("44");a6.add("500");
    ArrayList<String> a8 = new ArrayList<String>();
    a8.add("1");a8.add("2");a8.add("33");a8.add("44");a8.add("51231111");
    ArrayList<String> a9 = new ArrayList<String>();
    a9.add("1");a9.add("2");a9.add("33");a9.add("44");a9.add("51231111");
    LinkedHashMap<String,ArrayList<String>> lhm = new LinkedHashMap<String,ArrayList<String>>();
    lhm.put("rule1", al);lhm.put("rule2", a2);lhm.put("rule3", a3);
    // lhm.put("rule4", a4);
    // lhm.put("rule5", a5);
    // lhm.put("rule6", a6); // lhm.put("rule9", a9);
    // lhm.put("rule8", a8);
    System.out.println("lhm value " + lhm);
    StringBuilder match = new StringBuilder();
    String[] a= new String[0];
    a = lhm.keySet().toArray(a);
    for(int i=0;i<a.length;i++){
    for(int j = 0;j<a.length -1;j++){
    if(j!= i){
    ArrayList<String> x1 = lhm.get(a);
    ArrayList<String> x2 = lhm.get(a[j]);
    if(x1.containsAll(x2) && x2.containsAll(x1) && !(x1.isEmpty() || x2.isEmpty())){
    if(!match.toString().contains(a[i])){
    match.append(a[i]+",");
    if(!match.toString().contains(a[j])){
    match.append(a[j]+",");
    match.append(":");
    StringBuilder noMatch = new StringBuilder();
    for(int i=0;i<a.length;i++){
    for(int j = 0;j!= i &&j<a.length -1;j++){
    ArrayList<String> x1 = lhm.get(a[i]);
    ArrayList<String> x2 = lhm.get(a[j]);
    if(!(x1.containsAll(x2) && x2.containsAll(x1))){
    if(!(x1.isEmpty() || x2.isEmpty())){
    if(!match.toString().contains(a[i]) && !noMatch.toString().contains(a[i])){
    noMatch.append(a[i]+",");
    if(!match.toString().contains(a[j]) && !noMatch.toString().contains(a[j])){
    noMatch.append(a[j]+",");
    //For Matched (Grouping done here)
    List<List<String>> matchList = spitTheString(match.toString());
    List<List<String>> noMatchList = spitTheString(noMatch.toString());
    private static List<List<String>> spitTheString(String match){
    String[] strings = match.toString().split(":");
    List<List<String>> finalList = new ArrayList<List<String>>();
    StringBuilder builder = null;
    for(String string:strings){
    String[] strings2 = string.split(",");
    builder = new StringBuilder();
    List<String> list = new ArrayList<String>();
    for(int i = 0;i < strings2.length;i++){
    if(strings2[i].length() != 0){
    builder.append(strings2[i]);
    if(i < strings2.length -1)
    builder.append(",");
    if(builder.length() != 0){
    list.add(builder.toString());
    finalList.add(list);
    return finalList;

    codingMonkey wrote:
    Please use code tags when posting code. You can do this using the CODE button above the forum editor. Few people will bother to read unformatted code.This time I did bother to read the unformatted code, specifically to learn a new language. However I am not entirely sure what the language I learnt is called, so lets call it "non-english".
    To the OP what exactly is the problem here? I have gone over your code and I notice a few things. Firstly you only add 3 ArrayList<String> into your map, one of which is non empty, the other two are empty. Secondly you have two sets of for loops, the first for loop appends matches, the second appends non matches. In both cases you will only add a match or a non match if in either situation both ArrayLists are non empty. Further more in the situation where 2/3 of your ArrayLists are empty, then no string will ever be built, because the conditional expression of empty in both cases is true > (!true) > false. This is why you have two empty StringBuilders if you even bothered to check.
    Mel

  • ClassNotFound (class is there in EAR file)

    I have an EAR file. It gives me ClassNotFound error even though I have checked
    that the class is there in the EAR at right place. This happens with one particular
    server. Same EAR file when deployed on another instance gives no problem.
    Can it happen if a class is fould at two different locations in classpath at runtime?
    Thanks in advance

    SquareBox wrote:
    user8483670 wrote:
    To handle String data like you said the one "Hello world" we can use string Buffer or StringBuilder for that purpose? why only String?I'm NOT 100% sure about this but I'm pretty sure. Anytime you create a String, the Java compiler uses StringBuilder.No, that's definitely not the case.
    Perhaps what you're thinking of is that when you concatenate non-compile-time-constant Strings, the compiler generates StringBuilder.append() calls.
    That is why when you want to use an array to create Strings for each element, it is better to explicitly call the StringBuilder because otherwise Java will create a new StringBuilder for every single element. In this case if you create a StringBuilder explicitly, then Java would only have to do it once rather than for each element of the array. This would slow down the program for large arrays.Sort of. Arrays don't specifically have anything to do with it. They're just one specific case. The real issue is when doing a lot of concatenations in a loop, you want to explicitly user StringBuilder, to avoid creating (and having to GC) large numbers of temporary String and StringBuilder objects.
    String s1 = "abc" + x "def" + y + "zzz";The above is fine, because the compiler can insert the creation of a single StringBuilder.
    String s1 = "";
    loop {
      s1 += something;
    }The above is not good, because for every pass through the loop, there will be a StringBuilder and a String created, and eligible for GC.
    StringBuilder sb = new StringBuilder();
    loop {
      sb.append(something);
    }The above is the preferred way to do it. Although in practice, in the majority of cases you probably won't even notice the difference.
    Edited by: jverd on Mar 8, 2011 9:44 AM

  • Time conversion...any other way of doing same thing?

    Class field: totalSeconds of type String;
    Method to convert String appropriate time display of format h/mm/ss
    Created a method, it works find, but since i'm new i was wondering whether there is slightly different maybe easier or smarter way of doing the same thing?
    Here's my method's code:
    StringBuilder timeDisplay = new StringBuilder("");
        //Converting String to int
        int totalTime = Integer.valueOf(trackDuration).intValue();
        int temp;
    /* HOURS *********************************/
        temp = (totalTime/3600);
        totalTime = (totalTime - (temp*3600));
                timeDisplay.append(temp+":");       
    /* MINUTES *********************************/
        temp = (totalTime/60);
        totalTime = (totalTime-(temp*60));
        if (temp < 10)
            timeDisplay.append("0"+temp+":");
        else
                timeDisplay.append(temp+":");       
    /* SECONDS *********************************/
        if (totalTime < 10)
                timeDisplay.append("0"+totalTime);
        else
                timeDisplay.append(totalTime);
        return timeDisplay.toString();
       

    c00ler wrote:
    Hey, thank you for the response atul, forgot to say that i'm not dealing with Time of the day, general time such as movie playing time.Time is represented internally as 1/1000 sec since a base time. Your durations can also measured this way, the only difference is that the base isn't Jan 1, 1970, it's whenever you started timing. So you can use SimpleDateFormat to format these values, as long as the duration is less than a year. You can also you a GregorianCalendar to take these values apart.

  • Unicode Text Extract

    It looks this problem is not uncommon... I have a PostScript file that is generated by a 3rd party product. Distiller converts it to PDF, but I cannot search or copy a text. It looks this is because the ToUnicode CMap information is not readily available. I created a very simple document that contains only A, B, C, 1 and 9 vertically and tried a few things, but none of them worked.
    Can somebody shed light on this to get it working?
    So far I tried the following lines in the CMap section of the PostScript file. I read the tech article - 5411 ToUnicode Mapping File and other Adobe references and manuals.
            5 begincidchar
            <0031> 20
            <001C> 28
            <0041> 36
            <0042> 37
            <0043> 38
            endcidchar
            5 beginbfchar
            <0014> <0031>
            <001C> <0039>
            <0024> <0041>
            <0025> <0042>
            <0026> <0043>
            endbfchar
            5 beginbfchar
            <14> <0031>
            <1C> <0039>
            <24> <0041>
            <25> <0042>
            <26> <0043>
            endbfchar
    Thank you for your help.
    * No attachement is possible in this forum(?)
    %!PS-Adobe-3.0
    %%Keywords: (atend)
    %%Subject: (atend)
    %%Title: (atend)
    %%Creator: Document Sciences DCPI Build {dcpi_BUILD_3.0SP1.48.124}
    %%Author: (atend)
    %%CreationDate: Wed Feb 09 09:04:42 NZDT 2011
    %%PageOrder: Ascend
    %%Pages: 2
    %%BoundingBox: 0 0 612 792
    %%Orientation: Portrait
    %%DocumentProcessColors: Black
    %%DocumentCustomColors:
    %%CMYKCustomColor:
    %%RGBCustomColor:
    %%EndComments
    %%BeginProlog
    %%BeginResource: definicoes
    %%EndResource
    /PslibDict 300 dict def PslibDict begin/N{def}def/B{bind def}N/eN{exch def}B
    /ForcePS true N
    /strcat{/str1 eN /str2 eN str1 length str2 length add string /str3 eN str3 0 str2 putinterval
    str3 str2 length str1 putinterval str3}N [/setvpsjobname where ForcePS not and
    {pop /VPS? true N
    /Concat {grestore endinline gsave systemdict /concat get exec}def}
    {/setvpsjobname
    {256 string cvs /VPSJobName eN}N
    /Concat {systemdict /concat get exec}def
    /startbooklet{pop}N /endbooklet{}N /VPS? false N /endelement{}N}ifelse
    cleartomark /ImgData {(ImgData_) ImgName strcat cvn}B /ImgForm {(ImgForm_) ImgName strcat cvn}B
    /EmitterForm{VPS? {EPS_INIT exch
    placeelement EPS_CLEANUP grestore PageBBoxDict defineinline gsave
    }{EPS_INIT exch /Form findresource execform EPS_CLEANUP}ifelse}B
    /BeginImgData{/img_size eN /img_ury eN /img_urx eN /img_lly eN /img_llx eN /ImgName eN
    <</BBox [img_llx img_lly img_urx img_ury] img_size 0 eq{/F (ImgForm_) ImgName strcat}
    {/Length img_size /EODCount img_size}ifelse /Flexible true /Type /Reusable >> VPS?{ImgForm exch defineelement}
    {ImgData exch currentfile exch /SubFileDecode filter /ReusableStreamDecode filter}ifelse}N
    /EndImageData{VPS?{endelement}{N <</FormType 1 /BBox [img_llx img_lly img_urx img_ury]/Matrix [1 0 0 1 0 0]
    /PaintProc {pop ImgData cvx exec 0 setfileposition ImgData cvx exec cvx exec}>> ImgForm exch
    /Form defineresource pop}ifelse}N
    /PageBBoxDict {<</BBox [0 0 currentpagedevice /PageSize get aload pop ] >>}B
    /Save {PslibDict /PageSave save put VPS? {PageBBoxDict defineinline}if}N
    /Restore {VPS?{endinline}if PslibDict /PageSave get restore}N
    /p{show}N/w{0 rmoveto}B/a{moveto}B/l{lineto}B/qs{currentpoint
    currentpoint newpath moveto 3 2 roll dup true charpath stroke
    stringwidth pop 3 2 roll add exch moveto}B/qf{currentpoint
    currentpoint newpath moveto 3 2 roll dup true charpath fill
    stringwidth pop 3 2 roll add exch moveto}B/qsf{currentpoint
    currentpoint newpath moveto 3 2 roll dup true charpath gsave stroke grestore fill
    stringwidth pop 3 2 roll add exch moveto}B/qc{currentpoint
    currentpoint newpath moveto 3 2 roll dup true charpath clip
    stringwidth pop 3 2 roll add exch moveto}B/qsc{currentpoint
    currentpoint initclip newpath moveto 3 2 roll dup true charpath clip stroke
    stringwidth pop 3 2 roll add exch moveto}B/qfc{currentpoint
    currentpoint initclip newpath moveto 3 2 roll dup true charpath clip fill
    stringwidth pop 3 2 roll add exch moveto}B/qfsc{currentpoint
    currentpoint initclip newpath moveto 3 2 roll dup true charpath gsave stroke grestore clip fill
    stringwidth pop 3 2 roll add exch moveto}B/qi{currentpoint
    3 2 roll
    stringwidth pop 3 2 roll add exch moveto}B/tr{currentpoint currentpoint 5 4 roll add moveto}B/rt{moveto}B
    /reencdict 12 dict def /ReEncode { reencdict begin
    /newcodesandnames exch def /newfontname exch def /basefontname exch def
    /basefontdict basefontname findfont def /newfont basefontdict maxlength dict def
    basefontdict { exch dup /FID ne { dup /Encoding eq
    { exch dup length array copy newfont 3 1 roll put }
    { exch newfont 3 1 roll put } ifelse } { pop pop } ifelse } forall
    newfont /FontName newfontname put newcodesandnames aload pop
    128 1 255 { newfont /Encoding get exch /.notdef put } for
    newcodesandnames length 2 idiv { newfont /Encoding get 3 1 roll put } repeat
    newfontname newfont definefont pop end } def
    /MarkerBegin{countdictstack 50464 mark}B
    /MarkerCleanup{stopped {(A Marker caused a PostScript error, continuing processing...) =}if
    {cleartomark dup 50464 eq{pop exit}if}loop countdictstack exch sub dup 0 gt{{end}repeat}{pop}ifelse}B
    /EPS_INIT{/EPS_SAVE save N gsave newpath 100 dict begin /DictStackDepth countdictstack N
    /showpage{}N/erasepage{}N/copypage{}N mark}B
    /EPS_CLEANUP{cleartomark DictStackDepth 1 dup countdictstack exch sub {end}for
    end grestore EPS_SAVE restore} B
    /setcustomcolor
    {exch aload pop pop 4 {4 index mul 4 1 roll} repeat
    5 -1 roll pop setcmykcolor} 1 index where {pop pop pop} {dup xcheck {bind} if N} ifelse
    /ccdef {5 packedarray def} B
    /cc {setcustomcolor} N
    /ds_ComposeFont
        1 index /CMap resourcestatus
        { pop pop }
            /CIDInit /ProcSet findresource
            begin
            12 dict
            begin
            begincmap
            /CMapName 2 index def
            /CMapVersion 1.000 def
            /CMapType 1 def
            /WMode 0 def
            /CIDSystemInfo 3 dict dup
            begin
            /Registry (Adobe) def
            /Ordering (Identity) def
            /Supplement 0 def
            end def
            1 begincodespacerange
            <0000> <FFFF>
            endcodespacerange
            1 begincidrange
            <0000> <FFFF> 0
            endcidrange
            endcmap
            CMapName currentdict /CMap defineresource pop
            end
            end
        } ifelse
        composefont
    } bind def
    end %PSlibdict
    /pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse
    [/Keywords(atend)
    /Subject(atend)
    /Title(atend)
    /Creator (Document Sciences DCPI Build {dcpi_BUILD_3.0SP1.48.124})
    /Author(atend)
    /CreationDate (Wed Feb 09 09:04:42 NZDT 2011)
    /DOCINFO pdfmark
    %%EndProlog
    %%BeginSetup
    PslibDict begin
    %%EndSetup
    %DocScienceBeginComposeFont: EWMKLC+TimesNewRomanPSMT-Identity-H
    16 dict
    begin
    /FontType 42 def
    /FontMatrix [1 0 0 1 0 0] def
    /FontBBox [-1164 2062 4096 -628] def
    /CIDFontName /EWMKLC+TimesNewRomanPSMT def
    /CIDCount 65535 def
    /PaintType 0 def
    /CIDFontType 2 def
    /GDBytes 2 def
    /CIDSystemInfo 3 dict dup
    begin
    /Registry (Adobe) def
    /Ordering (Identity) def
    /Supplement 0 def
    end def
    /CharStrings 1 dict dup begin /.notdef 0 def end def
    /Encoding 1 array dup 0 /.notdef put readonly def
    /CIDMap 0 def
    /GlyphDirectory 16 dict dup begin
        0 <0002011C0000051C050000030007004DB10201BB02BE0006000702BFB2000504B802BEB403000A07
    04B802BEB5010019080605BF02BE0002000301290009016B015E00182B10F63CFD3C4E10F43C4DFD
    3C003F3CFD3C10FC3CFD3C31302111211125211121011C0400FC2003C0FC400500FB002004C0> def
    end def
    /sfnts [
    ] def
    /EWMKLC+TimesNewRomanPSMT currentdict end /CIDFont defineresource pop
    /EWMKLC+TimesNewRomanPSMT-Identity-H /Identity-H [/EWMKLC+TimesNewRomanPSMT] ds_ComposeFont pop
    %DocScienceEndComposeFont: EWMKLC+TimesNewRomanPSMT-Identity-H
    %DocScienceBeginEmbedGlyphs
    /EWMKLC+TimesNewRomanPSMT /CIDFont findresource /GlyphDirectory get
    begin
    37 <00030022000004E6054C001E002B0038027D40305A005A1E8900881E8933991A9D27AC1AAC27E91A
    EA27E72F0C38007A2779339A329933A524AA33D81AD827D8280A043AB802E7B30F67363AB8FFC0B3
    1C22343AB8FFC040E31517343340212C343340191E34324023283432401B1D3444244425891AD901
    D624DA33E52507042401250D32100315061B1A141E1624162815302E3245244A34570158195A2796
    02111000103A55015A24603A703A803AA03A081A301A3250000310071A241E28192F040602031E17
    1E4F3388249A24D93307203A403A503A6302630360056006600760307606731A731B701E74247327
    7A288406861B861E8F33803ACA2FDA2FEB24FA241959080F1F1B092122101F1B1621233324000304
    2C00352B1F24032229382C33032E2228353509162928171716022E280808090890260126B8FFC0B2
    3A3526B8FFC0B2423526B8FF80B33F413426B8FFC0B343463426B8FFC040144235264C5F1C010A1E
    301C021C55042B1F382C31B8FFC040104535124004A004020004A004E0040304B8FFC0400A0D1134
    00040120040104B801D140252C06131302552C0C0F0F02552C0C0D0D02552C22100F0E0F1002550F
    200D0D02550F9E393ABC01D100210061011800182B2B4EF42B2B3C4DED2B2B2BFD5D712B5D714358
    B90031032DE91BB90031032DED592B103C3C3C10F45D72ED2B2B2B2B2B72003F3C10ED3F3C10ED11
    12392FED12173911121739113901111217392B2B3130437940412F342328181E01071A1B191B0206
    062624250225332628182633012F07313301231E2633033401313303271B29330130052E3300251D
    2233001E32033533010100103C2B3C2B2B2B012B2B2B2B2B2B2B2B2A81818181015D710172727200
    7271002B2B2B2B012B2B2B005D005D01161716151406062321353332373635113427262323352132
    171616151406251616333236363534262322071116333236353426262322060703B28D466180DFE5
    FD80335525171D274D33024AA463969E7CFD7B255F3992934EC2BA64507471B5BE56C28F3E581B02
    B41E425C8565B95525362372036C7E212C251824B77766A10F07073F824D77A816FB6F1BA3784F92
    54040500> def
    end
    %DocScienceEndEmbedGlyphs
    %%Page: 1 1
    %%PageBoundingBox: 0 0 612 792
    %%BeginPageSetup
    <</PageSize [612.0 792.0]>> setpagedevice
    [ /CropBox [0 0 612 792] /PAGE pdfmark
    %%PageOrientation: Portrait
    %%EndPageSetup
    Save
    /EWMKLC+TimesNewRomanPSMT-Identity-H findfont [12 0 0 12 0 0] makefont setfont
    90 709.30 a
    0 0 0 setrgbcolor
    <0024> p
    90 695.50 a
    <0025> p
    90 681.70 a
    <0026> p
    90 667.91 a
    <0014> p
    90 654.11 a
    <001C> p
    Restore
    showpage
    %%Page: 2 2
    %%PageBoundingBox: 0 0 612 792
    %%BeginPageSetup
    [ /CropBox [0 0 612 792] /PAGE pdfmark
    %%PageOrientation: Portrait
    %%EndPageSetup
    Save
    /EWMKLC+TimesNewRomanPSMT-Identity-H findfont [12 0 0 12 0 0] makefont setfont
    90 709.30 a
    0 0 0 setrgbcolor
    <0024> p
    90 695.50 a
    <0025> p
    90 681.70 a
    <0026> p
    90 667.91 a
    <0014> p
    90 654.11 a
    <001C> p
    Restore
    showpage
    %%EOF

    I don't know a whole lot about postscript, but I do know a little about encoding and a little bit of experience developing with/against docsciences. What seems to be going on here is that there are glyphs described that translate the encoded text. I have the ability to encode and decode the postscript generated with docscience which I will share with you (in c#) - two event handlers from button clicks have been included to illustrate the usage of these conversions. Running the encoded text you provided through the AsciiConvert method (where offset = 29) revealed this text:
    A
    B
    C
    1
    9
    A
    B
    C
    1
    9
    Hope this helps,
    Usage:
            void btn_ConvertString_Click(object sender, RoutedEventArgs e)
                StringBuilder sb = new StringBuilder();
                foreach (string line in this.tb_Input.Text.Split(Environment.NewLine.ToCharArray()))
                    if (string.IsNullOrEmpty(line))
                        sb.AppendLine("a");
                        continue;
                    sb.AppendLine(HexConvert(line, 29));
                //string output = ConvertStringToHex(this.tb_Input.Text, System.Text.Encoding.ASCII);
                this.tb_Output.Text = sb.ToString();
            protected bool startblock = false;
            void btn_Convert_Click(object sender, RoutedEventArgs e)
                bool begin = true;
                StringBuilder sb = new StringBuilder();
                foreach (string line in this.tb_Input.Text.Split(Environment.NewLine.ToCharArray()))
                    if (line.StartsWith("%%Page:"))
                        sb.AppendLine(line);
                    if (line.EndsWith("a"))
                        startblock = true;
                    if (line.Trim().StartsWith("<") && line.EndsWith("> p"))
                        if (startblock && !begin)
                            sb.AppendLine();
                        begin = false;
                        string output = AsciiConvert(line.Replace("<", "").Replace("> p", ""), 29);
                        sb.Append(output);
                        startblock = false;
                this.tb_Output.Text = sb.ToString();
    Conversion methods:
            private static string AsciiConvert(string _hexInput, int offset)
                //string hexInput = myMatch.Groups[1].ToString();
                string asciiOutput = string.Empty;
                for (int s = 0; s < _hexInput.Length; s += 4)
                    int hold = int.Parse(_hexInput.Substring(s + 2, 2), System.Globalization.NumberStyles.HexNumber);
                    // This is necessary to adjust Document Sciences font matrix
                    hold += offset;
                    asciiOutput += Convert.ToChar(hold).ToString();
                return asciiOutput;
             abcdefghij
             klmnopqrst
             uvwxyz
            private static string HexConvert(string input, int offset)
                /* 0049> f
                 * 0055> r
                 * 0052> o
                 * 0050> m
                StringBuilder hex = new StringBuilder();
                hex.Append("<");
                foreach (char c in input)
                    hex.Append(HexStringTable[c - offset].PadLeft(4, '0'));
                hex.Append("> p");
                return hex.ToString();
            /// <summary>
            /// Hex string lookup table.
            /// </summary>
            private static readonly string[] HexStringTable = new string[]
                "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
                "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
                "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
                "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
                "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
                "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
                "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
                "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
                "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
                "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
                "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
                "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
                "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
                "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
                "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
                "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"

  • Which classes are inherent in the Java language?

    For some reason I just thought of the question this past 2AM.
    What classes are significant to the Java compiler? The list I thought of was:
    Object -- implements wait() and synchronized
    String -- all those convenience idioms we couldn't live without
    StringBuilder -- for String operators like "a" + var
    Integer, Long, Short, Char -- also for String operators like int i; String x = "abc" + i;
    Throwable -- needed for catch clause
    RuntimeException -- needed for implicit throw
    How about the following? Does javac need to know about these? Or are they all handled by the runtime base classes?
    Class
    Constructor
    Thread

    AlanObject wrote:
    jverd wrote:
    ErrorI've never run into this class before, but wouldn't the JVM and not the compiler be dealing with this?> I don't think it has to know about StringBuilder or StringBuffer, as the JLS does not require their use for string concatenation with +. It's just that most implementations do it that way.Good point.
    I don't doubt that in the creation of Java there were long discussions about this. They could have done away with the String-awareness of the language by forcing the use of direct methods but the usability issue won the day.
    Also, are there now classes implied in the use of the for-each statement (Collection?) and in enums (Enumeration?)That would be Iterable, a shiny new abstraction. And, by extension, Iterator. Both them and enums, though, are tricks of the compiler, syntactic sugar. There's no new bytecode for those mechanisms (as yet)

Maybe you are looking for