Request body empty (?) after migrating to Endpoints Framework 2.0 - java
I have a Java Google Endpoint as follows
#ApiMethod(
name="createShiftlist",
path="jeugdhuis/{websafeJeugdhuisKey}/shiftlists",
httpMethod="POST",
authenticators={FirebaseAuthenticator.class}
)
public void createShiftlist(User user, #Named("websafeJeugdhuisKey") String websafeJeugdhuisKey, ShiftlistForm shiftlistForm)
throws UnauthorizedException {
if (shiftlistForm.getStart() == null)
throw new IllegalArgumentException(shiftlistForm.getStart() + " " + shiftlistForm.getPartyName() + " " + shiftlistForm.getEnd());
if (user == null)
throw new UnauthorizedException("User is not logged in!");
if (!JukteUserAPI.isJeugdhuisAdmin(user, websafeJeugdhuisKey))
throw new UnauthorizedException("Logged in user is not an admin of the given Jeugdhuis.");
OfyService.ofy().save().entities(new Shiftlist[] {
new Shiftlist(
OfyService.factory().allocateId(Key.create(websafeJeugdhuisKey), Shiftlist.class).getId(),
websafeJeugdhuisKey, shiftlistForm.getPartyName(), shiftlistForm.getStart(), shiftlistForm.getEnd())
});
}
I use the following .js to call it.
var jukteapi = jukteapi || {};
var jukteKey = 'myKey';
function XHRBuilder(appId, apiName, version) {
this.root = "https://" + appId + ".appspot.com/_ah/api/" + apiName + "/" + version + "/";
this.params;
this.method;
this.endpoint;
this.authorizationToken;
this.onsucces;
this.get = function() {
this.method = 'GET';
return this;
};
this.post = function() {
this.method = 'POST';
return this;
};
this.delete = function() {
this.method = 'DELETE';
return this;
};
this.put = function() {
this.method = 'PUT';
return this;
}
this.path = function(endpointPath) {
this.endpoint = endpointPath;
return this;
};
this.authorizationToken = function(token) {
this.authorizationToken = token;
return this;
};
this.onsucces = function(func) {
this.onsucces = func;
return this;
};
this.addParam = function(paramName, paramValue) {
if (this.params === undefined)
this.params = new FormData();
this.params.append(paramName, paramValue);
return this;
};
this.send = function() {
var xhr = new XMLHttpRequest();
xhr.open(this.method, this.root + this.endpoint);
var self = this.onsucces;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
self(JSON.parse(xhr.responseText));
else if (xhr.readyState == 4 && xhr.status == 204)
self();
else if (xhr.readyState == 4 && xhr.status == 400)
alert(JSON.parse(xhr.responseText).error.message);
};
xhr.setRequestHeader('Authorization', 'Bearer ' + this.authorizationToken);
if (typeof this.params !== "undefined")
for (var pair of this.params.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
xhr.send(this.params);
};
}
jukteapi.http = function() {
return new XHRBuilder('jhjukte','jukte','v1')
}
jukteapi.createShiftlist = function(onsucces, name, start, end) {
firebase.auth().currentUser.getIdToken().then(function(idToken) {
jukteapi.http().post()
.path('jeugdhuis/' + jukteKey + '/shiftlists')
.authorizationToken(idToken)
.addParam('partyName', name)
.addParam('start', start + ':00')
.addParam('end', end + ':00')
.onsucces(onsucces)
.send();
});
}
This is the ShiftlistForm class.
package jukte.form;
import java.util.Date;
public class ShiftlistForm {
private String partyName;
private Date start;
private Date end;
#SuppressWarnings("unused")
private ShiftlistForm() {}
public ShiftlistForm(String partyName, Date start, Date end){
this.partyName = partyName;
this.start = start;
this.end = end;
}
public String getPartyName() {
return partyName;
}
public Date getStart() {
return start;
}
public Date getEnd() {
return end;
}
public void setPartyName(String partyName) {
this.partyName = partyName;
}
public void setStart(Date start) {
this.start = start;
}
public void setEnd(Date end) {
this.end = end;
}
}
The endpoint is called, but the variables in ShiftlistForm (start, end, partyName) are null. It worked perfectly before I migrated to 2.0 from 1.0. What is going on?
I believe you may want to try setting your Content-Type header to application/json.
Related
Xpages: send html email via java using backend document
I found this great Java Bean that allows you to send an html email including attachments via a managed java bean. It works as described when I use it directly form an Xpage. However, I would like to use this in the backend in a scheduled agent. The problem I have run into is when I try to pass a document to the java bean. The bean is expecting (I think) an XSP document, which I don't have when in the back end, so it throws an error. I thought I would just send the UNID of the document that I want and then change it so it would work with this bean, however, when I try to set the UNID I get an error: Unknown member 'setUNID' in Java class 'com.scoular.utls.Email' I am confused. Seems like this has something to do with a wrapped document, but don't understand. Here is the faces-config: <faces-config> <managed-bean> <managed-bean-name>Email</managed-bean-name> <managed-bean-class>com.scoular.utls.Email</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>debugMode</property-name> <value>true</value> </managed-property> </managed-bean> </faces-config> Here is a button I am using to test calling the method: //Need to get email document var emlView = database.getView("xpViewEmailsAll"); var emlDoc = emlView.getFirstDocument(); if (emlDoc != null) { //try{ var subject = "" var senderEmail = supEml var senderName = supNme Email.setSendTo("John"); Email.setSubject("subject"); Email.setSenderEmail("John#gmal.com"); Email.setUNID = emlDoc.getUniversalID(); Email.setSenderName("Sender"); //Email.setBackEndDocument(emlDoc); Email.setFieldName("Body"); Email.send(); //}catch(e){ //print(e.getMessage()); //} } And here is the bean: package com.scoular.utls; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.context.FacesContext; import lotus.domino.Database; import lotus.domino.Document; import lotus.domino.EmbeddedObject; import lotus.domino.MIMEEntity; import lotus.domino.MIMEHeader; import lotus.domino.NotesException; import lotus.domino.Session; import lotus.domino.Stream; import com.ibm.commons.util.NotImplementedException; import com.ibm.domino.xsp.module.nsf.NotesContext; import com.ibm.xsp.model.FileRowData; import com.ibm.xsp.model.domino.wrapped.DominoDocument; import com.ibm.xsp.model.domino.wrapped.DominoRichTextItem; import com.ibm.xsp.model.domino.wrapped.DominoDocument.AttachmentValueHolder; import com.ibm.xsp.persistence.PersistedContent; public class Email { private ArrayList<String> sendTo; private ArrayList<String> ccList; private ArrayList<String> bccList; private String senderEmail; private String senderName; private String subject; private DominoDocument document; private String fieldName; private String bannerHTML; private String footerHTML; private String unid; private boolean debugMode = false; private static final Pattern imgRegExp = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>"); // ------------------------------------------------------------------------- public Email() { this.subject = ""; this.sendTo = new ArrayList<String>(); this.ccList = new ArrayList<String>(); this.bccList = new ArrayList<String>(); } // ------------------------------------------------------------------------- public String getSendTo() { if (this.isDebugMode()) { System.out.println("getSendTo() : " + this.sendTo.toString()); } return this.sendTo.toString().replace("[", "").replace("]", ""); } public void setSendTo(final String sendTo) { this.sendTo.add(sendTo); } // ------------------------------------------------------------------------- public String getCcList() { if (this.isDebugMode()) { System.out.println("getCcList() : " + this.ccList.toString()); } return this.ccList.toString().replace("[", "").replace("]", ""); } public void setCcList(final String ccList) { this.ccList.add(ccList); } // ------------------------------------------------------------------------- public String getBccList() { if (this.isDebugMode()) { System.out.println("getBccList() : " + this.bccList.toString()); } return this.bccList.toString().replace("[", "").replace("]", ""); } public void setBccList(final String bccList) { this.bccList.add(bccList); } // ------------------------------------------------------------------------- public String getSenderEmail() { return this.senderEmail; } public void setSenderEmail(final String senderEmail) { this.senderEmail = senderEmail; } // ------------------------------------------------------------------------- public String getSenderName() { return this.senderName; } public void setSenderName(final String senderName) { this.senderName = senderName; } // ------------------------------------------------------------------------- public String getSubject() { return this.subject; } public void setSubject(final String subject) { this.subject = subject; } // ------------------------------------------------------------------------- public boolean isDebugMode() { return this.debugMode; } public void setDebugMode(final boolean debugMode) { this.debugMode = debugMode; } // ------------------------------------------------------------------------- private Session getCurrentSession() { NotesContext nc = NotesContext.getCurrentUnchecked(); return (null != nc) ? nc.getCurrentSession() : null; } // ------------------------------------------------------------------------- private Database getCurrentDatabase() { NotesContext nc = NotesContext.getCurrentUnchecked(); return (null != nc) ? nc.getCurrentDatabase() : null; } // ------------------------------------------------------------------------- public void send() throws NotesException, IOException, Exception { Session session = getCurrentSession(); Database database = getCurrentDatabase(); if (null != session && null != database && null != this.sendTo && null != this.subject && null != this.senderEmail) { try { if (this.isDebugMode()) { System.out.println("Started send()"); } session.setConvertMime(false); Document emailDocument = database.createDocument(); MIMEEntity emailRoot = emailDocument.createMIMEEntity("Body"); if (null != emailRoot) { MIMEHeader emailHeader = emailRoot.createHeader("Reply-To"); emailHeader.setHeaderVal(this.getSenderEmail()); emailHeader = emailRoot.createHeader("Return-Path"); emailHeader.setHeaderVal(this.getSenderEmail()); final String fromSender = (null == this.getSenderName()) ? this.getSenderEmail() : "\"" + this.getSenderName() + "\" <" + this.getSenderEmail() + ">"; emailHeader = emailRoot.createHeader("From"); emailHeader.setHeaderVal(fromSender); emailHeader = emailRoot.createHeader("Sender"); emailHeader.setHeaderVal(fromSender); emailHeader = emailRoot.createHeader("To"); emailHeader.setHeaderVal(this.getSendTo()); if (!this.ccList.isEmpty()) { emailHeader = emailRoot.createHeader("CC"); emailHeader.setHeaderVal(this.getCcList()); } if (!this.bccList.isEmpty()) { emailHeader = emailRoot.createHeader("BCC"); emailHeader.setHeaderVal(this.getBccList()); } emailHeader = emailRoot.createHeader("Subject"); emailHeader.setHeaderVal(this.getSubject()); MIMEEntity emailRootChild = emailRoot.createChildEntity(); if (null != emailRootChild) { final String boundary = System.currentTimeMillis() + "-" + this.document.getDocumentId(); emailHeader = emailRootChild.createHeader("Content-Type"); emailHeader.setHeaderVal("multipart/alternative; boundary=\"" + boundary + "\""); MIMEEntity emailChild = emailRootChild.createChildEntity(); if (null != emailChild) { final String contentAsText = this.document.getRichTextItem(this.fieldName) .getContentAsText(); Stream stream = session.createStream(); stream.writeText(contentAsText); emailChild.setContentFromText(stream, "text/plain; charset=\"UTF-8\"", MIMEEntity.ENC_NONE); stream.close(); emailChild = emailRootChild.createChildEntity(); stream = session.createStream(); stream.writeText(this.getHTML()); emailChild.setContentFromText(stream, "text/html; charset=\"UTF-8\"", MIMEEntity.ENC_NONE); stream.close(); stream.recycle(); stream = null; } // add embedded images.... final List<FileRowData> embeddedImages = this.getEmbeddedImagesList(); if (null != embeddedImages && !embeddedImages.isEmpty()) { if (this.isDebugMode()) { System.out.println("Adding Embedded Images..."); } for (FileRowData embeddedImage : embeddedImages) { emailRootChild = emailRoot.createChildEntity(); if (null != emailRootChild && embeddedImage instanceof AttachmentValueHolder) { InputStream is = null; try { String persistentName = ((AttachmentValueHolder) embeddedImage) .getPersistentName(); String cid = ((AttachmentValueHolder) embeddedImage).getCID(); emailHeader = emailRootChild.createHeader("Content-Disposition"); emailHeader.setHeaderVal("inline; filename=\"" + persistentName + "\""); emailHeader = emailRootChild.createHeader("Content-ID"); emailHeader.setHeaderVal("<" + cid + ">"); is = this.getEmbeddedImageStream(persistentName); Stream stream = session.createStream(); stream.setContents(is); emailRootChild.setContentFromBytes(stream, embeddedImage.getType(), MIMEEntity.ENC_IDENTITY_BINARY); if (this.isDebugMode()) { System.out.println("Added Embedded Image : " + persistentName); } } catch (IOException e) { if (this.isDebugMode()) { System.out.println("Adding Embedded Image failed : " + e.getMessage()); } throw e; } finally { if (null != is) { is.close(); is = null; } } } } if (this.isDebugMode()) { System.out.println("Completed Adding Embedded Images"); } } // add attachments.... final List<FileRowData> attachments = this.getDocument().getAttachmentList(this.getFieldName()); if (null != attachments && !attachments.isEmpty()) { if (this.isDebugMode()) { System.out.println("Adding Attachments..."); } for (FileRowData attachment : attachments) { emailRootChild = emailRoot.createChildEntity(); if (null != emailRootChild && attachment instanceof AttachmentValueHolder) { InputStream is = null; try { String persistentName = ((AttachmentValueHolder) attachment) .getPersistentName(); String cid = ((AttachmentValueHolder) attachment).getCID(); EmbeddedObject eo = this.getDocument().getDocument().getAttachment( persistentName); if (null != eo) { emailHeader = emailRootChild.createHeader("Content-Disposition"); emailHeader.setHeaderVal("attachment; filename=\"" + persistentName + "\""); emailHeader = emailRootChild.createHeader("Content-ID"); emailHeader.setHeaderVal("<" + cid + ">"); is = eo.getInputStream(); Stream stream = session.createStream(); stream.setContents(is); emailRootChild.setContentFromBytes(stream, attachment.getType(), MIMEEntity.ENC_IDENTITY_BINARY); if (this.isDebugMode()) { System.out.println("Added Attachment : " + persistentName); } } } catch (Exception e) { if (this.isDebugMode()) { System.out.println("Adding Attachment failed : " + e.getMessage()); } throw e; } finally { if (null != is) { is.close(); is = null; } } } } if (this.isDebugMode()) { System.out.println("Completed Adding Attachments"); } } } } emailDocument.send(); session.setConvertMime(true); if (this.isDebugMode()) { System.out.println("Completed send()"); } } catch (NotesException e) { if (this.isDebugMode()) { System.out.println("Failed send() with NotesException" + e.getMessage()); } throw e; } catch (IOException e) { if (this.isDebugMode()) { System.out.println("Failed send() with IOException" + e.getMessage()); } throw e; } catch (Exception e) { if (this.isDebugMode()) { System.out.println("Failed send() with Exception" + e.getMessage()); } throw e; } } } // ------------------------------------------------------------------------- public DominoDocument getDocument() { return this.document; } public void setDocument(final DominoDocument document) { this.document = document; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public String getFieldName() { return this.fieldName; } public void setFieldName(final String fieldName) { this.fieldName = fieldName; } // ------------------------------------------------------------------------- public List<FileRowData> getEmbeddedImagesList() throws NotesException { if (null != document && null != fieldName) { return document.getEmbeddedImagesList(fieldName); } return null; } // ------------------------------------------------------------------------- private InputStream getEmbeddedImageStream(final String fileName) throws NotesException, IOException { if (null != document && null != fieldName && null != fileName) { final DominoRichTextItem drti = document.getRichTextItem(fieldName); if (null != drti) { final PersistedContent pc = drti.getPersistedContent(FacesContext.getCurrentInstance(), fieldName, fileName); if (null != pc) { return pc.getInputStream(); } } } return null; } // ------------------------------------------------------------------------- public String getHTML() { StringBuffer html = new StringBuffer(); html.append(getBannerHTML()); html.append(getBodyHTML()); html.append(getFooterHTML()); return html.toString(); } // ------------------------------------------------------------------------- public String getBannerHTML() { return this.bannerHTML; } public void setBannerHTML(final String bannerHTML) { this.bannerHTML = bannerHTML; } // ------------------------------------------------------------------------- public String getBodyHTML() { if (null != document && null != fieldName) { if (this.isDebugMode()) { System.out.println("Started getBodyHTML()"); } final DominoRichTextItem drti = document.getRichTextItem(fieldName); if (null != drti) { try { String html = drti.getHTML(); if (null != html) { final List<FileRowData> fileRowDataList = document.getEmbeddedImagesList(fieldName); if (null != fileRowDataList) { final Matcher matcher = imgRegExp.matcher(html); while (matcher.find()) { String src = matcher.group(); final String srcToken = "src=\""; final int x = src.indexOf(srcToken); final int y = src.indexOf("\"", x + srcToken.length()); final String srcText = src.substring(x + srcToken.length(), y); for (FileRowData fileRowData : fileRowDataList) { final String srcImage = fileRowData.getHref(); final String cidImage = ((AttachmentValueHolder) fileRowData).getCID(); if (srcText.endsWith(srcImage)) { final String newSrc = src.replace(srcText, "cid:" + cidImage); html = html.replace(src, newSrc); if (this.isDebugMode()) { System.out.println("CID referenced image: " + srcText + " with CID:" + cidImage); } } } } } } if (this.isDebugMode()) { System.out.println("Completed getBodyHTML() : " + html); } return html; } catch (Exception e) { if (this.isDebugMode()) { System.out.println("Failed getBodyHTML() : " + e.getMessage()); } } } } return null; } public void setBodyHTML(final String bodyHTML) throws NotImplementedException { if (this.isDebugMode()) { System.out.println("Method setBodyHTML(string) is not permitted"); } throw new NotImplementedException(); } // ------------------------------------------------------------------------- public String getFooterHTML() { return this.footerHTML; } public void setFooterHTML(final String footerHTML) { this.footerHTML = footerHTML; } public String getUnid() { return unid; } public void setUnid(final String unid) { this.unid = unid; } // ------------------------------------------------------------------------- } // end EmailBean
The Email.setUNID statement is wrong. Try: Email.setUnid(emlDoc.getUniversalID());
Having Error while recurssing though A list of Objects that contains another List
I have a class in Java which has an object List<GroupNavigationItemSRO> children Now Every GroupNaviagationItemSRO has the same List List<GroupNavigationItemSRO> children NOw i want to iterate through every GroupNavigationSRO and populate a List of String . Currently i am trying to do that like this void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){ System.out.println("PRINT"); for(GroupNavigationItemSRO item : items) { nitems.add(item.getUrl()); System.out.println(item.getUrl()); // g.add(item.getUrl()); System.out.println("PRINT"); List<GroupNavigationItemSRO> nextItem = item.getChildren(); if (nextItem != null && nextItem.size()>0) { getNavItems(nextItem,nitems); } } } When i only print the objects ,it doesn't give any errors But as soon as i try and add to the List the recurssion stops nitems.add(item.getUrl()) Why is this happening . Here's the entire java file in case its helpful #Service("labelSearchService") public class LabelSearchServiceImpl extends AbstractSearchService { private static final String version = SearchVersion.VERSION_2.getValue(); private static final Logger LOG = LoggerFactory.getLogger(LabelSearchServiceImpl.class); private static final String EXPIRY_SET = "expiry"; private static final String DATA_SET = "data"; #Autowired #Qualifier("searchServiceFactory") private ISearchServiceFactory searchServiceFactory; #Autowired IAerospikeTopSellingBrandsCacheService topSellingBrandsCacheService; #Autowired private LabelSearchCacheServiceImplFactory labelSearchCacheServiceImplFactory; #Autowired AerospikeGuidedResponse aerospikeGuidedResponse ; List<String> g = null; #Override public SearchSRO getSolrResponse(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer productCategoryId, int start, int number, String sortBy, String userZone, String vertical, String clickSrc, boolean isSpellCheckEnabled, String categoryURL, boolean isNested) throws SearchException, ShardNotFoundException, IllegalAccessException { String originalKeyword = searchTerm; searchTerm = SearchUtils.modifySearchTerm(searchTerm); SearchSRO sro = new SearchSRO(); boolean isPartialSearch = SearchUtils.isPartialSearchEnabled(); keyGenerator.setPartialSearch(SearchUtils.isPartialSearchEnabled()); LabelNodeSRO labelNode = SearchUtils.getLabelNodeByNodePath(categoryURL); // for 'ALL' categories labelNode would be null. LOG.info("categoryURL : " + categoryURL); if (ALL.equals(categoryURL)) { if (number == 0 && !CacheManager.getInstance().getCache(SearchConfigurationCache.class).getBooleanProperty(SearchProperty.ALLOW_ZERO_RESULT_REQUESTS)) { return new SearchSRO(); } sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchBinResultsForAllLabels(keyGenerator, queryFromBrowser, searchTerm, labelNode, start, number, sortBy, userZone, vertical, isPartialSearch, isSpellCheckEnabled, originalKeyword, false, isNested); } else if (labelNode != null) { sro = getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, null, null, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled, originalKeyword, isNested, false,categoryURL); } else { throw new SearchException("Search was hit without selecting any category"); } // this is the minimum number to results that should match for results to be shown on 'people who search this bought this widget' SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); if ((ClickSourceType.PWSTBT_WIDGET.getValue()).equalsIgnoreCase(clickSrc) && sro.getNoOfMatches() < cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)) { LOG.info("The minimum number of results to match for PWSTBT widget are " + cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS) + " but number of matched results are " + sro.getNoOfMatches()); sro = new SearchSRO(); } return sro; } #Override public SearchSRO getSolrResponseForMobile(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer productCategoryId, int start, int number, String sortBy, String userZone, String vertical, String clickSrc, boolean isBinSearch, int noOfResultsPerBin, boolean isSpellCheckEnabled, boolean isPartialSearch, String categoryURL) throws SearchException, ShardNotFoundException, IllegalAccessException { String originalKeyword = searchTerm; searchTerm = SearchUtils.modifySearchTerm(searchTerm); SearchSRO sro = new SearchSRO(); isPartialSearch = isPartialSearch && SearchUtils.isPartialSearchEnabled(); // this is to disable partial search in case of PWSTBT if (ClickSourceType.PWSTBT_WIDGET.getValue().equalsIgnoreCase(clickSrc)) { isPartialSearch = false; } LabelNodeSRO labelNode = SearchUtils.getLabelNodeByNodePath(categoryURL); // for 'ALL' categories labelNode would be null if (ALL.equals(categoryURL)) { if (number == 0 && !CacheManager.getInstance().getCache(SearchConfigurationCache.class).getBooleanProperty(SearchProperty.ALLOW_ZERO_RESULT_REQUESTS)) { return new SearchSRO(); } // Response for Search result page in mobile - same as web. sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchBinResultsForAllLabels(keyGenerator, queryFromBrowser, searchTerm, labelNode, start, number, sortBy, userZone, vertical, isPartialSearch, isSpellCheckEnabled, originalKeyword, true, false); } else if (labelNode != null) { sro = getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, null, null, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled, originalKeyword, false, true,categoryURL); } else { throw new SearchException("Search was hit without selecting any category"); } // this is the minimum number to results that should match for results to be shown on 'people who search this bought this widget' SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); if ((ClickSourceType.PWSTBT_WIDGET.getValue()).equalsIgnoreCase(clickSrc) && sro.getNoOfMatches() < cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS)) { LOG.info("The minimum number of results to match for PWSTBT widget are " + cache.getIntegerProperty(SearchProperty.BEST_SELLER_MINIMUM_RESULTS) + " but number of matched results are " + sro.getNoOfMatches()); sro = new SearchSRO(); } return sro; } #Autowired private IUserPersonaSegmentService personaSegmentService; #Autowired private IContextHolder<SearchRequestContext> ctxProvider; private boolean isClientPersonaEnabled(SearchRequestContext ctx) { SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); String clientsEnabled = cache.getProperty(SearchProperty.PERSONA_CLIENTS_ENABLED); String client = ctx.req.getContextSRO().getAppIdent(); return !StringUtils.isEmpty(client) && !StringUtils.isEmpty(clientsEnabled) && Pattern.matches("(?i).*\\b" + client + "\\b.*", clientsEnabled); } protected UserSegmentDTO setupPersonalizationContext(LabelNodeSRO labelNode, String searchTerm, String sortBy) { SearchRequestContext ctx = ctxProvider.getContext(); if (ctx == null || ctx.req == null) { LOG.warn("No Request Context found"); return null; } SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); // check if Personalization is enabled if (labelNode == null || !cache.getBooleanProperty(SearchProperty.PERSONA_SEARCH_ENABLED) || StringUtils.isEmpty(searchTerm) || !SolrSortCategory.RELEVANCY.getValue().equalsIgnoreCase(sortBy) || !isClientPersonaEnabled(ctx)) { LOG.debug("Personalization not enabled"); return null; } LOG.info("Trying to set up personalization context"); // setup the context for later use ctx.personaSegments = personaSegmentService.getUserSegments(ctx.req.getUserTrackingId(), labelNode.getNodePath()); return ctx.personaSegments; } #Override public SearchSRO getSearchProducts(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer campaignId, ProductCategorySRO pc, LabelNodeSRO labelNode, int start, int number, String sortBy, String userZone, boolean isPartialSearch, boolean isSpellCheckEnabled, String originalKeyword, boolean isNested, boolean isMobile,String categoryURL) throws SearchException, ShardNotFoundException, IllegalAccessException { LOG.info("------------------Product category page---------------"); // build cache key considering campaign id keyGenerator.setCampaignId(String.valueOf(campaignId)); // Search results will vary based on isNested flag even for exact same keywords hence, when we cache // we cache both results with different key keyGenerator.setNested(isNested); SearchConfigurationCache cache = CacheManager.getInstance().getCache(SearchConfigurationCache.class); LOG.info("sortBy : " + sortBy + ", personalization Enabled : " + cache.getBooleanProperty(SearchProperty.PERSONA_SEARCH_ENABLED) + ", labelNode : " + labelNode); // try to set persona context keyGenerator.setPersonaSegment(setupPersonalizationContext(labelNode, searchTerm, sortBy)); SearchSRO searchSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, campaignId, pc, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled, originalKeyword, isNested, isMobile,categoryURL); /*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext(); if (coreContext != null) { if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) { String cacheKey = keyGenerator.buildKey(); try { final AerospikeClient aClient = AerospikeClientFactory.getInstance(); LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey); aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey)); aClient.delete(null, new Key("search", DATA_SET, cacheKey)); } catch (AerospikeException e) { e.printStackTrace(); } } }*/ return searchSRO; } #Override public FilterListSRO getFiltersForProducts(Integer categoryId, Integer campaignId, String q, String keyword, boolean partialSearch, boolean isBrand, String categoryUrl, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes, GetFiltersRequest request) throws SearchException, ShardNotFoundException { String key = new KeyGenerator(String.valueOf(categoryId), String.valueOf(campaignId), q, keyword, partialSearch, null, categoryUrl, version, userZone, hyperlocalCriteria, pinCodes).buildFilterKey(); if (campaignId != null) { LOG.info("Get Filters for Campaign Products wrt : " + key); } FilterListSRO filterListSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFiltersForProducts(key, categoryId, campaignId, q, keyword, partialSearch, isBrand, categoryUrl, userZone, hyperlocalCriteria, pinCodes,request); return filterListSRO; } #Override public FilterListSRO getFiltersForProducts(Integer categoryId, Integer campaignId, String q, String keyword, boolean partialSearch, boolean isBrand, String categoryUrl, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) throws SearchException, ShardNotFoundException { return getFiltersForProducts(categoryId, campaignId, q, keyword, partialSearch, isBrand, categoryUrl, userZone, hyperlocalCriteria, pinCodes,null); } #Override public FilterListSRO getFilterValuesForFilter(String categoryId, String campaignId, String q, String keyword, boolean partialSearch, String filterName, String fullQ, String categoryUrl, String[] filtersToFetch, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) throws SearchException, NumberFormatException, ShardNotFoundException { String uniqueFilterKey = new KeyGenerator(categoryId, campaignId, q, keyword, partialSearch, filterName, categoryUrl, version, userZone, hyperlocalCriteria, pinCodes).buildFilterKey(); String[] filterNames = filterName.split(","); FilterListSRO filterListSRO = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFilterValuesForFilter(uniqueFilterKey, categoryId, campaignId, q, keyword, partialSearch, filterNames, categoryUrl, filtersToFetch, userZone, hyperlocalCriteria, pinCodes); /*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext(); if (coreContext != null) { if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) { String cacheKey = uniqueFilterKey.concat(".FilterSRO"); try { final AerospikeClient aClient = AerospikeClientFactory.getInstance(); LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey); aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey)); aClient.delete(null, new Key("search", DATA_SET, cacheKey)); } catch (AerospikeException e) { e.printStackTrace(); } } }*/ return filterListSRO; } #Override public GroupNavigationSRO getGroupNavigation(KeyGenerator keyGenerator, String keyword, String q, String categoryUrl, Integer campaignId, boolean isSpellCheck, String userZone) throws IllegalAccessException { GroupNavigationSRO sro = new GroupNavigationSRO(); try { ProductCategoryCache categoryCache = CacheManager.getInstance().getCache(ProductCategoryCache.class); LabelNodeSRO labelNode = ALL.equals(categoryUrl) ? null : categoryCache.getLabelForLabelPath(categoryUrl); if (!ALL.equals(categoryUrl) && labelNode == null) { LOG.error("Invalid label : " + categoryUrl); return null; } // try to setup persona context - using sort to relevancy since group left nav doesn't change with sortBy keyGenerator.setPersonaSegment(setupPersonalizationContext(labelNode, keyword, SolrSortCategory.RELEVANCY.getValue())); sro = labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getGroupNavigation(keyGenerator, keyword, q, categoryUrl, campaignId, isSpellCheck, userZone); /*SearchCoreContext coreContext = CoreContextHolderThreadLocal.getContext(); if (coreContext != null) { if (coreContext.getCategoryUrlUsed().equalsIgnoreCase("ALL")) { String cacheKey = keyGenerator.buildKey().concat(".GroupNavigationSRO"); try { final AerospikeClient aClient = AerospikeClientFactory.getInstance(); LOG.info("Clearing Cache as Category redirected was ambiguous so redirected to ALL and removing key " + cacheKey); aClient.delete(null, new Key("search", EXPIRY_SET, cacheKey)); aClient.delete(null, new Key("search", DATA_SET, cacheKey)); } catch (AerospikeException e) { e.printStackTrace(); } } }*/ } catch (SearchException e) { LOG.error("Error in fetching GroupSRO: ", e); } return sro; } #Override public QueryResponse setCategoryFilterQueryAndExecute(SearchCriteria sc, Integer id) throws SearchException { labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().setCategoryFilterQuery(sc, id); return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().executeQuery(sc.buildQuery(), id); } #Override public Long getProductCategoryCount(Integer categoryId, String categoryUrl) { Long count = CacheManager.getInstance().getCache(ProductCategoryCache.class).getCategoryCountByUrl(categoryUrl); if (count == null) { count = new Long(0); } LOG.info("Product Category Counts for CategoryUrl: " + categoryUrl + " = " + count); return count; } #Override public List<TopSellingProductCategorySRO> getTopSellingProductsforCategories(List<Integer> categoryIds, List<String> categoryUrls) { List<TopSellingProductCategorySRO> topSellingProductCategorySROs = new ArrayList<TopSellingProductCategorySRO>(); for (String categoryUrl : categoryUrls) { try { TopSellingProductCategorySRO topSellingProductCategorySRO = null; Integer searchId = ShardResolverService.getSearchIdByLabel(categoryUrl); QueryResponse rsp = searchServiceFactory.getSearchService(SearchVersion.VERSION_2.getValue()).getTopProductsInfoById(searchId, CacheManager.getInstance().getCache(SearchConfigurationCache.class).getIntegerProperty(SearchProperty.MAX_TOP_SELLING_PRODUCTS_PER_CATEGORY)); List<Long> pogIds = SearchUtils.extractTopProductsByCategoryId(rsp); if (pogIds != null && !pogIds.isEmpty()) { topSellingProductCategorySRO = new TopSellingProductCategorySRO(categoryUrl, pogIds); topSellingProductCategorySROs.add(topSellingProductCategorySRO); } } catch (Exception e) { LOG.error("Unable to get Top Selling Products for categoryId: " + categoryUrl + ", Exception:" + e.getMessage()); } } return topSellingProductCategorySROs; } #Override public List<TopSellingBrandSRO> getTopSellingBrandsforCategories(List<Integer> categoryIds, List<String> categoryUrls) { List<TopSellingBrandSRO> topSellingBrandSROs = new ArrayList<TopSellingBrandSRO>(); for (String categoryUrl : categoryUrls) { TopSellingBrandSRO topSellingBrandSRO = topSellingBrandsCacheService.getTopSellingBrandsByUrl(categoryUrl); if (topSellingBrandSRO != null) { topSellingBrandSROs.add(topSellingBrandSRO); } } return topSellingBrandSROs; } #Override public List<TopSellingBrandSRO> getAllTopSellingProducts(){ List<TopSellingBrandSRO> topSellingBrandSROs = topSellingBrandsCacheService.getAllTopSellingProducts(); return topSellingBrandSROs; } #Override public FacetSRO getFacets(String cachekey, String keyword, String queryFieldName, String[] facetFields, Map<String, List<String>> filterMap, int number) throws SearchException { // update values for mainCategoryXpath & categoryXpath fields /*if(SolrFields.CATEGORY_XPATH.equals(queryFieldName) || SolrFields.MAIN_CATEGORY_XPATH.equals(queryFieldName)) { String labelPath = SearchUtils.getLabelPathByUrl(keyword); keyword = String.valueOf(ShardResolverService.getSearchIdByLabel(labelPath)); }*/ for (String filterField : filterMap.keySet()) { if (SolrFields.CATEGORY_XPATH.equals(filterField) || SolrFields.MAIN_CATEGORY_XPATH.equals(filterField)) { List<String> searchIds = new ArrayList<String>(); for (String val : filterMap.get(filterField)) { String labelPath = SearchUtils.getLabelPathByUrl(val); searchIds.add(String.valueOf(ShardResolverService.getSearchIdByLabel(labelPath))); } filterMap.put(filterField, searchIds); } } return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getFacets(cachekey, keyword, queryFieldName, facetFields, filterMap, number); } #Override public FilterListSRO getSRPFilters(KeyGenerator keyGenerator, String q, String keyword, boolean partialSearch, String categoryUrl, String userZone, HyperlocalCriteria hyperlocalCriteria, Set<Integer> pinCodes) throws SearchException { if (StringUtils.isEmpty(keyword)) { LOG.error("Invalid parameters."); return null; } keyword = SearchUtils.modifySearchTerm(keyword); if (StringUtils.isEmpty(keyword)) { LOG.info(" Returning empty filters for empty keyword."); return new FilterListSRO(); } return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getSRPFilters(keyGenerator.buildKey(), q, keyword, partialSearch, categoryUrl, userZone, hyperlocalCriteria, pinCodes); } #Override public SearchSRO getSearchProducts(KeyGenerator keyGenerator, String queryFromBrowser, String searchTerm, Integer campaignId, ProductCategorySRO pc, LabelNodeSRO labelNode, int start, int number, String sortBy, String userZone, boolean isPartialSearch, boolean isSpellCheckEnabled, String originalKeyword, boolean isNested, boolean isMobile) throws SearchException, ShardNotFoundException, IllegalAccessException { // TODO Auto-generated method stub return getSearchProducts(keyGenerator, queryFromBrowser, searchTerm, campaignId, pc, labelNode, start, number, sortBy, userZone, isPartialSearch, isSpellCheckEnabled, originalKeyword, isNested, isMobile, null); } #Override public String getmodelSearch(String query, String type) throws SearchException { return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getmodelSearch(query, type); } #Override public String classifierResponse(String query, String type) throws SearchException { try { return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getClassifierResponse(query, type); } catch (JsonGenerationException e) { return e.getMessage(); } catch (JsonMappingException e) { return e.getMessage(); } catch (IOException e) { return e.getMessage(); } } public GetGuidedSearchResponse getGuides(String query, String url) { if(!StringUtils.isEmpty(query) && !StringUtils.isEmpty(url) && url.equalsIgnoreCase("ALL")) { KeyGenerator keyGenerator = new KeyGenerator(); keyGenerator.setQ("sNapDeAl.sEarcH.getGuides=" +"##"+ query+ "##"+ url); return labelSearchCacheServiceImplFactory.getSearchCacheServiceImpl().getGuides(keyGenerator, query, url); } return null; } public GetGuidedSearchResponse getFilteredGuides(String query ,GetGroupLeftNavResponse leftNavBarResponse) { g=null; GroupNavigationSRO groups = leftNavBarResponse.getGroups(); List<GroupNavigationItemSRO> items = groups.getItems() ; // List<String> nitems = getNavItems(items); List<String> nitems = null; getNavItems(items,nitems); System.out.println("SIZE" + nitems.size()); List<String> navItems = new ArrayList<String>(); System.out.println("GETTING GUIDED FILE FROM AEROSPIKE"); List<String> guideItems = aerospikeGuidedResponse.getGuides(query); //HashMap<String,String> nodeUrlMapping = new HashMap<String,String>(); if(guideItems.isEmpty()) { System.out.println("\n\n\n\n" + "EMPTY GUIDED" + " \n\n\n\n\n"); } guideItems.set(0, guideItems.get(0).trim()); System.out.println("GUIDED RESPONSE"); for(int i=0 ; i < guideItems.size() ;i ++) { System.out.println(guideItems.get(i)); } /*for (int i =0 ;i < items.size() ;i++) { List<GroupNavigationItemSRO> children_items = items.get(i).getChildren(); String s = items.get(i).getNodePath(); String m = items.get(i).getUrl(); System.out.println(s + " " + m); navItems.add(m); //nodeUrlMapping.put(s,m); for (int j=0;j<children_items.size();j++) { String r = children_items.get(j).getNodePath(); String n = children_items.get(j).getUrl(); System.out.println(r +" " + n); // nodeUrlMapping.put(r,n); navItems.add(n); } }*/ System.out.println("ITEM RESPONSE"); //navItems = g ; for(int i=0 ; i < navItems.size() ;i ++) { System.out.println(navItems.get(i)); } List<String> filteredGuides = new ArrayList<String>(); for(int i=0 ; i < guideItems.size() ;i++) { if(navItems.contains(guideItems.get(i))) filteredGuides.add(guideItems.get(i)); else { } } System.out.println("NAV ITEMS" + navItems.size() + navItems.toString()); System.out.println("GUIDE ITEMS" + filteredGuides.size() + filteredGuides.toString()); List<WidgetEntity> entities = new ArrayList<WidgetEntity>(); /* Iterator it = nodeUrlMapping.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); System.out.println(pair.getKey() + " = " + pair.getValue()); }*/ for(int i=0;i<filteredGuides.size();i++) { String guide = filteredGuides.get(i); guide = guide.trim(); System.out.println(guide); LabelNodeSRO labelSRO = getLableSRO(guide); System.out.println(labelSRO.toString() + guide); WidgetEntity entity = new WidgetEntity(); entity.setId(labelSRO.getUrl()); entity.setName(labelSRO.getDisplayName()); entity.setType("category"); entities.add(entity); } System.out.println("ENTITIES DEtails" ); GetGuidedSearchResponse response = new GetGuidedSearchResponse(); for(int i =0 ;i<entities.size();i++) { System.out.println(entities.get(i).getId() + entities.get(i).getName() + entities.get(i).getType()); // System.out.println(nodeUrlMapping.get(entities.get(i).getId())); } response.setEntities(entities); return response; } LabelNodeSRO getLableSRO(String guide) { System.out.println(guide + "GET"); LabelNodeSRO label =SearchUtils.getLabelNodeByNodePath(guide); return label; } void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){ System.out.println("PRINT"); for(GroupNavigationItemSRO item : items) { nitems.add(item.getUrl()); System.out.println(item.getUrl()); // g.add(item.getUrl()); System.out.println("PRINT"); List<GroupNavigationItemSRO> nextItem = item.getChildren(); if (nextItem != null && nextItem.size()>0) { getNavItems(nextItem,nitems); } } } }
You could try something like this, when you return a list with all Strings, and if there are no more elments stop the recursivity and returns an empty list List<String> getNavItems(List<GroupNavigationItemSRO> items){ List<String> results = new ArrayList(); System.out.println("PRINT"); if(items != null && !items.isEmpty()){ for(GroupNavigationItemSRO item : items) { results.add(item.getUrl()); System.out.println(item.getUrl()); // g.add(item.getUrl()); System.out.println("PRINT"); results.addAll(getNavItems(item.getChildren())); } } } return results; }
In getFilteredGuides() method you're passing nitems as null and this would cause NullPointerException. Just Pass it as the following: List<String> nitems = new ArrayList<String>(); getNavItems(items,nitems); Or you can add a check for null inside getNavItems() method and initialize it accordingly: void getNavItems(List<GroupNavigationItemSRO> items,List<String> nitems){ if(nitems == null) { nitems = new ArrayList<String>(); } System.out.println("PRINT"); for(GroupNavigationItemSRO item : items) { nitems.add(item.getUrl()); System.out.println(item.getUrl()); // g.add(item.getUrl()); System.out.println("PRINT"); List<GroupNavigationItemSRO> nextItem = item.getChildren(); if (nextItem != null && nextItem.size()>0) { getNavItems(nextItem,nitems); } } }
Phonegap FileUpload Java Server
I am trying to upload an Image on Java Server.the File is trnsfering from android device but saving null on server . Here is server code public UploadMediaServerResponse uploadFileForFunBoard(#FormDataParam("photoPath") InputStream photoInputStream, #FormDataParam("photoPath") FormDataContentDisposition photoFileDetail, #FormDataParam("userId") int userId, #FormDataParam("mediaType") String mediaType, #FormDataParam("title") String title,#FormDataParam("funBoardId") int funBoardId) { MediaContenModel mediaContenModel = new MediaContenModel(); mediaContenModel.setFunBoardId(funBoardId); mediaContenModel.setMediaType(mediaType); mediaContenModel.setUserId(userId); UploadMediaServerResponse uploadMediaServerResponse = new UploadMediaServerResponse(); boolean isMediaProcessedAndUploaded = true; String mediaProcessingError = ""; if (photoInputStream != null && photoFileDetail != null) { uploadMediaServerResponse = mediaService.uploadOnServer(photoInputStream, photoFileDetail.getFileName(), userId+""); if (uploadMediaServerResponse != null && !uploadMediaServerResponse.getMediaUrl().equalsIgnoreCase("ERROR")) { mediaContenModel.setImageUrl(uploadMediaServerResponse.getMediaUrl()); logger.debug("ContentService --> createStroyline --> fearture Image url ::" + uploadMediaServerResponse.getMediaUrl()); } else { isMediaProcessedAndUploaded = false; mediaProcessingError = uploadMediaServerResponse.getMediaUrl(); logger.debug("ContentService --> createStroyline --> mediaProcessingError ::" + mediaProcessingError); } } if (isMediaProcessedAndUploaded) { UploadMediaServerResponse response = funBoardService.uploadMediaContent(mediaContenModel); uploadMediaServerResponse.setMediaUrl(response.getMediaUrl()); } else { uploadMediaServerResponse.setError("Task Failed"); uploadMediaServerResponse.setStatus(ServiceAPIStatus.FAILED.getStatus()); } return uploadMediaServerResponse; } here is my phonegap code var pictureSource; var destinationType; function onPhotoURISuccess(imageURI) { console.log(imageURI); var largeImage = document.getElementById('largeImage'); largeImage.style.display = 'block'; largeImage.src = imageURI; var options = new FileUploadOptions(); options.fileKey="photoPath"; options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1); options.mimeType="image/jpeg"; options.params = { "userId": 1, "funBoardId": 3, "mediaType": 'image' }; console.log(JSON.stringify(options)); var ft = new FileTransfer(); ft.upload(imageURI, _BaseURL+"mobile/userService/funboard/upload", win, fail, options); } function onPhotoDataSuccess(imageURI) { var imgProfile = document.getElementById('imgProfile'); imgProfile.src = imageURI; if(sessionStorage.isprofileimage==1) { getLocation(); } movePic(imageURI); } function onFail(message) { alert('Failed because: ' + message); } function movePic(file) { window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError); } function resolveOnSuccess(entry) { var d = new Date(); var n = d.getTime(); var newFileName = n + ".jpg"; var myFolderApp = "MyAppFolder"; window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) { fileSys.root.getDirectory( myFolderApp, {create:true, exclusive: false}, function(directory) { entry.moveTo(directory, newFileName, successMove, resOnError); }, resOnError); }, resOnError); } function successMove(entry) { alert(entry.fullPath); sessionStorage.setItem('imagepath', entry.fullPath); } function resOnError(error) { alert(error.code); } function capturePhotoEdit() { navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true, destinationType: destinationType.DATA_URL }); } function getPhoto(source) { navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, destinationType: destinationType.FILE_URI, sourceType: source }); } function onFail(message) { alert('Failed because: ' + message); } function win(r) { console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); alert(r.response); } function fail(error) { alert("An error has occurred: Code = " = error.code); } 04-14 19:33:46.010: E/FileTransfer(13550): java.io.FileNotFoundException: http:///jeeyoh/mobile/userService/funboard/upload Thanks in Advance
Replace options.fileKey="file"; To options.fileKey="photoPath";
How to pass username and password at the time of handshaking to authenticate use in websocket?
i am devloping a group chat appication and i want to send username and password at the time of handshaking. Here is my client side javascript code: <script type="text/javascript"> var Chat = {}; Chat.socket = null; Chat.connect = (function(host) { if ('WebSocket' in window) { Chat.socket = new WebSocket(host); } else if ('MozWebSocket' in window) { Chat.socket = new MozWebSocket(host); } else { alert("'Error: WebSocket is not supported by this browser.'") Console.log('Error: WebSocket is not supported by this browser.'); return; } Chat.socket.onopen = function() { Console.log('Info: WebSocket connection opened.'); document.getElementById('chat').onkeydown = function(event) { if (event.keyCode == 13) { Chat.sendMessage(); } }; }; Chat.socket.onclose = function() { document.getElementById('chat').onkeydown = null; Console.log('Info: WebSocket closed.'); }; Chat.socket.onmessage = function(message) { Console.log(message.data); }; }); Chat.initialize = function() { if (window.location.protocol == 'http:') { Chat.connect('ws://' + window.location.host + '/WebSocketDemo/ChatWebSocketServlet'); } else { Chat.connect('wss://' + window.location.host + '/WebSocketDemo/ChatWebSocketServlet'); } }; Chat.sendMessage = (function() { var message = document.getElementById('chat').value; if (message != '') { Chat.socket.send(message); document.getElementById('chat').value = ''; } }); var Console = {}; Console.log = (function(message) { var console = document.getElementById('console'); var p = document.createElement('p'); p.style.wordWrap = 'break-word'; p.innerHTML = message; console.appendChild(p); while (console.childNodes.length > 25) { console.removeChild(console.firstChild); } console.scrollTop = console.scrollHeight; }); Chat.initialize(); </script> and i have used tomcat 7 as a server. Here is my server side code: #Deprecated public class ChatWebSocketServlet extends WebSocketServlet { private static final long serialVersionUID = 1L; private static final String GUEST_PREFIX = "Guest"; private final AtomicInteger connectionIds = new AtomicInteger(0); private final Set<ChatMessageInbound> connections = new CopyOnWriteArraySet<ChatMessageInbound>(); #Override protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) { return new ChatMessageInbound(connectionIds.incrementAndGet()); } private final class ChatMessageInbound extends MessageInbound { private final String nickname; private ChatMessageInbound(int id) { System.out.println("stage 1"); this.nickname = GUEST_PREFIX + id; } #Override protected void onOpen(WsOutbound outbound) { connections.add(this); System.out.println("user:" + this); String message = String.format("* %s %s", nickname, "has joined."); broadcast(message); } #Override protected void onClose(int status) { connections.remove(this); String message = String.format("* %s %s", nickname, "has disconnected."); broadcast(message); } #Override protected void onBinaryMessage(ByteBuffer message) throws IOException { throw new UnsupportedOperationException( "Binary message not supported."); } #Override protected void onTextMessage(CharBuffer message) throws IOException { // Never trust the client String filteredMessage = String.format("%s: %s", nickname, HTMLFilter.filter(message.toString())); broadcast(filteredMessage); } private void broadcast(String message) { for (ChatMessageInbound connection : connections) { try { CharBuffer buffer = CharBuffer.wrap(message); connection.getWsOutbound().writeTextMessage(buffer); } catch (IOException ignore) { // Ignore } } } } } Here i want to send User's credential before actual handshaking to authenticate user. so how i can to in this?
Primefaces wizard. How to return js function tab for onnext
I use Primefaces 3.5. And try to call js function in onnext handler of <p:wizard/>. I want that onnext return on tab on specific tab after validation result ob current tab. My validation function function validateManageOtherTournaments(wizard, validationTab, lang) { var currentTabId = validationTab; if (currentTabId != 'competitionId') { return wizard.next(); } var seasonVal = document.getElementById('manageTournament:name_season_input').value; var dateFromVal = document.getElementById('manageTournament:dateFrom_input').value; var dateToVal = document.getElementById('manageTournament:dateTo_input').value; /*var compNameVal = document.getElementById('manageTournament:title_input').value;*/ var isValidName = validateFieldsInOtherTournament('manageTournament', ['title'], lang); if (isValidName) { if (validRuContentT) { var filledBothDate = (dateFromVal != "" && dateToVal != ""); var isEmptySeason = ("" != String(seasonVal)); if ( filledBothDate || isEmptySeason) { return wizard.next(); } } } return "competitionId"; // currentTab } I use code js wizard. But it still doesn't work.( //UPDATED I try to do something like this function validateManageOtherTournaments(wizard, validationTab, lang) { /*var wizardElement = document.getElementById('wiz');*/ var currentTabId = validationTab; if (currentTabId != 'competitionId') { var currentStepIndex = wizard.getStepIndex(wizard.getState().currentStep), stepIndexToGo = currentStepIndex + 1; var stepIdToGo = wizard.cfg.steps[stepIndexToGo]; return wizard.loadStep(stepIdToGo, stepIndexToGo, false); // next } var seasonVal = document.getElementById('manageTournament:name_season_input').value; var dateFromVal = document.getElementById('manageTournament:dateFrom_input').value; var dateToVal = document.getElementById('manageTournament:dateTo_input').value; /*var compNameVal = document.getElementById('manageTournament:title_input').value;*/ var isValidName = validateFieldsInOtherTournament('manageTournament', ['title'], lang); if (isValidName) { if (validRuContentT) { var filledBothDate = (dateFromVal != "" && dateToVal != ""); var isEmptySeason = ("" != String(seasonVal)); if ( filledBothDate || isEmptySeason) { var currentStepIndex = wizard.getStepIndex(wizard.getState().currentStep), stepIndexToGo = currentStepIndex + 1; var stepIdToGo = wizard.cfg.steps[stepIndexToGo]; return wizard.loadStep(stepIdToGo, stepIndexToGo, false); // next } } } var currentStepIndex = wizard.getStepIndex(this.getState().currentStep), stepIndexToGo = currentStepIndex; var stepIdToGo = wizard.cfg.steps[stepIndexToGo]; return wizard.loadStep(stepIdToGo, stepIndexToGo, false); //competitionId } How I can return in onnext function tab of wizard?
I did something like this: public String onFlowProcess(FlowEvent event) { if (!event.getOldStep().equals("competitionId")) { return event.getNewStep(); } if (validationPassed()) { return event.getNewStep(); } else { return event.getOldStep(); } } private boolean validationPassed() { // do your validation here. // return true if validation passed } Then in my wizard: flowListener="#{myBean.onFlowProcess}"