Android Wear File does not appear - file

I created a file to read the sensors of my Android Wear. I can tell it is working because my storage is being filled up, but I can't see the folder of the readings. Can you help me out finding out what is wrong with the code?
public class Logging extends Activity implements SensorEventListener {
DecimalFormat df =new DecimalFormat("##.##");
Boolean flag=true;
FileOutputStream outputStream;
TextView displayReading1;
TextView displayReading2;
TextView displayReading3;
TextView displayReading4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File Project=getDir("Project", Context.MODE_PRIVATE);
if(!Project.exists())
Project.mkdir();
File fileWithinProject=new File (Project+"/","Project.txt");
if(!fileWithinProject.exists())
try {
fileWithinProject.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// final File file=new File (dirPath,"Project.txt");
/* File file = new File(dirPath, "Project.txt");
try {
if (!file.exists())
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}*/
setContentView(R.layout.activity_logging);
Button start=(Button)findViewById(R.id.StartButton);
Button stop=(Button)findViewById(R.id.StopButton);
//BUTTON START
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=true;
Toast.makeText(getApplicationContext(),"Start Recording Readings",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), ("File in: "+ Project), Toast.LENGTH_LONG).show();
}
}); {
}
//BUTTON STOP
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=false;
Toast.makeText(getApplicationContext(),"Done recording readings",Toast.LENGTH_SHORT).show();
}
});{
}
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor accSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor rotSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
Sensor gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
Sensor gyroSensor = sensorManager.getDefaultSensor((Sensor.TYPE_GYROSCOPE));
sensorManager.registerListener(this, accSensor, 100000000);
sensorManager.registerListener(this, rotSensor, 100000000);
sensorManager.registerListener(this, gravitySensor, 100000000);
sensorManager.registerListener(this, gyroSensor, 100000000);
displayReading1 = (TextView) findViewById(R.id.acc_sensor);
displayReading2 = (TextView) findViewById(R.id.rotational_sensor);
displayReading3 = (TextView) findViewById(R.id.gravity_sensor);
displayReading4 = (TextView) findViewById(R.id.gyro_sensor);
displayReading1.setTextSize(14f);
displayReading2.setTextSize(14f);
displayReading3.setTextSize(14f);
displayReading4.setTextSize(14f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_logging, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSensorChanged (SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
displayReading1.setText("Accelerometer (m/s2): " +"\nX"+" " +df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X11=event.values[0];
float X12=event.values[1];
float X13=event.values[2];
if( flag) {
try {
// Toast.makeText(getApplicationContext(), ("current location newFile.getAbsolutePath()), Toast.LENGTH_LONG).show();
outputStream = openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(((df.format(X11) + df.format(X12) + df.format(X13)
)).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
displayReading2.setText("Rotational Vector: " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X21=event.values[0];
float X22=event.values[1];
float X23=event.values[2];
if( flag) {
try {
outputStream=openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(("Rotational Vector : " +"\nX"+" " +df.format(X21) + "\nY"+" " + df.format(X22) + "\nZ"+" " + df.format(X23)).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}}
if (event.sensor.getType() == Sensor.TYPE_GRAVITY)
displayReading3.setText("Gravity (m/s2): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE)
displayReading4.setText("Gyroscope (rad/s): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X31=event.values[0];
float X32=event.values[1];
float X33=event.values[2];
if( flag) {
try {
outputStream = openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(("Gyroscope (rad/s): " + "\nX" + " " + df.format(X31) + "\nY" + " " + df.format(X32) + "\nZ" + " " + df.format(X33)
).getBytes());
//Toast.makeText(getApplicationContext(), "Gyroscope (rad/s): " + "\nX" + " " + df.format(X31) + "\nY" + " " + df.format(X32) + "\nZ" + " " + df.format(X33), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (!flag){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}

Related

Sqlite The database file is locked database is locked

I constantly write an error, the database is locked. I just can not understand why this is happening.
db_login.cs
private db_controller _dbctrl = new db_controller();
public SqliteDataReader dataread;
private string query;
//this two inputField,
public void LoginToGo()
{
login = _login.captionText.text;
pass = _pass.text.ToString();
query = "SELECT id from users where users = '" + login + "' AND pass = '" + pass + "'";
try
{
dataread = _dbctrl.ExecuteReader(query);
if(dataread.HasRows & dataread != null)
{
while (dataread.Read())
{
VerifyAdmin();
_dbctrl.Disconnect();
}
}
else
{
errortxt.text = "Неверный логин или пароль, пожалуйста повторите!";
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void VerifyAdmin() //Who are you, admin or user
{
login = _login.captionText.text;
query_access = "SELECT root from users where users = '" + login + "'";
try
{
dataread = _dbctrl.ExecuteReader(query_access);
while (dataread.Read())
{
if(dataread[0].ToString() == "0" || dataread[0].ToString() == null)
{
MainMenu();
}
else
{
AdminMenu();
}
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void AdminMenu()
{
JOIN.SetActive(false);
ADMIN.SetActive(true);
}
public void MainMenu()
{
JOIN.SetActive(false);
MAIN.SetActive(true);
}
db_controller.cs
public SqliteConnection con_db;
public SqliteCommand cmd_db;
public SqliteDataReader rdr_db;
public void connections()
{
try
{
if(Application.platform != RuntimePlatform.Android)
{
path = Application.dataPath + "/StreamingAssets/db.bytes"; // Путь для Windows
}
else
{
path = Application.persistentDataPath + "/db.bytes"; // Путь для Android
if(!File.Exists(path))
{
WWW load = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "db.bytes");
while (!load.isDone) { }
File.WriteAllBytes(path, load.bytes);
}
}
con_db = new SqliteConnection("URI=file:" + path);
con_db.Open();
if (con_db.State == ConnectionState.Open)
{
debugText.text = path.ToString() + " - is connected";
Debug.Log(path.ToString());
}
}
catch (Exception ex)
{
debugText.text = ex.ToString();
}
}
//Тут я создаю метод отключения
public void Disconnect()
{
con_db.Close();
}
public SqliteDataReader ExecuteReader(string query)
{
connections();
try
{
cmd_db = new SqliteCommand(query, con_db);
rdr_db = cmd_db.ExecuteReader();
return rdr_db;
}
catch (Exception ex) { debugText.text = ex.ToString(); return null; }
}
//Тут я записываю данные. Заодно решил проверить закрыто ли соединение.
public void SetDB()
{
if (con_db.State == ConnectionState.Open)
{
Debug.Log("open");
}
else
{
Debug.Log("close!");
}
//The connection is closed. But I can not complete the request cmd_db.ExecuteNonQuery();
connections();
try
{
brand = AutoName.captionText.text;
model = AutoModel.captionText.text;
years = OldAuto.captionText.text;
number = GosNumber.text.ToString();
nusers = UserName.text.ToString();
dbirthday = DBirthday.captionText.text;
mbirthday = MBirthday.captionText.text;
ybirthday = YBirthday.captionText.text;
mobile = Mobile.text.ToString();
cmd_db = new SqliteCommand("INSERT INTO clients(brand,model,years,number,nusers,dbirthday,mbirthday,ybirthday,mobile,groupmodel) values('" + brand + "', '" + model + "','" + years + "','" + number + "','" + nusers + "','" + dbirthday + "','" + mbirthday + "','" + ybirthday + "','" + mobile + "','" +groupmodel+ "')" , con_db);
cmd_db.ExecuteNonQuery(); //Swears, says that the base is locked. And why? I just read the data and the connection was closed.
}
catch (Exception ex) { debugText.text = ex.ToString(); }
Disconnect();
}
the documentation says:
This error code occurs when you try to do two incompatible things with the database at the same time from the same connection to the database.
But the connection with the base is closed.
Maybe I'm missing something, or not doing the right thing. I ask for help to clarify this issue.

Multipart image upload issue in Codename One

I am using this code to upload an image. It works on emulator but always fail on Android device (OS 6.0)
My code is
`private void uploadImage3(final String imagePath, String id){
final Hashtable htArg = new Hashtable();
htArg.put("pk1value", id);
htArg.put("pk2value", "");
htArg.put("pk3value", "");
htArg.put("datatype", "6");
htArg.put("module", "");
htArg.put("action", "");
try {
htArg.put("thefile", FileSystemStorage.getInstance().openInputStream(imagePath));
} catch (IOException ex) {
Log.p("imgRequest.Error = " + ex.toString());
}
htArg.put("submit", "Submit");
final String boundary = "-----------------------------0123456789012";
MultipartRequest request = new MultipartRequest(){
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
Writer writer = null;
writer = new OutputStreamWriter(os, "UTF-8");
String CRLF = "\r\n";
boolean canFlushStream = true;
Enumeration e = htArg.keys();
while(e.hasMoreElements()) {
if (shouldStop()) {
break;
}
String key = (String)e.nextElement();
Object value = htArg.get(key);
writer.write("--");
writer.write(boundary);
writer.write(CRLF);
if(value instanceof String) {
writer.write("Content-Disposition: form-data; name=\""+key+"\"");
writer.write(CRLF);
writer.write(CRLF);
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
writer.write(Util.encodeBody((String)value));
if(canFlushStream){
writer.flush();
}
}else {
writer.write("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + key +"\"");
writer.write(CRLF);
writer.write("Content-Type: ");
writer.write("image/jpeg");
writer.write(CRLF);
writer.write("Content-Transfer-Encoding: binary");
writer.write(CRLF);
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
InputStream i;
if (value instanceof InputStream) {
i = (InputStream)value;
byte[] buffer = new byte[8192];
int s = i.read(buffer);
while(s > -1) {
os.write(buffer, 0, s);
if(canFlushStream){
writer.flush();
}
s = i.read(buffer);
}
// (when passed by stream, leave for caller to clean up).
if (!(value instanceof InputStream)) {
Util.cleanup(i);
}
} else {
os.write((byte[])value);
}
value = null;
if(canFlushStream){
writer.flush();
}
}
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
}
writer.write("--" + boundary + "--");
writer.write(CRLF);
if(canFlushStream){
writer.flush();
}
writer.close();
}
#Override
protected void readResponse(InputStream input) {
try {
Result result = Result.fromContent(input, Result.XML);
Log.p("imgRequest response: " + result.toString());
} catch (Exception ex) {
Log.p("imgRequest.Error = " + ex.toString());
ex.printStackTrace();
}
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Log.p("handleErrorResponseCode = "+code + ":" + message);
}
#Override
protected void handleException(Exception err) {
Log.p("handleException = "+err.toString());
err.printStackTrace();
}
};
String theURL = Application.getCurrentConnection().get("URL").toString() + "/W1Servlet";
request.setUrl(theURL+"/uploadfiledebug");
request.setBoundary(boundary);
request.setPost(true);
try {
//need to keep this code as it will calculate file size internally
// and also have to add thefile separately in myArgHashTable
request.addData("thefile", imagePath, "image/jpeg");
request.setFilename("thefile", "img.jpeg");
} catch (Exception ex) {
}
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
request.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(request);
}`
The traced error on real device is,
`java.net.ProtocolException: exceeded content-length limit of 11076 bytes
at com.android.okhttp.internal.http.RetryableSink.write(RetryableSink.java:58)
at com.android.okhttp.okio.RealBufferedSink.close(RealBufferedSink.java:234)
at com.android.okhttp.okio.RealBufferedSink$1.close(RealBufferedSink.java:209)
at com.codename1.impl.CodenameOneImplementation.cleanup(CodenameOneImplementation.java:4385)
at com.codename1.impl.android.AndroidImplementation.cleanup(AndroidImplementation.java:4579)
at com.codename1.io.Util.cleanup(Util.java:149)
at com.codename1.io.BufferedOutputStream.close(BufferedOutputStream.java:287)
at com.codename1.impl.CodenameOneImplementation.cleanup(CodenameOneImplementation.java:4385)
at com.codename1.impl.android.AndroidImplementation.cleanup(AndroidImplementation.java:4579)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:804)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread$1.run(CodenameOneThread.java:60)
at java.lang.Thread.run(Thread.java:818)`
I am not sure what I am missing.
Please someone can help me.
Thanks
Updated Code
`private void uploadImage4(final String imagePath, String id){
MultipartRequest request = new MultipartRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
try {
Result result = Result.fromContent(input, Result.XML);
if(isDebugOn){
Application.writeInDebugFile(debugFileName,
"result.toString(): "+ result.toString());
}
Log.p("imgRequest response: " + result.toString());
} catch (Exception ex) {
Log.p("imgRequest.Error = " + ex.toString());
ex.printStackTrace();
if(isDebugOn){
Application.writeInDebugFile(debugFileName,
"readResponse.Exception: "+ex.toString());
}
}
}
};
String theURL = Application.getCurrentConnection().get("URL").toString() + "/W1Servlet";
request.setUrl(theURL+"/uploadfiledebug");
request.addArgument("entityname", "RCV_HEADERS");
request.addArgument("category", "37");
request.addArgument("description", "Uploaded by More4Apps Mobile App");
request.addArgument("pk1value", id);//this is used as a primary key
request.addArgument("pk2value", "");
request.addArgument("pk3value", "");
request.addArgument("datatype", "6");
request.addArgument("module", "");
request.addArgument("action", "");
request.addArgument("submit", "Submit");
try {
//add the data image
request.addData("thefile", imagePath, "image/jpeg");
request.setFilename("thefile", "img.jpeg");
} catch (IOException ex) {
Log.p("Error:"+ ex.toString());
}
request.setPriority(ConnectionRequest.PRIORITY_CRITICAL);
NetworkManager.getInstance().addToQueue(request);
}`
And new error is:
`<ERROR_MESSAGE>IO Error:com.more4apps.mobile.ActionUploadFileoracle.ord.im.OrdHttpUploadException: IMW-00106: the end-of-headers delimiter (CR-LF) was not present
IMW-00112: additional error information: Content-Type: text/plain; charset=UTF-8IMW-00106: the end-of-headers delimiter (CR-LF) was not present
IMW-00112: additional error information: Content-Type: text/plain; charset=UTF-8
oracle.ord.im.OrdMultipartParser.doParse(OrdMultipartParser.java:312)
oracle.ord.im.OrdMultipartParser.parseFormData(OrdMultipartParser.java:150)
oracle.ord.im.OrdHttpUploadFormData.parseFormData(OrdHttpUploadFormData.java:532)
com.more4apps.mobile.ActionUploadFile.performAction(ActionUploadFile.java:39)
com.more4apps.mobile.W1Servlet.processAction(W1Servlet.java:449)
com.more4apps.mobile.W1Servlet.doPost(W1Servlet.java:248)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:64)
oracle.apps.jtf.base.session.ReleaseResFilter.doFilter(ReleaseResFilter.java:26)
com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:15)
oracle.apps.fnd.security.AppsServletFilter.doFilter(AppsServletFilter.java:318)
com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:642)
com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:391)
com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:908)
com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:458)
com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:313)
com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:199)
oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
java.lang.Thread.run(Thread.java:682)</ERROR_MESSAGE>`
If you override buildRequestBody in a multipart request you effectively disable its functionality...
All of that code is incorrect and shouldn't be there. Multipart will work for large files by default.

Customizing DBTrigger message in adf

Hi I am trying to customize DBTrigger message in bean Here is code for it, it is displaying my customized message but as well it is displaying DBTrigger message below to my message, Kindly help me to get out of this.
public void saveLataActionListenerNew(ActionEvent actionEvent) {
System.out.println("----on click saved ");
try {
OperationBinding operationBinding = (OperationBinding)getBindings().getOperationBinding("Commit");
Object result = operationBinding.execute();
System.out.println("Errors : " + operationBinding.getErrors());
if (operationBinding.getErrors() != null) {
Iterator it = operationBinding.getErrors().iterator();
System.out.println("error = " + it);
System.out.println("size of Errors - " + operationBinding.getErrors().size());
while (it.hasNext()) {
DMLException error = (DMLException)it.next();
String errorCause = "" + error.getCause();
System.out.println("error.getCause() : " + errorCause);
if (errorCause != null && errorCause.contains("ORA-00001: unique constraint")) {
uniqueConstraint = "Lata is Exists for given State";
showMessage(uniqueConstraint, FacesMessage.SEVERITY_ERROR);
return;
}
}
}
uniqueConstraint = "Record is saved successfully";
showMessage(uniqueConstraint, FacesMessage.SEVERITY_INFO);
System.out.println("---record saved successfully");
// addPlaceCodePfl.setRendered(false);
// addPlaceCodePgl.clearInitialState();
// addPlaceCodePfl.
} catch (Exception e) {
uniqueConstraint = e.getMessage();
showMessage(uniqueConstraint, FacesMessage.SEVERITY_ERROR);
e.printStackTrace();
}

Active directory Change password - Java

I am trying to change the password of Active directory user and get error code 65. Please see below the source code I used.
public class ADConnection {
DirContext ldapContext;
String baseName = ",CN=Users,DC=wso2,DC=test";
public ADConnection() {
try {
Hashtable ldapEnv = new Hashtable(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, "ldaps://192.168.18.xx:636");
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrator"
+ baseName);
ldapEnv.put(Context.SECURITY_CREDENTIALS, "xxxxxx");
ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
ldapContext = new InitialDirContext(ldapEnv);
} catch (Exception e) {
System.out.println(" bind error: " + e);
e.printStackTrace();
System.exit(-1);
}
}
public void updatePassword(String username, String password) {
try {
String quotedPassword = "\"" + password + "\"";
char unicodePwd[] = quotedPassword.toCharArray();
byte pwdArray[] = new byte[unicodePwd.length * 2];
for (int i = 0; i < unicodePwd.length; i++) {
pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8);
pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff);
}
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("UnicodePwd", pwdArray));
ldapContext.modifyAttributes("cn=" + username + baseName, mods);
//ldapContext.modifyAttributes("cn=" + username, mods);
} catch (Exception e) {
System.out.println("update password error: " + e);
System.exit(-1);
}
}
public static void main(String[] args) {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// the keystore that holds trusted root certificates
System.setProperty("javax.net.ssl.trustStore", "client-truststore.jks");
//System.setProperty("javax.net.debug", "all");
ADConnection adc = new ADConnection();
adc.updatePassword("admin", "pass#word3");
}
}
I used the code from following link.
http://blogs.msdn.com/b/alextch/archive/2012/05/15/how-to-set-active-directory-password-from-java-application.aspx
What is the wrong with this ?
Thanks

loading image to jsp (struts2) from database

I have problem with loading image from database to jsp view. It looks like action are execute but stop in middle.
I log when execute() method start and when its end. In log file i can see start this method but there are no end.
I have action:
public class ShowImageAction extends BaseAction {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(ShowImageAction.class);
private int id;
public String execute() {
LOG.info("Enter execute()");
MessageBean messageBean = (MessageBean) sessionParameters
.get(SessionParameters.BANNER_EDIT);
IFiles filesEJB = EJBLocator.getFiles();
if (messageBean != null) {
id = messageBean.getBannerId();
}
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
bytes = FileUtils.readFileToByteArray(file.getImage());
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
LOG.info("Exit execute()");
return NONE;
}
jsp:
<div class="OneFilteringRow">
Podgląd<br />
<img src="/ebok-bm/ShowImageAction" alt="Podgląd banera" />
</div>
struts.xml
<action name="ShowImageAction"
class="pl.bm.action.content.ShowImageAction">
</action>
Problem was in:
FileBean file = filesEJB.file(id);
I get bytes from database and try to save it to tmpFile. Now I get bytes and writes them to a temporary file and immediately transmit it to the action and everything is ok.
Now I have:
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
**bytes = file.getImage();**
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
}
Switch to your own result implements Result class and write output here.Other in struts.xmlaction result type specified own with approx mate parameters.
refer:generate own image as action result

Resources