Exception when saving a result - java

I am developping J2EE application with appfuse , i have a webform called easyVolAction that contain a method search() I need to save the result of search method in database but and an excpetion is generated when clicking in the action search :NullPointerException in object trajet .I created TrajetDaoHibernate:
public TrajetDaoHibernate() {
super(TrajetModel.class);
}
/**
* {#inheritDoc}
*/
#SuppressWarnings("unchecked")
public List<TrajetModel> getTrajet() {
Session session = getSessionFactory().getCurrentSession();
Query qry = session.createQuery("from TrajetModel u order by upper(u.id)");
return qry.list();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) {
if (log.isDebugEnabled()) {
log.debug("user's id: " + trajet.getId());
}
Session session = getSessionFactory().getCurrentSession();
session.saveOrUpdate(trajet);
// necessary to throw a DataIntegrityViolation and catch it in UserManager
session.flush();
return trajet;
}
#Override
public TrajetModel save(TrajetModel trajet) {
return this.saveTrajet(trajet);
}
and TrajetDao:
public interface TrajetDao extends GenericDao {
List<TrajetModel> getTrajet();
TrajetModel saveTrajet(TrajetModel trajet);
}
and trajetManager:
#Service("trajetManager")
public class TrajetModelImpl extends GenericManagerImpl<TrajetModel, Long> implements TrajetManager {
private TrajetDao trajetDao;
#Autowired
public void setTrajetModelDao(TrajetDao trajetDao) {
this.dao = trajetDao;
this.trajetDao = trajetDao;
}
/**
* {#inheritDoc}
*/
public TrajetModel getTrajet(String trajetId) {
return trajetDao.get(new Long(trajetId));
}
/**
* {#inheritDoc}
*/
public List<TrajetModel> getTrajet() {
return trajetDao.getAllDistinct();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) throws TrajetExistsException {
try {
return trajetDao.saveTrajet(trajet);
} catch (DataIntegrityViolationException e) {
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
} catch (JpaSystemException e) { // needed for JPA
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
}
}
}
finnaly the action where i declare the search method:
public String recherche() throws IOException, TrajetExistsException {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
// String url1 =
// FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("hidden");
String departAller = request.getParameter("easyVolRobot:villeDepart");
String arriveeAller = request.getParameter("easyVolRobot:villeArrivee");
String jourAller = request.getParameter("easyVolRobot:jourDep");
String moisAller = request.getParameter("easyVolRobot:dateDep");
String jourRetour = request.getParameter("easyVolRobot:jourDep");
String moisRetour = request.getParameter("easyVolRobot:dateArr");
String jourAllerPlus1 = jourAller + 1;
parametre = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAller + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
parametre1 = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAllerPlus1 + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
String response = sendGetRequest(url, parametre);
// insert();
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(
"/data/crawl/root/siteSNCF.html"));
out.print(response);
} finally {
if (out != null)
out.close();
}
// tableau de resultats des trajets
List<TrajetModel> listTrajets = new ArrayList<TrajetModel>();
// trajet
//TrajetModel trajet = new TrajetModel();
File input = new File("/data/crawl/root/siteSNCF.html");
Document doc = Jsoup.parse(input, "UTF-8",
"http://www.easyvols.org/france-voyage");
for (Element vol : doc.select("div.vols")) {
//trajet = new TrajetModel();
for (Element allerRetour : vol.select("div.aller-retour")) {
Elements aeroport = allerRetour.select("div.aeroport");
System.out.println(aeroport.text());
Elements depart = allerRetour.select("div.depart");
Elements arrive = allerRetour.select("div.arrivee");
Elements date = allerRetour.select("div.date");
trajet.setNom(aeroport.text());
trajet.setVilleDepart(depart.text());
trajet.setVilleArrive(arrive.text());
trajet.sethArrive(12);
trajet.sethDepart(11);
trajet.sethReqt(14);
}
Elements prix2 = vol.select("div.tarif");
trajet.setPrice(prix2.text());
trajet = trajetManager.saveTrajet(trajet);
System.out.println(trajet);}
return"mainMenu";
}

why you comment this line out?
//TrajetModel trajet = new TrajetModel();
I see no other line where you create the TrajetModel.
If that object is not initiated you get the NPE here:
trajet.setNom(aeroport.text());

Related

WildFly 13 migration - Only session and message-driven beans with bean-managed transaction demarcation are allowed to access UserTransaction

I have an "XAManager" class that I'm using for a JCA component inside WildFly 13.
In the standalone-full.xml the resource adapter in question is defined as so:
...
<resource-adapter id="myTest.ear#LuceneConnector-ra-impl-0.1.0.rar">
<archive>
myTest.ear#LuceneConnector-ra-impl-0.1.0.rar
</archive>
<transaction-support>XATransaction</transaction-support>
<connection-definitions>
<connection-definition class-name="com.impl.LuceneManagedConnectionFactory" jndi-name="java:jboss/eis/LuceneConnector" enabled="true" use-java-context="true" pool-name="LuceneConnection" use-ccm="true">
<xa-pool>
<min-pool-size>0</min-pool-size>
<max-pool-size>10</max-pool-size>
<prefill>false</prefill>
<use-strict-min>false</use-strict-min>
<flush-strategy>FailingConnectionOnly</flush-strategy>
<pad-xid>false</pad-xid>
<wrap-xa-resource>true</wrap-xa-resource>
</xa-pool>
<security>
<application/>
</security>
</connection-definition>
</connection-definitions>
</resource-adapter>
....
This class is being used in the ManagedConnection class of the JCA, being returned in the getXAResource() method:
public XAResource getXAResource()
throws ResourceException {
if (this.xaResource == null) {
this.xaResource = new LuceneXAManager(this);
}
if (LuceneManagedConnection.LOGGER.isDebugEnabled()) {
LuceneManagedConnection.LOGGER.debug("XAResource=" + this.xaResource);
}
return this.xaResource;
}
The class definition is as follows:
public class LuceneXAManager
implements XAResource {
static final String _CVS = "$Revision: 1.12 $";
private static final Logger LOGGER = Logger.getLogger(IndexWriter.class);
private LuceneManagedConnection lmc = null;
// private final CACClientLocal cacClientLocal = null;
// private final CACCommunityLocal cacCommunityLocal = null;
public LuceneXAManager(final LuceneManagedConnection lmc) {
this.lmc = lmc;
}
/**
* {#inheritDoc}
*/
public void commit(final Xid xid, final boolean arg1)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("commit transaction : " + xid + " int " + arg1);
}
List<LuceneDocumentTransferWrapper> tasks = this.lmc.getLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
if (tasks != null) {
TransactionManager tm = null;
Transaction tx = null;
try {
InitialContext ctx = new InitialContext();
tm = (TransactionManager)ctx.lookup("java:jboss/TransactionManager");
tx = tm.suspend();
UserTransaction ut = (UserTransaction)ctx.lookup("java:jboss/UserTransaction");
ut.begin();
for (LuceneDocumentTransferWrapper wrapper : tasks) {
String operation = wrapper.getCommand();
Object dataObject = wrapper.getDataObject();
IndexWriter writer = null;
if (wrapper.getCommunityId() != null) {
if (LuceneManagedConnection.DO_RECREATE_INDEX.equals(operation)) {
IndexWriterManager.createNewVNIndexFor(this.loadCommunity(wrapper.getCommunityId()));
continue;
} else {
writer = IndexWriterManager.getVNWriterFor(wrapper.getCommunityId());
if (writer == null) {
writer = IndexWriterManager.getVNWriterFor(this.loadCommunity(wrapper.getCommunityId()));
}
}
if (writer == null) {
throw new IllegalArgumentException("Failed to get index writer for community " + wrapper.getCommunityId());
}
} else if (wrapper.getClientId() != null) {
if (LuceneManagedConnection.DO_RECREATE_INDEX.equals(operation)) {
IndexWriterManager.createNewIndexFor(this.loadClient(wrapper.getClientId()));
continue;
} else {
writer = IndexWriterManager.getWriterFor(wrapper.getClientId());
if (writer == null) {
writer = IndexWriterManager.getWriterFor(this.loadClient(wrapper.getClientId()));
}
}
if (writer == null) {
throw new IllegalArgumentException("Failed to get index writer for client " + wrapper.getClientId());
}
} else {
throw new IllegalArgumentException("Have no clientId or communityId");
}
if (LuceneManagedConnection.DO_DELETE_DOCUMENTS.equals(operation)) {
List<Long> documentIds = (List<Long>)dataObject;
writer.deleteDocuments(documentIds);
} else if (LuceneManagedConnection.DO_INDEX_DOCUMENT.equals(operation)) {
Document document = (Document)dataObject;
writer.addDocument(document);
} else if (LuceneManagedConnection.DO_UPDATE_INDEX.equals(operation)) {
Document document = (Document)dataObject;
if (Document.DOCUMENT_STATUS_ACTIVE.equals(document.getStatus())
|| Document.DOCUMENT_STATUS_WAITING.equals(document.getStatus())
|| Document.DOCUMENT_STATUS_OUTDATED.equals(document.getStatus())) {
writer.updateDocument(document, null);
} else {
writer.deleteDocument(document);
}
} else if (LuceneManagedConnection.DO_INDEX_CONTAINER.equals(operation)) {
Container container = (Container)dataObject;
writer.deleteContainer(container.getRfid());
writer.addContainer(container);
} else {
throw new IllegalArgumentException(" Wrong command " + operation);
}
}
ut.commit();
} catch (Exception e) {
LuceneXAManager.LOGGER.error("Failed to handle commit for transaction " + xid, e);
HashSet<Long> failedDocuments = new HashSet<Long>();
for (LuceneDocumentTransferWrapper wrapper : tasks) {
failedDocuments.clear();
if (LuceneManagedConnection.DO_DELETE_DOCUMENTS.equals(wrapper.getCommand())) {
failedDocuments.addAll((List)wrapper.getDataObject());
} else if (LuceneManagedConnection.DO_INDEX_DOCUMENT.equals(wrapper.getCommand())) {
failedDocuments.add(((Document)wrapper.getDataObject()).getId());
} else if (LuceneManagedConnection.DO_UPDATE_INDEX.equals(wrapper.getCommand())) {
failedDocuments.add(((Document)wrapper.getDataObject()).getId());
}
for (Long id : failedDocuments) {
LuceneXAManager.LOGGER.error("Possible Lucene index corruption - failed to '" + wrapper.getCommand() + "' document (id=" + id
+ ")");
}
}
throw new XAException(XAException.XAER_RMFAIL);
} finally {
try {
if (tm != null && tx != null) {
tm.resume(tx);
}
} catch (Exception e) {
LuceneXAManager.LOGGER.error("Error while close resume session", e);
}
this.lmc.removeLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
}
}
}
/**
* {#inheritDoc}
*/
public void end(final Xid xid, final int arg1)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("end transaction : " + xid);
}
}
/**
* {#inheritDoc}
*/
public void forget(final Xid xid)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("forget transaction : " + xid);
}
this.lmc.removeLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
}
/**
* {#inheritDoc}
*/
public int getTransactionTimeout()
throws XAException {
return 0;
}
/**
* {#inheritDoc}
*/
public boolean isSameRM(final XAResource arg0)
throws XAException {
return false;
}
/**
* {#inheritDoc}
*/
public int prepare(final Xid xid)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("prepare transaction : " + xid);
}
List<LuceneDocumentTransferWrapper> tasks = this.lmc.getLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
List<Long> clientWriter = new ArrayList<Long>();
List<Long> communityWriter = new ArrayList<Long>();
if (tasks != null) {
for (LuceneDocumentTransferWrapper wrapper : tasks) {
if (wrapper.getCommunityId() != null) {
if (!communityWriter.contains(wrapper.getCommunityId())) {
communityWriter.add(wrapper.getCommunityId());
}
} else {
if (!clientWriter.contains(wrapper.getClientId())) {
clientWriter.add(wrapper.getClientId());
}
}
}
}
TransactionManager tm = null;
try {
InitialContext ctx = new InitialContext();
tm = (TransactionManager)ctx.lookup(CACBean.JDNI_TX_MANAGER);
tm.suspend();
UserTransaction ut = (UserTransaction)ctx.lookup(CACBean.JDNI_USERTRANACTION);
ut.begin();
for (Long clientId : clientWriter) {
IndexWriter writer = IndexWriterManager.getWriterFor(clientId);
if (writer == null) {
if (IndexWriterManager.getWriterFor(this.loadClient(clientId)) == null) {
throw new IllegalArgumentException("Failed to get index writer for client " + clientId);
}
}
}
for (Long communityId : communityWriter) {
IndexWriter writer = IndexWriterManager.getVNWriterFor(communityId);
if (writer == null) {
if (IndexWriterManager.getVNWriterFor(this.loadCommunity(communityId)) == null) {
throw new IllegalArgumentException("Failed to get index writer for community " + communityId);
}
}
}
ut.commit();
} catch (Exception e) {
LuceneXAManager.LOGGER.error("Failed to handle prepare for transaction " + xid, e);
throw new XAException(XAException.XAER_RMFAIL);
} finally {
// try {
// if (tm != null && tx != null) {
// tm.resume(tx);
// }
// } catch (Exception e) {
// LuceneXAManager.LOGGER.warn("Error while close resume session", e);
// }
}
return XAResource.XA_OK;
}
/**
* {#inheritDoc}
*/
public Xid[] recover(final int arg0)
throws XAException {
return null;
}
/**
* {#inheritDoc}
*/
public void rollback(final Xid xid)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("rollback transaction : " + xid);
}
this.lmc.removeLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
}
/**
* {#inheritDoc}
*/
public boolean setTransactionTimeout(final int arg0)
throws XAException {
return false;
}
/**
* {#inheritDoc}
*/
public void start(final Xid arg0, final int arg1)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("start transaction : " + arg0 + " int " + arg1);
}
}
private Client loadClient(final Long clientId)
throws RemoteException, CreateException, NamingException, CACException {
....
return client;
}
private Community loadCommunity(final Long communityId)
throws RemoteException, CreateException, NamingException, CACException {
....
return community;
}
}
The problem I'm having is that when trying to get the UserTransaction via JNDI I get Caused by: javax.naming.NameNotFoundException: UserTransaction [Root exception is java.lang.IllegalStateException: WFLYEJB0137: Only session and message-driven beans with bean-managed transaction demarcation are allowed to access UserTransaction]
I tried annotating my class with #Stateless and #TransactionManagement(TransactionManagementType.BEAN) to get over this issue but to no use.
I've also tried injecting the UserTransaction via #Inject UserTransaction but in this case the UserTransaction is null.
Any ideas ?

paging in Java for a lookup

I am trying to implement paging in an already running application, it works like mongodb where you get a query with bunch of parameters like
searchConditions ,limit( how many docs you want), skip ( skip these many docs)
and so on
and the response is back in json my task is to generate the previous and next link to the query that means previous page and the next page as per query
I came up with a method below
public Paging generateLink(RequestFilter filter) {
int prev_skip;
int prev_limit;
String pagePrev = "";
String pageNext = "";
int next_skip;
int next_limit;
String searchCondition = JsonUtils.toSimpleJsonString(filter.getSearch());
String url = "http://isgswmdi1n1.nam.nsroot.net:7014/account-search/rest/api/v1/pmm";
//properties.getProperty("paging.link");
System.out.println(url);
Paging pagingOption = new Paging();
Result result = new Result();
int count = luceneSearchService.searchCount(filter);
try {
if (count > 1) {
if (filter.getSkip() > 0) {
prev_skip = Math.max((filter.getSkip() - 1), 0);
prev_limit = filter.getLimit();
pagePrev = url + "?search=" + searchCondition + "&skip=" + prev_skip + "$limit=" + prev_limit;
} else{
result.setPaging(null);
return null;
}
if (count > (filter.getLimit() + filter.getSkip())) {
next_skip = (filter.getSkip() + filter.getLimit());
next_limit = filter.getLimit();
pageNext = url + "?search=" + searchCondition + "&skip=" + next_skip + "$limit=" + next_limit;
} else{
result.setPaging(null);
return null;
}
pagingOption.setPagePrev(pagePrev);
pagingOption.setPageNext(pageNext);
result.setPaging(pagingOption);
}
return pagingOption;
} catch (NullPointerException n)
{
n.printStackTrace();
return pagingOption;
}
}
call to generateLink method
return Result.ok(resultRow, generateLink(filter));
the ok response method in the Result class
public static Result ok(List<ResultRow> resultRows, Paging paging) {
if (paging != null) {
return new Result(resultRows, 200, "Completed", paging);
} else
return new Result(resultRows, 200, "Completed");
}
Underlying paging class
public class Paging implements Serializable {
public String getPagePrev() {
return pagePrev;
}
public void setPagePrev(String pagePrev) {
this.pagePrev = pagePrev;
}
#JsonProperty("pagePrev")
private String pagePrev;
public String getPageNext() {
return pageNext;
}
public void setPageNext(String pageNext) {
this.pageNext = pageNext;
}
#JsonProperty("pageNext")
private String pageNext;
}
but my test method is failing
#Test
public void search_allFilterParamsAreDefined_hp() throws Exception {
// given
Map<String, Serializable> searchConditions = singletonMap("shortName", "GO");
List<String> returnFields = asList("shortname", "gfcid");
String returnFieldsStr = returnFields.stream().collect(joining(","));
RequestFilter filter = RequestFilter.create(searchConditions, returnFieldsStr, 5, 10, true);
int resultSize = 20;
List<ResultRow> searchResult = getSearchResult(resultSize);
when(luceneSearchService.search(filter)).thenReturn(searchResult);
when(luceneSearchService.searchCount(filter)).thenReturn(resultSize);
// do
Result result = searchCoordinator.search(filter);
// verify
assertEquals(searchResult, result.getRows());
assertReturnFields(returnFields, result.getRows());
assertNotNull(result.getPaging());
Map<String, String> nextParams = getQueryParams(result.getPaging().getPageNext());
assertParam(nextParams, "search", toSimpleJsonString(searchConditions));
assertParam(nextParams, "skip", "15");
assertParam(nextParams, "limit", "10");
}

How do I open a TCSession?

I'm working with Teamcenter and Catia via the Java SOA libraries. I'm running into an issue where the demo code appears broken and I can't find a good example or documentation to work towards. The following code results in a null value exception. Specifically the line "session = PortalContext.getContext().getSession();" is where I'm crashing.
package com.ebsolutions.catiman.actions;
import java.io.File;
import java.io.RandomAccessFile;
/*
* Tc java classes
*/
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentRevisionRuleType;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
/*
* Catia integration java classes
*/
import com.ebsolutions.catiman.ErrorWarningMessages;
import com.ebsolutions.catiman.PortalContext;
import com.ebsolutions.catiman.commands.TClassUserLUSCommand;
/**
* Sample file.
* This class is not launched by the CATIAV5 integration
*
* #date 02/06/2008
*/
public class SampleIndependentSilentLUS
{
/**
* Current TC session: needed to access Tc server (service.call)
* null value is not allowed.
*/
protected TCSession session = null;
/**
* This flag defines wether the LUS should be performed in silent mode or not
*/
protected boolean is_silent[];
/**
* title of the messages
*/
private String _title = "Sample Independent SilentLUS";
/**
* components that contains the assembly to LUS.
*/
private TCComponentItem[] item = null;
private TCComponentItemRevision[] item_revision = null;
private TCComponentDataset[] part_dataset = null;
private TCComponentDataset[] product_dataset = null;
private TCComponentDataset[] drawing_dataset = null;
private TCComponentForm[] other = null;
private TCComponentBOMWindow bom_window[] = null;
/**
* The constructor.
*/
public SampleIndependentSilentLUS()
{
/* try to find the TCSession
note: this is not the only way to retrieve the TCSession. */
session = PortalContext.getContext().getSession();
}
/* --------------------------------------------------------------------- */
/*
* Sample main function
* #date 02/06/2008
*/
public void customerProcess() {
showInformationMessage("START of silent LUS");
TClassUserLUSCommand silent_lus_command = null;
/*
* example of searching items to LUS
*/
int return_value = findItemToLUS();
if (return_value < 0)
{
/* Unable to find any item to LUS */
return;
}
/**
* Initialize the API
*/
silent_lus_command = new TClassUserLUSCommand(session);
/*
* API: LUS process.
* call the "executeLUS" function
*/
/******* Item ********/
try
{
if (item[0] != null)
{
silent_lus_command.executeLUS(item[0], is_silent[0]);
showInformationMessage("pause in silent LUS after Item");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (1) Exception : " + ex);
}
/******* Item Revision ********/
try
{
if (item_revision[1] != null)
{
silent_lus_command.executeLUS(item_revision[1], is_silent[1]);
showInformationMessage("pause in silent LUS after Item_rev");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (2) Exception : " + ex);
}
/******* bom window ********/
try
{
if (bom_window[2] != null)
{
silent_lus_command.executeLUS(bom_window[2], is_silent[2]);
showInformationMessage("pause in silent LUS after bom_widow");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (3) Exception : " + ex);
}
/******* CATPart dataset ********/
try
{
if (part_dataset[3] != null)
{
silent_lus_command.executeLUS(part_dataset[3], is_silent[3]);
showInformationMessage("pause in silent LUS after CATPart");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (4) Exception : " + ex);
}
/******* CATProduct dataset ********/
try
{
if (product_dataset[4] != null)
{
silent_lus_command.executeLUS(product_dataset[4], is_silent[4]);
showInformationMessage("pause in silent LUS after CATProduct");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (5) Exception : " + ex);
}
/******* CATDrawing dataset ********/
try
{
if (drawing_dataset[5] != null)
{
silent_lus_command.executeLUS(drawing_dataset[5], is_silent[5]);
showInformationMessage("pause in silent LUS after CATDrawing");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (6) Exception : " + ex);
}
/******* other dataset ********/
try
{
if (other[6] != null)
{
silent_lus_command.executeLUS(other[6], is_silent[6]);
showInformationMessage("pause in silent LUS ");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (7) Exception : " + ex);
}
silent_lus_command.stopProcess();
}
/**
* is used to display an Error message
* #param i_msg (I) the message to be displayed
*/
private void showErrorMessage(final String i_msg)
{
ErrorWarningMessages.showErrorMessage(i_msg, _title);
}
/**
* is used to display an Information message
* #param i_msg (I) the message to display
*/
private void showInformationMessage(final String i_msg)
{
ErrorWarningMessages.showInformationMessage(i_msg, _title);
}
/**
* Sample of searching item to LUS.
* read the query.txt file that contains the item_id, item_rev_id and silent mode of the selected item
* The first line contains the number of assembly to LUS
* Then, for each assembly, we need 3 lines : item_id, item_rev_id and silent_mode
* example :
* 2
* 000010
* A
* true
* 000020
* B
* false
*/
protected int findItemToLUS()
{
String item_id = null;
String item_rev_id = null;
int return_value = 0;
int nb_assy = 0;
RandomAccessFile reader = null;
File file = null;
try
{
String file_path = "c:\\catiman_tmp\\tmp\\query.txt";
file = new File(file_path);
reader = new RandomAccessFile(file, "r");
nb_assy = Integer.valueOf(reader.readLine()).intValue();
is_silent = new boolean[nb_assy];
item = new TCComponentItem[nb_assy];
item_revision = new TCComponentItemRevision[nb_assy];
part_dataset = new TCComponentDataset[nb_assy];
product_dataset = new TCComponentDataset[nb_assy];
drawing_dataset = new TCComponentDataset[nb_assy];
other = new TCComponentForm[nb_assy];
bom_window = new TCComponentBOMWindow[nb_assy];
}
catch (Exception ex)
{
showErrorMessage("error 0 - " + ex);
return_value = -1;
}
for (int i = 0 ; i < (nb_assy) ; i++)
{
try
{
item_id = reader.readLine();
item_rev_id = reader.readLine();
is_silent[i] = Boolean.valueOf(reader.readLine()).booleanValue();
// search item name item_id
TCComponentItemType it = (TCComponentItemType)(session.getTypeComponent("Item"));
item[i] = it.find(item_id);
if (item[i] == null)
{
showErrorMessage("Error : item <" + item_id + ">not found");
return_value = -1;
}
else
{
// the item was found, search the correction item revision
AIFComponentContext[] revisions = item[i].getChildren();
TCComponentItemRevision revision_component = null;
for (int j = 0; j < revisions.length; j++)
{
InterfaceAIFComponent component = revisions[j].getComponent();
if (component instanceof TCComponentItemRevision)
{
revision_component = (TCComponentItemRevision) component;
if (revision_component.getProperty("item_revision_id").equals(item_rev_id))
{
item_revision[i] = revision_component;
break;
}
}
}
if (item_revision[i] == null)
{
showErrorMessage("Error : Item revision [" + item_rev_id + "] doesn't exist for item [" + item_id + "]");
return_value = -1;
}
else
{
// create the BOMWindow with the item revision previously found
TCComponentBOMWindowType type = (TCComponentBOMWindowType)session.getTypeComponent("BOMWindow");
TCComponentRevisionRuleType rule = (TCComponentRevisionRuleType)session.getTypeComponent("RevisionRule");
bom_window[i] = type.create(rule.getDefaultRule());
/* Define the BOMWindow top line */
TCComponentBOMLine top_line = bom_window[i].setWindowTopLine(item[i], item_revision[i], null, null);
}
}
}
catch (Exception ex)
{
showErrorMessage("error 1 - " + ex);
return_value = -1;
}
// search for a dataset (CATPart or CATProduct and/or CATDrawing)
try
{
int nb = item_revision[i].getChildrenCount();
if (nb > 0)
{
AIFComponentContext[] aif_comp_cont = item_revision[i].getChildren();
for (int j = 0 ; j < nb ; j++)
{
InterfaceAIFComponent int_aif_comp = aif_comp_cont[j].getComponent();
if (int_aif_comp.getType().equals("CATPart"))
{
part_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("CATProduct"))
{
product_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("CATDrawing"))
{
drawing_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("ItemRevision Master"))
{
other[i] = (TCComponentForm)int_aif_comp;
}
}
}
}
catch (Exception ex)
{
showErrorMessage("error 2 - " + ex);
return_value = -1;
}
}
try
{
reader.close();
}
catch (Exception ex)
{
showErrorMessage("error 3 - " + ex);
}
return return_value;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Lets try this");
SampleIndependentSilentLUS test = new SampleIndependentSilentLUS();
//test.customerProcess();
}
}
There are two ways to get TCSession.
1) If you writing a Rich-Client Plugin
//numTry - number of attemts
private static TCSession getCurrentSession(int numTry) throws Exception {
try {
TCSession session = null;
ISessionService iss=null;
int numtry=numTry;
while (iss==null && numtry>0) {
iss = AifrcpPlugin.getSessionService();
numtry--;
}
session=(TCSession)iss.getSession("com.teamcenter.rac.kernel.TCSession");
return session;
}
catch (Exception ex) {
throw ex;
}
}
2) If you writing a stand-alone application, using SOA to work with Teamcenter API.
In this case, you need to connect teamcenter first. View "HelloTeamcenter" example in documentation for details.
did you get a solution for this?
SampleIndependentSilentLUS is a very good way of automating LUS process.but i prefer using the other class(SampleSilentLUS ) that can be called from command line because TCIC will automatically provide a TCSession
the session object you get from SOA(com.teamcenter.services.strong.core._2008_06.Session) is not compatible with RAC Session(com.teamcenter.rac.TCSession).
but if you use loose services(com.teamcenter.services.loose.core), i think you can simply typecast to TCSession

wrapper class is it a design pattern

i'm new to design pattern , and now i'm working on an open ware code : so i'm trying to understand the architecture of the code : layers , used design pattern ...
So i found the a package containing classes named EntityWrapper.java here's an example :
The wrapper class :
package org.objectweb.salome_tmf.api.data;
/**
* #author marchemi
*/
public class ActionWrapper extends DataWrapper{
String awaitedResult;
int orderIndex;
int idTest;
/**
* #return Returns the orderIndex.
*/
public int getOrderIndex() {
return orderIndex;
}
/**
* #param orderIndex The orderIndex to set.
*/
public void setOrderIndex(int orderIndex) {
this.orderIndex = orderIndex;
}
/**
* #return Returns the waitedResult.
*/
public String getAwaitedResult() {
return awaitedResult;
}
/**
* #param waitedResult The waitedResult to set.
*/
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
/**
* #return Returns the idTest.
*/
public int getIdTest() {
return idTest;
}
/**
* #param idTest The idTest to set.
*/
public void setIdTest(int idTest) {
this.idTest = idTest;
}
}
The entity class:
package org.objectweb.salome_tmf.data;
import java.io.File;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import org.objectweb.salome_tmf.api.Api;
import org.objectweb.salome_tmf.api.ApiConstants;
import org.objectweb.salome_tmf.api.Util;
import org.objectweb.salome_tmf.api.data.ActionWrapper;
import org.objectweb.salome_tmf.api.data.FileAttachementWrapper;
import org.objectweb.salome_tmf.api.data.ParameterWrapper;
import org.objectweb.salome_tmf.api.data.SalomeFileWrapper;
import org.objectweb.salome_tmf.api.data.UrlAttachementWrapper;
import org.objectweb.salome_tmf.api.sql.ISQLAction;
public class Action extends WithAttachment {
static ISQLAction pISQLAction = null;
private String awaitedResult;
public String getAwaitedResult() {
return awaitedResult;
}
public void setAwaitedResult(String awaitedResult) {
this.awaitedResult = awaitedResult;
}
private int orderIndex;
private Hashtable parameterHashTable;
private Test pTest = null;
public Action(Test pTest, String name, String description) {
super(name, description);
awaitedResult = "";
orderIndex = 0;
parameterHashTable = new Hashtable();
this.pTest = pTest;
if (pISQLAction == null){
pISQLAction = Api.getISQLObjectFactory().getISQLAction();
}
}
public Action(ActionWrapper pAction, Test pTest) {
this(pTest, pAction.getName(), pAction.getDescription());
awaitedResult = pAction.getAwaitedResult();
orderIndex = pAction.getOrderIndex();
idBdd = pAction.getIdBDD();
}
public Action(Action pAction, Test pTest) {
this(pTest, pAction.getNameFromModel(), pAction.getDescriptionFromModel());
awaitedResult = pAction.getAwaitedResultFromModel();
} // Fin du constructeur Action/1
protected void reloadBaseFromDB() throws Exception {
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
ActionWrapper pActionWrapper = pISQLAction.getActionWrapper(idBdd);
awaitedResult = pActionWrapper.getAwaitedResult();
orderIndex = pActionWrapper.getOrderIndex();
name = pActionWrapper.getName();
description = pActionWrapper.getDescription();
}
public void reloadFromDB(boolean base, Hashtable paramsInModel, boolean attach)
throws Exception {
int transNuber = -1;
try {
transNuber = Api.beginTransaction(101, ApiConstants.LOADING);
if (base){
reloadBaseFromDB();
}
reloadUsedParameterFromDB(paramsInModel);
if (attach){
reloadAttachmentDataFromDB(false);
}
Api.commitTrans(transNuber);
} catch (Exception e){
Api.forceRollBackTrans(transNuber);
throw e;
}
}
public void clearCache() {
/* TODO ClearAttachement */
}
/******************************************************************************/
/** ACCESSEURS ET
MUTATEURS ***/
/******************************************************************************/
public String getAwaitedResultFromModel() {
return awaitedResult;
}
public void setAwaitedResultInModel(String string) {
awaitedResult = string;
}
public int getOrderIndexFromModel() {
return orderIndex;
}
public void setOrderIndex(int i) {
orderIndex = i;
}
public Test getTest(){
return pTest;
}
/////////////////////////////// Basic Operation /////////////////////////
/* Used by Manuel Test */
void addInDB(Test pTest) throws Exception {
//boolean needUpdate = false;
if (isInBase()) {
throw new Exception("Action " + name + " is already in BDD");
}
if (!pTest.isInBase()){
throw new Exception("Test " + pTest.getNameFromModel() + " is not in BDD");
}
int id = pISQLAction.insert(pTest.getIdBdd(), name, description, awaitedResult);
setIdBdd(id);
orderIndex = pISQLAction.getActionWrapper(id).getOrder();
/*if (orderIndex != rowCount){
needUpdate = true;
}
return needUpdate;*/
Project.pCurrentProject.notifyChanged( ApiConstants.INSERT_ACTION ,this);
}
/* Used by Manuel Test */
void addInModel(Test pTest){
this.pTest = pTest;
}
/* Used by Manuel Test */
void addInDBAndModel(Test pTest)throws Exception {
//boolean res;
addInDB(pTest);
addInModel(pTest);
//return res;
}
public void updateInDB(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.update(idBdd, newActionName, newActionDesc, newActionResAttendu );
Project.pCurrentProject.notifyChanged( ApiConstants.UPDATE_ACTION ,this, new String(name), newActionName);
}
public void updateInModel(String newActionName, String newActionDesc, String newActionResAttendu) {
setNameInModel(newActionName);
updateDescriptionInModel(newActionDesc);
setAwaitedResultInModel(newActionResAttendu);
}
public void updateInDBAndModel(String newActionName, String newActionDesc, String newActionResAttendu) throws Exception {
updateInDB(newActionName, newActionDesc, newActionResAttendu);
updateInModel(newActionName, newActionDesc, newActionResAttendu);
}
public void updateInDBAndModel(String newName, String newDesc) throws Exception {
updateInDB(newName, newDesc, awaitedResult);
updateInModel(newName, newDesc, awaitedResult);
}
public void updateOrderInDBAndModel(boolean inc) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
orderIndex = pISQLAction.updateOrder(idBdd, inc);
}
/* Used by Manuel Test */
void deleteInDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.delete(idBdd);
Project.pCurrentProject.notifyChanged( ApiConstants.DELETE_ACTION ,this);
}
/* Used by Manuel Test */
void deleteInModel(){
pTest=null;
parameterHashTable.clear();
clearAttachInModel();
}
/* Used by Manuel Test */
void deleteInDBAndModel() throws Exception {
deleteInDB();
deleteInModel();
}
//////////////// PARAMETERS ////////////////////////
public void setParameterHashSetInModel(HashSet set) {
parameterHashTable.clear();
for (Iterator iter = set.iterator(); iter.hasNext();) {
Parameter param = (Parameter)iter.next();
parameterHashTable.put(param.getNameFromModel(), param);
}
}
public void setParameterHashtableInModel(Hashtable table) {
parameterHashTable.clear();
parameterHashTable = table;
}
public Hashtable getCopyOfParameterHashTableFromModel(){
Hashtable copyParameter = new Hashtable();
Enumeration enumKey = parameterHashTable.keys();
while (enumKey.hasMoreElements()){
Object key = enumKey.nextElement();
copyParameter.put(key, parameterHashTable.get(key));
}
return copyParameter;
}
public void reloadUsedParameterFromDB(Hashtable parametersInModel) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] paramActionArray = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < paramActionArray.length; i++) {
Parameter param = null;
ParameterWrapper pParameterWrapper = paramActionArray[i];
if (parametersInModel != null){
param = (Parameter)parametersInModel.get(pParameterWrapper.getName());
if (param == null){
param = new Parameter(pParameterWrapper);
}
}
setUseParamInModel(param);
}
}
public void setUseParamInModel(Parameter pParam) {
parameterHashTable.put(pParam.getNameFromModel(), pParam);
if (pTest != null) {
if (pTest.getUsedParameterFromModel(pParam.getNameFromModel()) == null){
pTest.setUseParamInModel(pParam);
}
}
}
public void setUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.addUseParam(idBdd,paramId);
}
public void setUseParamInDBAndModel(Parameter pParam) throws Exception {
//DB
setUseParamInDB(pParam.getIdBdd());
//model
setUseParamInModel(pParam);
}
public void deleteUseParamInDB(int paramId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteParamUse(idBdd, paramId);
}
public void deleteUseParamInDBAndModel(Parameter pParam) throws Exception {
deleteUseParamInDB(pParam.getIdBdd());
deleteUseParamInModel(pParam);
}
public void deleteUseParamInModel(Parameter pParam) {
// Clean Action
String newDesc = null ;
if (getDescriptionFromModel()!=null)
newDesc = clearStringOfParameter(getDescriptionFromModel(), pParam);
String newResult = null;
if (getAwaitedResultFromModel()!=null)
newResult = clearStringOfParameter(getAwaitedResultFromModel(), pParam);
description = newDesc;
awaitedResult = newResult;
Object o= parameterHashTable.remove(pParam.getNameFromModel());
Util.log("[Action->deleteUseParamInModel] Delete Use Parameter " + pParam + ", in Action " + name + " res is " +o);
}
public Parameter getParameterFromModel(String name) {
Enumeration paramList = parameterHashTable.elements();
while (paramList.hasMoreElements()){
Parameter param = (Parameter)paramList.nextElement();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public Parameter getParameterFromDB(String name) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = getParameterHashSetFromDB();
for (Iterator iter = result.iterator(); iter.hasNext(); ) {
Parameter param = (Parameter)iter.next();
if (param.getNameFromModel().equals(name)) {
return param;
}
}
return null;
}
public HashSet getParameterHashSetFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
HashSet result = new HashSet();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Vector getParameterVectorFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
Vector result = new Vector();
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
ParameterWrapper[] listParamWrapper = pISQLAction.getParamsUses(idBdd);
for (int i = 0; i < listParamWrapper.length; i++){
result.add(new Parameter(listParamWrapper[i]));
}
return result;
}
public Hashtable getParameterHashSetFromModel() {
return parameterHashTable;
}
////////////// ATTACHEMENT ///////////////////////
public void addAttachementInDB (Attachment attach )throws Exception {
if (attach instanceof FileAttachment) {
addAttachFileInDB((FileAttachment) attach);
} else {
addAttachUrlInDB((UrlAttachment) attach);
}
}
void addAttachFileInDB(FileAttachment file) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
File f = file.getLocalFile();
int id = pISQLAction.addFileAttach(idBdd,new SalomeFileWrapper(f),file.getDescriptionFromModel());
file.setIdBdd(id);
}
void addAttachUrlInDB(UrlAttachment url) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
int id = pISQLAction.addUrlAttach(idBdd, url.getNameFromModel(),url.getDescriptionFromModel());
url.setIdBdd(id);
}
public void deleteAttachementInDB(int attachId) throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
pISQLAction.deleteAttachment(idBdd, attachId);
}
public void deleteAttachementInDBAndModel(Attachment attach)throws Exception {
deleteAttachementInDB(attach.getIdBdd());
deleteAttachmentInModel(attach);
}
public Vector getAttachFilesFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
FileAttachementWrapper[] fawArray = pISQLAction.getAllAttachFile(idBdd);
Vector result = new Vector();
for(int i = 0; i < fawArray.length; i++) {
result.add(fawArray[i]);
}
return result;
}
public Vector getAttachUrlsFromDB() throws Exception {
if (!isInBase()) {
throw new Exception("Action " + name + " is not in BDD");
}
UrlAttachementWrapper[] uawArray = pISQLAction.getAllAttachUrl(idBdd);
Vector result = new Vector();
for(int i = 0; i < uawArray.length; i++) {
result.add(uawArray[i]);
}
return result;
}
//////// PROTECTED //////////////
protected String clearStringOfParameter(String prtString, Parameter pParam) {
String result = prtString;
result = result.replaceAll("[$]" + pParam.getNameFromModel() + "[$]", "");
return result;
}
public static boolean isInBase(Test pTest, String actionName) {
try {
int id = pISQLAction.getID(pTest.getIdBdd(), actionName);
if (id > 0){
return true;
}
return false;
} catch (Exception e) {
}
return false;
} // Fin de la methode isInBase/1
public boolean existeInBase() throws Exception {
if (!isInBase()) {
return false;
}
return pISQLAction.getID(pTest.getIdBdd(), name) == idBdd;
}
}
So what is the utility of the wrapper class , is it a kind of design pattern ?
I can not see, what ActionWrapper wraps, for me is just implementation of DataWrapper interface.
There 3 "kinds" of wrappers design patterns:
Facade design pattern = take a lot of classes/interfaces, do some logic inside and get out small interface. For example "Car start" encapsulate inside: open car, put key, set DVD, correct chair, ignition.
Decorator design pattern = take some class with behavior and make ability to add behaviors in run time. for example, instead of do class CarWithLCDWithDVDWithTurbo you can do: new LCDDecorator(new DVDDecorator(TurboDecorator(new car)));
Adapter design pattern = take some new interface and adapt it to some known interface.
The fact that something ends with the Wrapper word doesn´t make it a wrapper. To be a wrapper it has to wrap something. This is, it has to encapsulate one or more components, probably a whole third-party API.
There are different types of wrappers as #zzfima says. And yes, proxy could be a wrapper in some cases and also bridges could be.
Your code doesn´t encapsulate any other component and then, it is not a wrapper (at least for me)
call something "wrapper" doesn't make it a wrapper. Basically it needs to encapsulate something or wrap something, whatever you call it

java.io.IOException: Stream closed

For multiple image retrieval I am calling a PhotoHelperServlet with an anchor tag to get imageNames(multiple images) as follows
PhotoHelperServlet to get names of Images
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Getting userid from session
Image image = new Image();
image.setUserid(userid);
ImageDAO imageDAO = new ImageDAO();
try {
List<Image> imageId = imageDAO.listNames(image);
if (imageId == null) {
// check if imageId is retreived
}
request.setAttribute("imageId", imageId);
//Redirect it to home page
RequestDispatcher rd = request.getRequestDispatcher("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
catch (Exception e) {
e.printStackTrace();
}
In ImageDAO listNames() method :
public List<Image> listNames(Image image) throws IllegalArgumentException, SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
Database database = new Database();
List<Image> imageId = new ArrayList<Image>();
try {
connection = database.openConnection();
preparedStatement = connection.prepareStatement(SQL_GET_PHOTOID);
preparedStatement.setLong(1, image.getUserid());
resultset = preparedStatement.executeQuery();
while(resultset.next()) {
image.setPhotoid(resultset.getLong(1));
imageId.add(image);
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
close(connection, preparedStatement, resultset);
}
return imageId;
}
In JSP code:
<c:forEach items="${imageId}" var="imageid">
<img src="Photos/${imageid}">
</c:forEach>
In PhotoServlet doGet() method to get a photo:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String imageid = request.getPathInfo().substring(1);
if(imageid == null) {
// check for null and response.senderror
}
ImageDAO imageDAO = new ImageDAO();
try {
Image image = imageDAO.getPhotos(imageid);
if(image == null) {}
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(image.getPhoto(), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
} catch(Exception e) {
e.printStackTrace();
}
In ImageDAO getPhotos() method
public Image getPhotos(String imageid) throws IllegalArgumentException, SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
Database database = new Database();
Image image = new Image();
try {
connection = database.openConnection();
preparedStatement = connection.prepareStatement(SQL_GET_PHOTO);
preparedStatement.setString(1, imageid);
resultset = preparedStatement.executeQuery();
while(resultset.next()) {
image.setPhoto(resultset.getBinaryStream(1));
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
close(connection, preparedStatement, resultset);
}
return image;
}
In web.xml
<!-- Getting each photo -->
<servlet>
<servlet-name>Photos Module</servlet-name>
<servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Photos Module</servlet-name>
<url-pattern>/Photos/*</url-pattern>
</servlet-mapping>
<!-- Getting photo names -->
<servlet>
<servlet-name>Photo Module</servlet-name>
<servlet-class>app.controllers.PhotoHelperServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Photo Module</servlet-name>
<url-pattern>/Photo</url-pattern>
</servlet-mapping>
Question:
I am getting following Exception:
java.io.IOException: Stream closed
on this Line:
at app.controllers.PhotoServlet.doGet(PhotoServlet.java:94)
while ((length = input.read(buffer)) > 0) {
The full Exception:
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:134)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at app.controllers.PhotoServlet.doGet(PhotoServlet.java:94)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
I'd imagine that the basic code flow is laid out like follows:
try {
Get connection, statement, resultset
Use connection, statement, resultset
Get inputstream of resultset
} finally {
Close resultset, statement, connection
}
try {
Get outputstream
Use inputstream of resultset, outputstream
} finally {
Close outputstream, inputstream of resultset
}
And that the close of the ResultSet has implicitly closed the InputStream. It look like that your JDBC driver does not store the InputStream of the ResultSet fully in memory or on temp storage when the ResultSet is closed. Perhaps the JDBC driver is a bit simplistic, or not well thought designed, or the image is too large to be stored in memory. Who knows.
I'd first figure out what JDBC driver impl/version you're using and then consult its developer documentation to learn about settings which may be able to change/fix this behaviour. If you still can't figure it out, then you'd have to rearrange the basic code flow as follows:
try {
Get connection, statement, resultset
Use connection, statement, resultset
try {
Get inputstream of resultset, outputstream
Use inputstream of resultset, outputstream
} finally {
Close outputstream, inputstream of resultset
}
} finally {
Close resultset, statement, connection
}
Or
try {
Get connection, statement, resultset
Use connection, statement, resultset
Get inputstream of resultset
Copy inputstream of resultset
} finally {
Close resultset, statement, connection
}
try {
Get outputstream
Use copy of inputstream, outputstream
} finally {
Close outputstream, copy of inputstream
}
The first approach is the most efficient, only the code is clumsy. The second approach is memory inefficient when you're copying to ByteArrayOutputStream, or performance inefficient when you're copying to FileOutputStream. If the images are mostly small and do not exceed a megabyte or something, then I'd just copy it to ByteArrayOutputStream.
InputStream input = null;
OutputStream output = null;
try {
input = new BufferedInputStream(resultSet.getBinaryStream("columnName"), DEFAULT_BUFFER_SIZE);
output = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
for (int length; ((length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException ignore) {}
if (input != null) try { input.close(); } catch (IOException ignore) {}
}
Image image = new Image();
image.setPhoto(new ByteArrayInputStream(output.toByteArray()));
// ...
参考一下:
ImageLoad
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
/**
* 图片加载帮助类(自动异步加载、图片文件缓存、缓存文件管理)
*
* #author n.zhang
*
*/
public class ImageLoad {
private static final String TAG = "imageLoad";// 日志标签
private static final String TAG_REF = TAG + "Ref";
private Executor executor; // 线程池
private int defaultImageID;// 默认图片id
private Context context;// 你懂的
private HashMap<String, PathInfo> cache = new HashMap<String, PathInfo>();// URL
boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 路径信息对应表
private LinkedList<PathInfo> use = new LinkedList<PathInfo>();// 已在使用的路径信息队列
private LinkedList<PathInfo> lost = new LinkedList<PathInfo>();// 还未使用的路径信息队列
private LinkedList<PathInfo> original = new LinkedList<PathInfo>();// 初始图片路径信息队列
private int index = 0;// id下标
/**
* 图片加载工具,默认10线程下载,缓存80张图片
*
* #param context
*/
public ImageLoad(Context context) {
this(context, 10, 80, 0);
}
/**
* 图片加载工具
*
* #param context
* 你懂的
* #param threadSize
* 最大线程数
* #param maxCacheSize
* 最大缓存图片数量
* #param defaultImageID
* 默认图片id
*/
public ImageLoad(Context context, int threadSize, int maxCacheSize, int defaultImageID) {
this.context = context;
this.defaultImageID = defaultImageID;
executor = Executors.newFixedThreadPool(threadSize);
loadImagePathInfo();
// 图片信息数量不足不满最大值,以空白图片信息补足。
newImagePathInfo(maxCacheSize);
for (PathInfo pi : original) {
if (null == pi.url) {
lost.offer(pi);
} else {
use.offer(pi);
cache.put(pi.url, pi);
}
}
File dir = null;
if (sdCardExist) {
dir = new File(Environment.getExternalStorageDirectory() + "/t_image/");
} else {
dir = new File(context.getCacheDir() + "/t_image/");
}
// 如果文件存在并且不是目录,则删除
if (dir.exists() && !dir.isDirectory()) {
dir.delete();
}
// 如果目录不存在,则创建
if (!dir.exists()) {
dir.mkdir();
}
}
/**
* 路径信息
*
* #author n.zhang
*
*/
public static class PathInfo {
private int id;// 图片id 此id用于生成存储图片的文件名。
private String url;// 图片url
}
/**
* 获得图片存储路径
*
* #param url
* #return
*/
public PathInfo getPath(String url) {
PathInfo pc = cache.get(url);
if (null == pc) {
pc = lost.poll();
}
if (null == pc) {
pc = use.poll();
refresh(pc);
}
return pc;
}
/**
* #info 微博使用加载数据路径
* #author FFMobile-cuihe
* #date 2012-3-1 下午2:13:10
* #Title: getsPath
* #Description: TODO
* #param#param url
* #param#return 设定文件
* #return PathInfo 返回类型
* #throws
*/
public PathInfo getsPath(String url) {
PathInfo pc = cache.get(url);
if (null == pc) {
pc = lost.peek();
}
// if (null == pc) {
// pc = use.peek();
// refresh(pc);
// }
return pc;
}
public PathInfo getLocalPath(String url) {
PathInfo pc = cache.get(url);
if (null == pc) {
pc = lost.peek();
}
return pc;
}
/**
* 刷新路径信息(从索引中删除对应关系、删除对应的图片文件、获取一个新id)
*
* #param pc
*/
private void refresh(PathInfo pc) {
long start = System.currentTimeMillis();
File logFile = null;
try {
cache.remove(pc.url);
File file = toFile(pc);
file.delete();
logFile = file;
pc.id = index++;
pc.url = null;
} finally {
Log.d(TAG_REF, "ref time {" + (System.currentTimeMillis() - start) + "}; ref {" + logFile + "}");
}
}
/**
* 获得file对象
*
* #param pi
* 路径缓存
* #return
*/
public File toFile(PathInfo pi) {
if (sdCardExist) {
return new File(Environment.getExternalStorageDirectory() + "/t_image/" + pi.id + ".jpg");
} else {
return new File(context.getCacheDir() + "/t_image/" + pi.id + ".jpg");
}
}
/**
* 请求加载图片
*
* #param url
* #param ilCallback
*/
public void request(String url, final ILCallback ilCallback) {
final long start = System.currentTimeMillis();
final PathInfo pc = getPath(url);
File file = toFile(pc);
if (null != pc.url) {
ilCallback.seed(Uri.fromFile(file));
Log.d(TAG, "load time {" + (System.currentTimeMillis() - start) + "}; cache {" + pc.url + "} ");
} else {
pc.url = url;
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (null == msg.obj) {
ilCallback.seed(Uri.EMPTY);
Log.d(TAG, "load lost time {" + (System.currentTimeMillis() - start) + "}; network lost {"
+ pc.url + "}");
} else {
ilCallback.seed((Uri) msg.obj);
Log.d(TAG, "load time {" + (System.currentTimeMillis() - start) + "}; network {" + pc.url + "}");
}
};
};
executor.execute(new DownloadImageTask(pc, file, mHandler));
}
}
private void localRequest(String url, final ILCallback ilCallback) {
final long start = System.currentTimeMillis();
final PathInfo pc = getLocalPath(url);
File file = toFile(pc);
if (null != pc.url) {
ilCallback.seed(Uri.fromFile(file));
Log.d(TAG, "load time {" + (System.currentTimeMillis() - start) + "}; cache {" + pc.url + "} ");
}
}
public void localRequest(String url, ImageView iv) {
localRequest(url, new ImageViewCallback(iv));
}
/**
* 请求加载图片
*
* #param url
* #param iv
*/
public void request(String url, ImageView iv) {
request(url, new ImageViewCallback(iv));
}
/**
* 请求加载图片
*
* #param url
* #param iv
*/
// public void request(String url, ImageButton iv) {
// request(url, new ImageButtonCallbacks(iv));
// }
/**
* 请求加载图片
*
* #param url
* #param iv
*/
// public void request(String url, Button iv) {
// request(url, new ButtonCallbacks(iv));
// }
/**
* 请求加载图片
*
* #param url
* #param iv
*/
public void request(String url, ImageSwitcher iv) {
request(url, new ImageSwitcherCallbacks(iv));
}
/**
* 下载图片任务
*
* #author Administrator
*
*/
private class DownloadImageTask implements Runnable {
private Handler hc;
private PathInfo pi;
private File file;
public DownloadImageTask(PathInfo pi, File file, Handler hc) {
this.pi = pi;
this.file = file;
this.hc = hc;
}
public void run() {
try {
byte[] b = requestHttp(pi.url);
if (null == b) {
throw new IOException("数据为空");
}
writeFile(file, b);
use.offer(pi);
cache.put(pi.url, pi);
Message message = new Message();
message.obj = Uri.fromFile(file);
hc.sendMessage(message);
} catch (IOException e) {
Message message = hc.obtainMessage(0, Uri.EMPTY);
hc.sendMessage(message);
Log.i(TAG, "image download lost.", e);
} catch (RuntimeException e) {
Message message = hc.obtainMessage(0, Uri.EMPTY);
hc.sendMessage(message);
Log.i(TAG, "image download lost.", e);
}
}
}
private void writeFile(File file, byte[] data) throws IOException {
FileOutputStream out = new FileOutputStream(file);
try {
out.write(data);
} finally {
out.close();
}
}
private static byte[] requestHttp(String url) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
System.gc();
try {
HttpGet get = new HttpGet(url);
HttpResponse res = client.execute(get);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (200 == res.getStatusLine().getStatusCode()) {
res.getEntity().writeTo(baos);
return baos.toByteArray();
} else {
throw new IOException("httpStatusCode:" + res.getStatusLine().getStatusCode());
}
} finally {
client.getConnectionManager().shutdown();
}
}
/**
* 读取图片路径信息
*
* #return
*/
#SuppressWarnings("unchecked")
private void loadImagePathInfo() {
long start = System.currentTimeMillis();
File file = new File(context.getCacheDir() + "/imagePathCache.json");
try {
if (!file.isFile()) {
// 文件不存在。
Log.d(TAG, "path info file does not exist");
imageGc();
return;
}
StringWriter sw = new StringWriter();
char[] buf = new char[1024];
int len;
FileReader fr = new FileReader(file);
while (-1 != (len = fr.read(buf))) {
sw.write(buf, 0, len);
}
fr.close();
JSONObject json = new JSONObject(sw.toString());
Iterator<String> it = json.keys();
while (it.hasNext()) {
String key = it.next();
int id = json.getInt(key);
PathInfo pi = new PathInfo();
pi.url = key;
pi.id = id;
if (index < id) {
index = id;
}
original.add(pi);
}
// 打开文件文件缓存成功
Log.i(TAG, "load path info ok.");
} catch (IOException e) {
Log.i(TAG, "load path info lost - IOException.", e);
imageGc();
} catch (JSONException e) {
Log.i(TAG, "load path info lost - JSONException.", e);
imageGc();
} finally {
if (file.exists()) {
file.delete();
Log.d(TAG, "delete path info file");
}
Log.d(TAG, "load path info time {" + (System.currentTimeMillis() - start) + "}");
}
}
/**
* 如果路径信息加载失败,清理图片目录。
*/
private void imageGc() {
long start = System.currentTimeMillis();
try {
File dir;
if (sdCardExist) {
dir = new File(Environment.getExternalStorageDirectory() + "/t_image/");
} else {
dir = new File(context.getCacheDir() + "/t_image/");
}
if (dir.isDirectory()) {
for (File file : dir.listFiles()) {
file.delete();
// gc
Log.d(TAG_REF, "gc {" + file + "}");
}
}
} finally {
// gc 计时
Log.d(TAG_REF, "gc time {" + (System.currentTimeMillis() - start) + "}");
}
}
private void newImagePathInfo(int max_size) {
for (int i = original.size(); i < max_size; i++) {
PathInfo pc = new PathInfo();
pc.id = index++;
original.add(pc);
}
}
/**
* 保存图片路径信息(如记录,下次程序打开,可读取该记录已存图片继续可用)
*/
public void saveImagePathInfo() {
long start = System.currentTimeMillis();
try {
JSONObject json = new JSONObject();
for (PathInfo pi : use) {
try {
json.put(pi.url, pi.id);
} catch (JSONException e) {
e.printStackTrace();
}
}
File file = new File(context.getCacheDir() + "/imagePathCache.json");
try {
FileWriter fw = new FileWriter(file);
fw.write(json.toString());
fw.close();
Log.i(TAG, "image file info save ok.");
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "image file info save lost.");
file.delete();
}
} finally {
Log.d(TAG, "save time {" + (System.currentTimeMillis() - start) + "}");
}
}
/**
* 图片加载回调
*
* #author n.zhang
*
*/
public static interface ILCallback {
public void seed(Uri uri);
}
private class ImageViewCallback implements ILCallback {
public ImageViewCallback(ImageView iv) {
if (defaultImageID > 0) {
iv.setImageResource(defaultImageID);
}
this.iv = iv;
}
private ImageView iv;
public void seed(Uri uri) {
File f = new File(uri.getPath());
iv.setImageURI(Uri.parse(f.toString()));
f = null;
}
}
// private class ImageButtonCallbacks implements ILCallback {
// public ImageButtonCallbacks(ImageButton iv) {
// if (defaultImageID > 0) {
// iv.setBackgroundResource(defaultImageID);
////iv.setImageResource(defaultImageID);
// }
// this.iv = iv;
// }
//
// private ImageButton iv;
//
// public void seed(Uri uri) {
// iv.setImageURI(uri);
// }
// }
// private class ButtonCallbacks implements ILCallback {
// public ButtonCallbacks(Button iv) {
// if (defaultImageID > 0) {
// iv.setBackgroundResource(defaultImageID);
////iv.setImageResource(defaultImageID);
// }
// this.iv = iv;
// }
//
// private Button iv;
//
// public void seed(Uri uri) {
// iv.setImageURI(uri);
// }
// }
private class ImageSwitcherCallbacks implements ILCallback {
public ImageSwitcherCallbacks(ImageSwitcher iv) {
if (defaultImageID > 0) {
iv.setImageResource(defaultImageID);
}
this.iv = iv;
}
private ImageSwitcher iv;
public void seed(Uri uri) {
iv.setImageURI(uri);
}
}
}
It looks as if the problem is actually not in the code you posted. For some reason the stream input is closed. So you are probably closing the stream in image.getPhoto()

Categories

Resources