Java - object file access
how can I access randon to java object file
thanks
Can you clarify this question?
I'm going to give an initial answer, based on a guess as to what you meant:
BCEL lets you access the internals of a compiled Java class file (aka, the bytecode, aka the object code).
Similar Messages
-
How to access variables declared in java class file from jsp
i have a java package which reads values from property file. i have imported the package.classname in jsp file and also i have created an object for the class file like
classname object=new classname();
now iam able to access only the methods defined in the class but not the variables. i have defined connection properties in class file.
in jsp i need to use
statement=con.createstatement(); but it shows variable not declared.
con is declared in java class file.
how to access the variables?
thankshere is the code
* testbean.java
* Created on October 31, 2006, 12:14 PM
package property;
import java.beans.*;
import java.io.Serializable;
public class testbean extends Object implements Serializable {
public String sampleProperty="test2";
public String getSampleProperty() {
return sampleProperty;
}jsp file
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="java.sql.*,java.util.*"%>
<html>
<head>
<title>Schedule Details</title>
</head>
<jsp:useBean id="ConProp" class="property.testbean"/>
<body>
Messge is : <jsp:getProperty name="msg" property="sampleProperty"/>
<%
out.println(ConProp.sampleProperty);
%>
</body>
</html>out.println(ConProp.sampleProperty) prints null value.
is this the right procedure to access bean variables
thanks -
XSLT - How to pass a Java object to the xslt file ?
Hi ,
I need help in , How to pass a java object to xslt file.
I am using javax.xml.transform.Tranformer class to for the xsl tranformation. I need to pass a java object eg
Class Employee {
private String name;
private int empId;
public String getName() {
return this.name;
public String getEmpId() {
return this.empId;
public String setName(String name) {
this.name = name;
public String setEmpId(int empId){
this.empId = empId;
How can i access this complete object in the xsl file ? is there any way i can pass custom objects to xsl using Transformer class ?This is elementary. Did you ask google ? http://www.google.com/search?q=calling+java+from+xsl
ram. -
Accessing Java Object with out any application servers
Hi,
I would be much thankful if any one guide/suggest me how to
access an java object with out using any application servers.I am
having an java object which holds dummy data and an mxml file which
contains some text fields. My plan was to access the java object
and put the dummy data in the text fields. I am using RemoteObject
for this. I am not able to proceed further. Please help me.
Thanks in advance
Regards
Karun KumarYou can check The Merapi Project it's still in the
development phase but it'll allow to an AIR app invoke a java class
and run it as it were inside your app. But that's something you
can't take into production yet, why don't u wanna use a server
backend? -
Generation of XML file from Java objects using castor
I have the following java file(Customer.java).
public class Customer
private String ID;
private FirstName firstName;
private MiddleName middleName;
private LastName lastName;
private ArrayList address;
public ArrayList getAddress() {
return address;
public void setAddress(ArrayList address) {
this.address = address;
public FirstName getFirstName() {
return firstName;
public void setFirstName(FirstName firstName) {
this.firstName = firstName;
public String getID() {
return ID;
public void setID(String id) {
ID = id;
public LastName getLastName() {
return lastName;
public void setLastName(LastName lastName) {
this.lastName = lastName;
public MiddleName getMiddleName() {
return middleName;
public void setMiddleName(MiddleName middleName) {
this.middleName = middleName;
Using castor i have created an xml file(customer.xml) which has the following format.
<?xml version="1.0" encoding="UTF-8" ?>
- <customer ID="fbs0001">
<FIRSTNAME>Fred</FIRSTNAME>
<MIDDLENAME>B</MIDDLENAME>
<LASTNAME>Scerbo</LASTNAME>
- <ADDRESS>
<FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
<SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
</ADDRESS>
- <ADDRESS>
<FIRSTLINE>ITPL</FIRSTLINE>
<SECONDLINE>Whitefield Bangalore</SECONDLINE>
</ADDRESS>
</customer>
I have used a mapping file to get this output.Is there a way where i can get the output xml in the following format without changing the Java object structure.If yes then please suggest how this can be done.
<?xml version="1.0" encoding="UTF-8" ?>
- <customer ID="fbs0001">
<FIRSTNAME>Fred</FIRSTNAME>
<MIDDLENAME>B</MIDDLENAME>
<LASTNAME>Scerbo</LASTNAME>
</customer>
<ADDRESS>
<FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
<SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
</ADDRESS>
- <ADDRESS>
<FIRSTLINE>ITPL</FIRSTLINE>
<SECONDLINE>Whitefield Bangalore</SECONDLINE>
</ADDRESS>
I mean the output xml file should have the address as a separate tag not withing the root tag customer.Hello,
Castor's own discussion groups might be able to point you to the solution you're looking for (if this use case is possible using Castor).
Oracle has its own object-to-XML mapping tool that is part of the TopLink product. It allows you to map existing objects to an existing XML Schema. This can be done visually using the TopLink Workbench, or programmatically using the TopLink APIs. TopLink OXM also supports the JAXB specification.
Using TopLink OXM to get the desired XML result I would recommend the following. Map the Customer and Address classes to XML, but don't map the relationship between Customer and Address. Then make the calls to the marshaller something like the following:
marshaller.marshal(aCustomer, System.out);
for(int x=0; x<aCustomer.getAddress().size(); x++) {
marshal(aCustomer.getAddress().get(x), System.out);
Example - Using TopLink OXM to map an existing object model to an existing XML Schema:
http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/howto/ox/index.htm
For more information on TopLink object-to-XML mapping:
http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/objectxml/index.html
-Blaise -
Parse of a xml file to an java object model
Hello,
I'm trying to do a program that receive an xml file and ought to create all the neccesary java objects according to the content of the parsed xml file.
I've all the class created for all the objects that could be present into the xml and the idea is to go down in the tree of nodes recursively until it returns nodes more simple. Then, I create the last object and while I come back of the recursively calls, I create the objects more complex until I reached to the main object.
Until now, I have part of this code, that is the one wich have to parse the parts of the xml.
public static void readFile(String root){
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
String contents = scanner.next();
scanner.close();
Document document = builder.parse(new ByteArrayInputStream(contents.getBytes()));
Node node = null;
NodeList nodes = null;
Element element = document.getDocumentElement();
System.out.println(element.getNodeName());
NodeList subNodes;
NamedNodeMap attributes;
//if (element.hasAttributes())
visitNodes(element);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
private static void visitNodes (Node node){
for(Node childNode = node.getFirstChild(); childNode!=null;){
if (childNode.getNodeType() == childNode.DOCUMENT_NODE){
System.out.println("Document node Name " + childNode.getNodeName());
visitNodes(childNode);
}else if (childNode.getNodeType() == childNode.ELEMENT_NODE){
System.out.println("Node Name " + childNode.getNodeName());
if (childNode.hasAttributes()){
visitAttributes(childNode.getAttributes());
if (childNode.hasChildNodes()){
visitNodes(childNode);
}else if (childNode.getNodeType() == childNode.TEXT_NODE && !childNode.getNodeValue().contains("\n\t")){
System.out.println("Node value " + childNode.getNodeValue());
Node nextChild = childNode.getNextSibling();
childNode = nextChild;
private static void visitAttributes(NamedNodeMap attributes){
Node node;
for(int i = 0; i < attributes.getLength(); i++){
node = attributes.item(i);
System.out.print(node.getNodeName() + " ");
System.out.print(node.getNodeValue() + " ");
}I don't know the use of childNodeType. For example, I expected that the XML tags with childs in his structure, enter by the option NODE_DOCUMENT and the tags without childs by the ELEMENT_NODE.
But the most important problem I've found are the nodes [#text] because after one ELEMENT_NODE I always found this node and when I ask if the node hasChilds, always returns true by this node.
Has any option to obtain this text value, that finally I want to display without doing other recursively call when I enter into the ELEMENT_NODE option?
When one Node is of type DOCUMENT_NODE or DOCUMENT_COMMENT? My program always enter by the ELEMENT_NODE type
Have you any other suggestions? All the help or idea will be well received.
Thanks for all.Hello again,
My native language is Spanish and sorry by my English I attemp write as better I can, using my own knowledge and the google traductor.
I have solved my initial problem with the xml parser.
Firstly, I read the complete XML file, validated previously.
The code I've used is this:
public static String readCompleteFile (String root){
String content = "";
try {
Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
content = scanner.next();
scanner.close();
} catch (IOException e) {
e.printStackTrace();
return content;
}Now, I've the file in memory and I hope I can explain me better.
I can receive different types of XML that could be or not partly equals.
For this purpose I've created an external jar library with all the possible objects contained in my xml files.
Each one of this objects depend on other, until found leaf nodes.
For example, If I receive one xml with a scheme like the next:
<Person>
<Name>Juliet</Name>
<Father Age="30r">Peter</Father>
<Mother age="29">Theresa</Mother>
<Brother>
</Brother>
<Education>
<School>
</school>
</education>
</person>
<person>
</person>The first class, which initializes the parse, should selecting all the person tags into the file and treat them one by one. This means that for each person tag found, I must to call each subobject wich appears in the tag. using as parameter his own part of the tag and so on until you reach a node that has no more than values and or attributes. When the last node is completed I'm going to go back for completing the parent objects until I return to the original object. Then I'll have all the XML in java objects.
The method that I must implement as constructor in every object is similar to this:
public class Person{
final String[] SUBOBJETOS = {"Father", "Mother", "Brothers", "Education"};
private String name;
private Father father;
private Mother mother;
private ArrayList brothers;
private Education education;
public Person(String xml){
XmlUtil utilXml = new XmlUtil();
String xmlFather = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[0]);
String xmlMother = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[1]);
String xmlBrothers = utilXml.textBetweenMultipleXmlTags(xml, SUBOBJETOS[2]);
String xmlEducation = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[3]);
if (!xmlFather.equals("")){
this.setFather(new Father(xmlFather));
if (!xmlMother.equals("")){
this.setMother(new Father(xmlMother));
if (!xmlBrothers.equals("")){
ArrayList aux = new ArrayList();
String xmlBrother;
while xmlBrothers != null && !xmlBrothers.equals("")){
xmlBrother = utilXml.textBetweenXmlTags(xmlBrothers, SUBOBJETOS[2]);
aux.add(new Brother(xmlBrother);
xmlBrothers = utilXml.removeTagTreated(xmlBrothers, SUBOBJETOS[2]);
this.setBrothers(aux);
if (!xmlEducation.equals("")){
this.setEducation(new Father(xmlEducation));
}If the object is a leaf object, the constructor will be like this:
public class Mother {
//Elements
private String name;
private String age;
public Mother(String xml){
XmlUtil utilXml = new XmlUtil();
HashMap objects = utilXml.parsearString(xml);
ArraysList objectsList = new ArrayList();
String[] Object = new String[2];
this.setName((String)objects.get("Mother"));
if (objects.get("attributes")!= null){
objectsList = objects.get("attributes");
for (int i = 0; i < objectsList.size();i++){
Object = objectsList.get(i);
if (object[0].equals("age"))
this.setAge(object[1]);
else
}Each class will have its getter and setter but I do not have implemented in the examples.
Finally, the parser is as follows:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class XmlUtil {
public HashMap parsearString(String contenido){
HashMap objet = new HashMap();
DocumentBuilderFactory factory;
DocumentBuilder builder;
Document document;
try{
if (content != null && !content.equals("")){
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
document = builder.parse(new ByteArrayInputStream(content.getBytes()));
object = visitNodes(document);
}else{
object = null;
} catch (ParserConfigurationException e) {
e.printStackTrace();
return null;
} catch (SAXException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
return object;
private HashMap visitNodes (Node node){
String nodeName = "";
String nodeValue = "";
ArrayList attributes = new ArrayList();
HashMap object = new HashMap();
Node childNode = node.getFirstChild();
if (childNode.getNodeType() == Node.ELEMENT_NODE){
nodeName = childNode.getNodeName();
if (childNode.hasAttributes()){
attributes = visitAttributes(childNode.getAttributes());
}else{
attributes = null;
nodeValue = getNodeValue(childNode);
object.put(nodeName, nodeValue);
object.put("attributes", attributes);
return object;
private static String getNodeValue (Node node){
if (node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE && !node.getFirstChild().getNodeValue().contains("\n\t"))
return node.getFirstChild().getNodeValue();
else
return "";
private ArrayList visitAttributes(NamedNodeMap attributes){
Node node;
ArrayList ListAttributes = new ArrayList();
String [] attribute = new String[2];
for(int i = 0; i < attributes.getLength(); i++){
atribute = new String[2];
node = attributes.item(i);
if (node.getNodeType() == Node.ATTRIBUTE_NODE){
attribute[0] = node.getNodeName();
attribute[1] = node.getNodeValue();
ListAttributes.add(attribute);
return ListAttributes;
}This code functioning properly. However, as exist around 400 objects to the xml, I wanted to create a method for more easily invoking objects that are below other and that's what I can't get to do at the moment.
The code I use is:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class UtilClasses {
public Object UtilClasses(String package, String object, String xml){
try {
Class class = Class.forName(package + "." + object);
//parameter types for methods
Class[] partypes = new Class[]{Object.class};
//Create method object . methodname and parameter types
Method meth = class.getMethod(object, partypes);
//parameter types for constructor
Class[] constrpartypes = new Class[]{String.class};
//Create constructor object . parameter types
Constructor constr = claseObjeto.getConstructor(constrpartypes);
//create instance
Object obj = constr.newInstance(new String[]{xml});
//Arguments to be passed into method
Object[] arglist = new Object[]{xml};
//invoke method!!
String output = (String) meth.invoke(dummyto, arglist);
System.out.println(output);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
}This is an example obtained from the Internet that I've wanted modified to my needs. The problem is that when the class calls this method to invoke the constructor and does not fail, this does not do what I expect, because it creates an empty constructor. If not, the parent class gives a casting error.
I hope that now have been more clear my intentions and that no one has fallen asleep reading this lengthy explanation.
greetings. -
File Access with unsigned Applet through editing the java.policy file
I'am starting to lose my hair on this...
I am trying to get an applet to run so that it can access the file system to move files on my local maschin. Because this applet is only running on my VM i can change the java.policy to avoid the signing of the applet.
first of all, if i wrote in the java.policy file
grant {
permission java.security.AllPermission;
};everything is working perfekt.
But I have not the intention to open the gates for any applet out there, so i want to limit the access to my applet. With every of the following versions I get at best an
java.security.AccessControlException: access denied (java.io.FilePermission...
My Setup
My Java Version: jre1.6.0_02
My applet is located unter the url
http://admin.mydomain.com/applet.jar
In Html i tryed the following different versions of loading the applet - none worked
<applet codebase="http://admin.mydomain.com/" name="shortcut" code="start.class" archive="applet.jar" width="0" height="0"></applet>
<applet codebase="http://admin.mydomain.com" name="shortcut" code="start.class" archive="applet.jar" width="0" height="0"></applet>
<applet name="shortcut" code="start.class" archive="http://admin.mydomain.com/applet.jar" width="0" height="0"></applet>in java.policy i tryed following versions with every html applet load version
grant codeBase "http://admin.x-press.de/-" {
permission java.security.AllPermission;
grant codeBase "http://admin.x-press.de/+" {
permission java.security.AllPermission;
grant codeBase "http://admin.x-press.de/applet.jar" {
permission java.security.AllPermission;
};why is it with
grant {
permission java.security.AllPermission;
};working, and not with the other versions?
i am almost bold now, please try to save my last hair from falling down.
any suggestion would be nice
thanks, feyyaz
Message was edited by:
feyyazdoguI read the mentioned documentation and your right, some of my versions were wrong, but after reading the doumentation again i came to following result which should had worked but didn't.
java.policy
grant codeBase "http://admin.mydomain.com/*" {
permission java.security.AllPermission;
HTML File
<applet codebase="http://admin.mydomain.com/" name="shortcut" code="start.class" archive="applet.jar" height="0" width="0"></applet>if I am entering http://admin.mydomain.com/applet.jar i can download the jar, so the archive lays in the correct directory.
what i am doing wrong? do i have to change an additional file somewhere else? -
Java.io.File causes "access denied" exception in a signed applet
Hi,
New to these forums and not entirely where it's appropriate to post this issue, so I'll stick it here for now until told otherwise.
The problem:
My applet throws the following exception.
INFO: Exception Message: access denied (java.io.FilePermission C:\Some Dir With Spaces\AnotherDir\FinalDir read)
The psuedo-code:
java.io.File RootPath = new java.io.File( "C:\" );
private boolean doesSubdirectoryExist(String directory) {
boolean mResult = false;
try
java.io.File tmpPath = new java.io.File( RootPath.toString() + java.io.File.separatorChar + directory );
mResult = tmpPath.isDirectory();
tmpPath = null;
catch (Exception e)
... error handling code
return mResult;
private void btnCheckPathActionPerformed(java.awt.event.ActionEvent evt) {
....some other stuff....
doesSubdirectoryExist(.. a text field value from the GUI form..);
....some other stuff....
} The conditions:
1) The applet is signed.
2) The applet runs fine in the AppletViewer.
3) I am using JDK1.5.0_09.
4) When I click the button the event handler is tied to, it works correctly the first time.
5) If I click a second time, with the same value in the text field (i.e. testing for the same subdirectory again) I get the exception error.
I'm pulling my hair out trying to figure this one out. If it were a security issue with the applet running from a browser, why does it work the first time?
Am I failing to release some lock that creating a java.io.File instance creates?
I would appreciate any help.I've identified the issue. I was attempting to access the filesystem from two different thread and/or contexts.
It seems that if I use the SwingWorker class from https://swingworker.dev.java.net/ to perform background tasks in the Worker thread, I don't get the security privileges required to modify the filesystem. Even though I have signed the jar correctly.
However I can access the filesystem quite happily from the Event Dispatcher thread. If my jar is signed correctly.
So, I have the following questions:
1. Why doesn't SwingWorker worker threads get the same security context as the event dispatcher thread?
2. Is there anyway I can give the worker thread the necessary security privileges?
3. Is there anyway to do this without having to write my own thread handling code and creating my own thread pools?
Message was edited by:
Fidotas
Message was edited by:
Fidotas -
Error could not access a java object field called allowAppDataInServContext after Applying Security
After applying the security patch 12-26 I am getting the error "Could not access a java object field called allowAppDataInServContext". When I removed the update the error goes away. When I read the update it returns.
The error states it occurred in the following line: cfapplication name="somename" clientmanagement="No" sessionmanagement="Yes" setclientcookies="Yes"Is it a linux server? Look at the following, second comment.
http://blogs.coldfusion.com/post.cfm/coldfusion-security-update
^_^
EDIT: Also, http://www.shilpikhariwal.com/2012/12/security-hotfix-for-coldfusion-9-and.html -
Database access from flex thro java objects
Please tell me how to access the data from the MS SQL server
through a java object and connect it to flex and display the data
in flex.
please provide me the code for this assignment.
Thanks in Advance.
Selvakumar.What would you consider when choosing between FDS and PHP
(via HTTP) for mySQL communication?
My app doesn't need to be real time but I am concerned about
the load on the webserver running PHP. Is that a typical point of
failure? -
Java.io.EOFException in Object file transfer
Greetings,
I am having a problem sending a file across a network. At one point it was working, however I am not sure where along the way it became broken.
Stack Trace:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Sour
ce)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at WBServer.unpackVectors(WBServer.java:283)
at fileListener.run(WBServer.java:374)
public void getWBContent(String hid) throws java.rmi.RemoteException //<- Send all object vectors and relevant integers...
setPageNum(pageCount-1);
HID=hid;
packVectors(null);
new Thread() {
public void run(){
try{javax.swing.SwingUtilities.invokeLater(
new Runnable(){
public void run(){
try{ //Yes...
java.net.Socket s = new java.net.Socket(HID, 1113); //<- Make a network port
java.io.BufferedWriter sos = new java.io.BufferedWriter(new java.io.OutputStreamWriter(s.getOutputStream())); //<-Open a stream
sos.write("vectordata.dat"); //<-Send the name of the file
sos.close(); //<- Close the stream
s.close(); //<- Close the port
String anchor = getClass().getResource("WBServer.class").getPath();
java.net.Socket ns = new java.net.Socket(HID, 1113); //<- Open a new port to the same place
java.io.FileInputStream fio = new java.io.FileInputStream(anchor.substring(0, anchor.lastIndexOf('/')+1)+"vectordata.dat"); //<- Open the file to stream
//java.io.DataInputStream dia = new java.io.DataInputStream(fio); //<- Open the stream to read
java.io.BufferedInputStream bia = new java.io.BufferedInputStream(fio);
java.io.BufferedOutputStream boa = new java.io.BufferedOutputStream(ns.getOutputStream());//<- Open the data stream for the port
int read=0; //<- Byte Read Counter
byte[] fbuffer = new byte[1024]; //<- Byte Read Buffer
boolean EOF=false;
while(!EOF){ //<- Until we reach the end of the stream...
try{read=bia.read(fbuffer);
boa.write(fbuffer, 0, read);} //<- ...send the number of bytes stored in the buffer at the time.
catch(java.io.EOFException e){ EOF=true;}
boa.flush(); //<- Make sure the stream is cleared
boa.close(); //<- Close the port's stream
bia.close(); //<- Close the reading stream
fio.close(); //<- Close the file's stream
ns.close(); //<- Close the port...
catch(Exception e)
{SimpleFormatter sf = new SimpleFormatter();
LogRecord tempLog = new LogRecord(Level.WARNING, "File Send Error: "+e.toString());
sf.format(tempLog);
logFile.publish(tempLog);}
catch(Exception e)
{SimpleFormatter sf = new SimpleFormatter();
LogRecord tempLog = new LogRecord(Level.WARNING, "Error running getWBContent() send file thread: "+e.toString());
sf.format(tempLog);
logFile.publish(tempLog);}
}}.start();
public void packVectors(String filePath) { //This function writes all the objects in memory to a file for transport.
String anchor = getClass().getResource("WBServer.class").getPath();
if(filePath==null){filePath=anchor.substring(0, anchor.lastIndexOf('/')+1)+"data/vectordata.dat";}
System.out.println("From packVectors(): "+filePath);
java.io.File ovFile = new java.io.File(filePath); //Setup out data file
try{if(!ovFile.exists()){ovFile.createNewFile();}else{ovFile.delete(); ovFile.createNewFile();} //If it's not there...make one. If it is, delete it and make a new one.
java.io.ObjectOutputStream oojStream = new java.io.ObjectOutputStream(new java.io.FileOutputStream(ovFile)); //Ready the writer for writingness.
oojStream.writeObject(PageHolder); //Pages to file...
oojStream.writeObject(ImgPage); //Images for the Pages to file...
oojStream.writeObject(WBStack); //Current object stack to file...
oojStream.writeInt(objCount); //Current object count to file...
oojStream.writeInt(pageCount); //Current page count to file...
oojStream.writeInt(pageCount-1); //Current page number to file...
oojStream.flush(); //<-Commit final write operations...
oojStream.close();} //<- Close the file...
catch(Exception e)
{SimpleFormatter s = new SimpleFormatter();
LogRecord tempLog = new LogRecord(Level.WARNING, "Persistence save error: "+e.toString());
s.format(tempLog);
e.printStackTrace();
logFile.publish(tempLog);}
public void unpackVectors(String filePath) { //This function reads objects from a file that was previously written by packVectors().
String anchor = getClass().getResource("WBServer.class").getPath();
if(filePath==null){filePath=anchor.substring(0, anchor.lastIndexOf('/')+1)+"data/vectordata.dat";}
System.out.println("From unpackVectors(): "+filePath);
java.io.File ivFile = new java.io.File(filePath); //Setup the file to read from.
try{if(!ivFile.exists()){ //If the file doesn't exist, we're screwed...
SimpleFormatter s = new SimpleFormatter();
LogRecord tempLog = new LogRecord(Level.WARNING, "Persistence load error: File vectordata.dat does not exist!");
s.format(tempLog);
logFile.publish(tempLog);
}else{
java.io.ObjectInputStream iojStream = new java.io.ObjectInputStream(new java.io.FileInputStream(ivFile)); //Ready the reader for readingness...
PageHolder = (java.util.Vector)iojStream.readObject(); //Pages from file...
ImgPage = (java.util.Vector)iojStream.readObject(); //images for Pages from file...
WBStack = (java.util.Vector)iojStream.readObject(); //Current object stack from file...
objCount = iojStream.readInt(); //Current object count from file...
pageCount = iojStream.readInt(); //Current number of pages from file...
pageNum = iojStream.readInt();//iojStream.readInt(); //Current page number from file...
iojStream.close();}} //Close the file...
catch(Exception e)// We screwed up somewhere.....
{SimpleFormatter s = new SimpleFormatter();
LogRecord tempLog = new LogRecord(Level.WARNING, "Persistence load error: "+e.toString());
s.format(tempLog);
e.printStackTrace();
logFile.publish(tempLog);}
class fileListener extends Thread {
public fileListener(WBServer wb) //<-Constructor
try{ms = new java.net.ServerSocket(1113);} //<- Listener socket
catch(Exception e){e.toString();}
server = wb; //<- Referencial variable back to the server
public fileListener(WBServer wb, int port) //<- Constructor with port
try{ms = new java.net.ServerSocket(port);} //<- Listener socket
catch(Exception e){e.toString();}
server = wb; //<- Referencial variable back to the server
public void run() {
String filepath; //<- Holder for file path operations...
while(!disconnect) {
try{java.net.Socket cs = ms.accept(); //<- Accept incoming request.
server.fileStat = 1;
java.io.BufferedReader str = new java.io.BufferedReader(new java.io.InputStreamReader(cs.getInputStream())); //<- Open communications with client
String checkStr = str.readLine(); //<- Grab the file name from the client
System.out.println(checkStr);
String anchor = getClass().getResource("fileListener.class").getPath();
if(checkStr.equalsIgnoreCase("vectordata.dat"))
{filepath=anchor.substring(0, anchor.lastIndexOf('/')+1)+"data/"+checkStr;}
else{filepath=anchor.substring(0, anchor.lastIndexOf('/')+1)+"scans/"+checkStr;}
System.out.println(filepath);
str.close(); //<- Close communications with client
cs.close(); //<- Close socket
//System.out.println("Recieved File Name: "+filepath);//Debugging
java.io.File inFile = new java.io.File(filepath); //<- Make a file in memory on the host computer with the specified name.
inFile.createNewFile(); //<- Create an empty file of that name within the local file system
java.net.Socket ds = ms.accept(); //<- Accept incoming request
java.io.FileOutputStream fos = new java.io.FileOutputStream(inFile); //<- Open file stream for writing...
java.io.BufferedInputStream bis = new java.io.BufferedInputStream(ds.getInputStream()); //<- Open communications with client for data/
byte[] fbuffer = new byte[1024]; //<- Byte read buffer
int read=0; //<- Byte read counter
server.fileStat = 2;
while((read=bis.read(fbuffer))!=-1){ //<-Until we reach the end of the stream...
fos.write(fbuffer, 0, read); System.out.print(read+":");}// <- ...write the buffer to the file.
fos.flush(); //<- Clear the file stream
fos.close(); //<- Close the file stream
bis.close(); //<- Close the data stream from the client
if(checkStr.equalsIgnoreCase("vectordata.dat"))
{server.fileStat = 3; // ...otherwise, we show loading...
server.unpackVectors(null);
server.sendRefresh(true);
server.fileStat=0;}
else //If it's the sych data, unpack it and load the data
{server.fileStat = 3; // ...otherwise, we show loading...
server.passImage(inFile); //<-Load the file into the image vector...
server.sendRefresh(true); //<- Ensure that the client updates properly
server.fileStat=0;}
ds.close(); //<- Close the client socket
catch(Exception e){e.toString();}
//System.out.println("Listener Shutdown");//Debugging
try{ms.close();} catch(Exception e){e.toString();} //<- Close the listening socket
public boolean disconnect = false; //<- Flag for killing the "file server" prematurely
private static WBServer server; //<- Referencial variable to the whiteboard server
private java.net.ServerSocket ms; //<- Listener socket
}I'm stumped as to where it is going wrong. I know that packVectors() and unpackVectors() both work, as they are used in a local save function. I suspect the problem lies between the getWBContent(String hid) and the fileListener class, but I am not certain where. Any help would be appreciated.First, you are expecting read(buffer,offset,count) to throw an EOFException. It doesn't, it returns -1 at EOF.
Second, you are using a Writer to write binary data (resulting from serialization). This will corrupt it. Use an OutputStream.
Third, what I really don't get is why would you (i) write local data to a file and (ii) start a new thread to (iii) read it back and (iv) send it over not one but two sockets, when you could just return the data as the result of the remote method without the file, the thread, or the Sockets.
And in any case this sort of thing is most definitely not what SwingtUtilites.invokeLater() is for. (What it is for is updating Swing components and ensuring it all happens in the Swing thread, being the only correct way to write Swing code as Swing is not thread-safe by design.) If your server has a Swing GUI, which doesn't seem likely, it will stall for the duration of all this I/O. If it doesn't, why start the Swing thread at all?
Just define a serializable object that contains all the data you are passing to writeObject()/writeInt() and return it as the result of the remote method.
You will save yourself a lot of latency and code in the process, and you could reduce all this to about six lines of code, something like:
return new WBContent(
PageHolder, //Pages to file...
ImgPage, //Images for the Pages to file...
WBStack, //Current object stack to file...
objCount, //Current object count to file...
pageCount, //Current page count to file...
pageCount-1 //Current page number to file...
); where WBContent is a serializable class with the appropriate members and constructor, and is the return type of getWBContent(). -
Serializing Java Objects to XML files
Hi,
We looking for SAP library which can serialize Java Objects into XML files.
Can you point us were to find it ?
We have found such open source library called "XStream" at the following link
http://www.xml.com/pub/a/2004/08/18/xstream.html
Is it allowed to use that library inside SAP released software ?
Thanks
OritHow about https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/webcontent/uuid/83f6d2fb-0c01-0010-a2ba-a2ec94ba08f4 [original link is broken] [original link is broken]? Depends on your use cases...
Both are supported in SAP NW CE 7.1.
HTH!
-- Vladimir -
Hi..
I am currently working on Internationalization. I have created property files for the textual content and using PropertyResourceBundles. Now I want to use ListResourceBundles. So what I want to know is..
How to convert Property files into Java Objects.. I think Orielly(in their book on Internationalization) has given an utitlity for doing this. But I did not get a chance to look into that. If anyone has come across this same issue, can you please help me and send the code sample on how to do this..
TIA,
CKHi Mlk...
Thanks for all your help and suggestions. I am currently working on a Utility Class that has to convert a properties file into an Object[][].
This will be used in ListResourceBundle.
wtfamidoing<i>[0] = currentKey ;
wtfamidoing<i>[1] = currentValue ;I am getting a compilation error at these lines..(Syntax error)
If you can help me.. I really appreciate that..
TIA,
CK -
How to print the image data stored in object of 'java.io.File' Class in jsp
I have created a file object for the image file in the system temporary directory.Now I want to display it in my page. please tell,How to print the image data stored in object(in my program it is imgr) of 'java.io.File' Class in jsp
Create a servlet which gets an InputStream of the file and writes it to the OutputStream of the response and call this servlet in `src` attribute. That's basically all.
Here's an example which covers the most of the minimum needs: [http://balusc.blogspot.com/2007/04/imageservlet.html]. -
Trying to access the java script files via jar file in WEB SERVER
hi all,
I am trying to access the java script files via jar file ,which is present in Apache webserver in order to minimise the number of hits to app server.some thing like cache ...
in jsp the code goes like this...
<script type="text/javascript" archive="http://localhost:14000/dojo.jar!" src="dojo.jar/parser.js" " ></script>{code}
But i am not able to access the js file which is put in jar file present in the webserver.Hi,
You can use DWR (Direct Web remoting) for that. It is easy AJAX for java. ou can directly call the java script function from java class and also java class from javaScripts..
Regards,
Hardik
Maybe you are looking for
-
How to transfer files using Oracle Managed File Transfer from Oracle EBS 12.1.3
Hello, I'm looking for ideas to securely transfer files bi-directional between Oracle EBS 12.1.3 to IIS using Oracle Managed File Transfer and SOA. Any help is greatly appreciated. Thanks
-
Regarding creation of an invoice/open-item via FB01 or F-22
Hello All, I was trying to post an invoice/open item in a customer's account. I used the transaction code fb01 or we can also use f-22 for the same. I was confused regarding what posting keys to use to have a debit and a credit entry while creating a
-
Hi, I am workingon JDBCXIRFC scenario. After creating Data types, message types, message interfaces and etc, i started defining communciation channel template under "Adapter Objects". While selecting the particular Adapter type, the window is popping
-
Material substitute in purchase requisition
Hi all! I know that in SD we can manage material determination, but I'd like to know if I can do the same in MM, using for example material substitute when I create a purchase requisition. Is it possible? Which is the best practise for this? Thanks S
-
hello. Is Nikon D5200 compatible with Lightroom 3 ? (sorry for my poor english)