I am unable to see the output of the below java code in WSO2 logs.
package com.esb.integration.mediators;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
public class DbLookup extends AbstractMediator {
private String url;
private String userName;
private String password;
private String database;
private String status;
private String action;
private String DSP;
private String USER;
private String PID;
private String PMJ;
private String PMT;
private String NZPO;
private String PD;
private String SD;
public boolean mediate(MessageContext context) {
String url = (String) context.getProperty("url");
String userName = (String) context.getProperty("userName");
String password = (String) context.getProperty("password");
String database = (String) context.getProperty("database");
String status = (String) context.getProperty("status");
String action = (String) context.getProperty("action");
try {
System.out.println("Inside DB Extractor");
System.out.println("Action: "+action);
Class.forName("com.access.JDBCDriver");
Connection conn = DriverManager.getConnection(url,userName,password);
Statement stmt = conn.createStatement();
System.out.println("After getting connection");
if (action.equals("updateData")){
System.out.println("Inside if: "+action);
int result =0;
DSP = (String) context.getProperty("DSP");
USER = (String) context.getProperty("USER");
PID = (String) context.getProperty("PID");
PMJ = (String) context.getProperty("PMJ");
PMT = (String) context.getProperty("PMT");
NZPO = (String) context.getProperty("NZPO");
PD = (String) context.getProperty("PD");
SD = (String) context.getProperty("SD");
String updateQuery = "Update Table Set DSP = '"+DSP+"',USER = '"+USER+"',PID = '"+PID+"',PMJ="+PMJ+",PMT="+PMT+" Where DSP<>'Y' AND NZPO='"+NZPO+"' AND PD='"+PD+"' AND SD="+SD;
System.out.println("Query String: "+updateQuery);
result = stmt.executeUpdate(updateQuery);
if(result>0){
String response = "successfully updated "+result+" rows";
System.out.println("successfully added "+result);
context.setProperty("status",response);
return true;
}
else{
System.out.println("failed");
context.setProperty("status","0 rows were updated");
return true;
}
}
else {
context.setProperty("status","Failed");
return false;
}
}catch (Exception e) {
System.out.println("Got an exception! ");
System.out.println(e.getMessage());
context.setProperty("status","Failed");
return false;
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getstatus() {
return status;
}
public void setstatus(String status) {
this.status = status;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getDSP() {
return DSP;
}
public void setDSP(String DSP) {
DSP = DSP;
}
public String getUSER() {
return USER;
}
public void setUSER(String USER) {
USER = USER;
}
public String getPID() {
return PID;
}
public void setPID(String PID) {
PID = PID;
}
public String getPMJ() {
return PMJ;
}
public void setPMJ(String PMJ) {
PMJ = PMJ;
}
public String getPMT() {
return PMT;
}
public void setPMT(String PMT) {
PMT = PMT;
}
public String getNZPO() {
return NZPO;
}
public void setNZPO(String NZPO) {
NZPO = NZPO;
}
public String getPD() {
return PD;
}
public void setPD(String PD) {
PD = PD;
}
public String getSD() {
return SD;
}
public void setSD(String SD) {
SD = SD;
}
}
Here is the proxy service:-
<proxy xmlns="http://ws.apache.org/ns/synapse" name="TestProxy" transports="jms" statistics="disable" trace="disable" startOnLoad="true">
<inSequence>
<property name="userName" value="****"></property>
<property name="password" value="****"></property>
<property name="url" value="********"></property>
<property name="action" value="updateData"></property>
<iterate id="Item" expression="//itemList/item" sequential="true">
<target>
<sequence>
<property name="DSP" expression="//DSP/text()"></property>
<property name="USER" expression="//USER/text()"></property>
<property name="PID" expression="//PID/text()"></property>
<property name="PMJ" expression="//PMJ/text()"></property>
<property name="PMT" expression="//PMT/text()"></property>
<property name="NZPO" expression="//NZPO/text()"></property>
<property name="PD" expression="//PD/text()"></property>
<property name="SD" expression="//SD/text()"></property>
<class name="com.esb.integration.mediators.DbLookup"></class>
<log separator=",**after updatedb call**" description=""></log>
</sequence>
</target>
</iterator>
</inSequence>
<loopback/>
<outSequence/>
<parameter name="transport.jms.ContentType">application/json</parameter>
<parameter name="transport.jms.Destination">TestProxy.Q</parameter>
</proxy>
But,I can only see the "after updatedb call" message in logs when the query is executing successfully.
What should I add/modify above to get the message(which are written as System.out.println(" ")) in the WSO2 logs?
In [ESB_HOME]\repository\conf\log4j.properties put this:
log4j.logger.package=INFO, CARBON_LOGFILE, CARBON_MEMORY
Where package = the package of your class, in my case:
log4j.logger.org.softdevelop.test=INFO, CARBON_LOGFILE, CARBON_MEMORY
Restart the server and try with:
if (log.isInfoEnabled()) {
log.info("First Element log : " + firstElement.getLocalName());
}
System.out.println("First Element Text syso : " + firstElement.getText());
In my case the log print:
[2017-03-13 12:16:30,010] INFO - testIterateProperty First Element log : jsonObject
First Element Text syso :
log.info("whatever you want");
Related
I have created a class NewUserEmail to auto generate an email with username and password while creating a new user. I am able to create the password but whenever I am trying to log in with that password, its not logging in. I am not able to generate my mail. Please guide me and let me know what is wrong with my code:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.jscript.ClasspathScriptLocation;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
public class NewUserEmail implements NodeServicePolicies.OnCreateNodePolicy {
private Logger logger = Logger.getLogger(NewUserEmail.class);
private PolicyComponent policyComponent;
private NodeService nodeService;
private PersonService personService;
private ServiceRegistry serviceRegistry;
protected String userName = null;
protected String password = null;
protected String email = null;
protected String subject = null;
protected String body = null;
private static final String NEW_USER_EMAIL_TEMPLATE = "alfresco/module/demoact1-repo/template/new_user_email.ftl";
private static final String EMAIL_FROM = "no-reply#eisenvault.com";
public void init() {
this.email = "";
this.userName = "";
this.password = "";
this.subject = "New User Alfresco";
this.body = "";
this.policyComponent.bindClassBehaviour(
QName.createQName(NamespaceService.ALFRESCO_URI, "onCreateNode"),
ContentModel.TYPE_PERSON,
new JavaBehaviour(this, "ReportUser", org.alfresco.repo.policy.JavaBehaviour.NotificationFrequency.EVERY_EVENT)
);
}
public void onCreateNode(ChildAssociationRef childAssocRef) {
if (logger.isInfoEnabled()) logger.info(" NewUserEmail Node create policy fired");
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setPolicyComponent(PolicyComponent policyComponent) {
this.policyComponent = policyComponent;
}
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
public String getSubject() {
return this.subject;
}
public String getBody() {
return this.body;
}
public String getEmail() {
return this.email;
}
public String getUserName() {
return this.userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void ReportUser(ChildAssociationRef childAssocRef) {
NodeRef personRef = childAssocRef.getChildRef();
this.userName = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_USERNAME);
this.email = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_EMAIL);
sendEmail();
}
public void sendEmail() throws AlfrescoRuntimeException {
Map<String, Object> templateModel = new HashMap<String, Object>();
if (getEmail() != null && getEmail() != "") {
Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL, getEmail(), 1);
if (result.size() == 1) {
changePassword(getUserName());
ClasspathScriptLocation location = new ClasspathScriptLocation(NEW_USER_EMAIL_TEMPLATE);
try {
if (location.getInputStream() != null) {
// Check that there is a template
templateModel.put("userName", getUserName());
templateModel.put("password", getPassword());
this.body = serviceRegistry.getTemplateService().processTemplate("freemarker", NEW_USER_EMAIL_TEMPLATE, templateModel);
}
} catch (AlfrescoRuntimeException e) {
// If template isn't found, email is constructed "manually"
logger.error("Email Template not found " + NEW_USER_EMAIL_TEMPLATE);
this.body = "<html> <body> <p> A new User has been created.</p>" +
"<p>Hello, </p><p>Your username is " + getUserName() + " and your " +
"password is " + getPassword() + "</p> " +
"<p>We strongly advise you to change your password when you log in for the first time.</p>" +
"Regards</body> </html>";
//send();
}
}
}
}
protected void send() {
MimeMessagePreparator mailPreparer = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws MessagingException {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(getEmail());
message.setSubject(getSubject());
message.setText(getBody(), true);
message.setFrom(EMAIL_FROM);
}
};
}
public void changePassword(String password) {
AuthenticationUtil.setRunAsUserSystem();
Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL, getEmail(), 1);
if (result.size() == 1) {
Object[] userNodeRefs = result.toArray();
NodeRef userNodeRef = (NodeRef) userNodeRefs[0];
String username = (String) serviceRegistry.getNodeService().getProperty(userNodeRef, ContentModel.PROP_USERNAME);
// Generate random password
String newPassword = Password.generatePassword();
char[] cadChars = new char[newPassword.length()];
for (int i = 0; i < newPassword.length(); i++) {
cadChars[i] = newPassword.charAt(i);
}
serviceRegistry.getAuthenticationService().setAuthentication(username, newPassword.toCharArray());
setPassword(newPassword);
System.out.println("Password is :" + newPassword);
}
}
}
Below is a working solution.
resource/alfresco/extension/new-user-email-context.xml:
<?xml version='1.0' encoding='UTF-8'?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="newUserEmail" class="demo.NewUserEmail">
<property name="policyComponent" ref="policyComponent"/>
<property name="nodeService" ref="nodeService"/>
<property name="personService" ref="personService"/>
<property name="passwordGenerator" ref="passwordGenerator"/>
<property name="authenticationService" ref="authenticationService"/>
</bean>
</beans>
demo.NewUserEmail.java:
package demo;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.*;
import org.alfresco.repo.security.authentication.PasswordGenerator;
import org.alfresco.service.cmr.repository.*;
import org.alfresco.service.cmr.security.*;
import org.alfresco.util.PropertyCheck;
import org.springframework.beans.factory.InitializingBean;
public class NewUserEmail implements
NodeServicePolicies.OnCreateNodePolicy, InitializingBean {
#Override
public void onCreateNode(ChildAssociationRef childAssocRef) {
notifyUser(childAssocRef);
}
private void notifyUser(ChildAssociationRef childAssocRef) {
NodeRef personRef = childAssocRef.getChildRef();
// get the user name
String username = (String) this.nodeService.getProperty(
personRef, ContentModel.PROP_USERNAME);
// generate the new password (Alfresco's rules)
String newPassword = passwordGenerator.generatePassword();
// set the new password
authenticationService.setAuthentication(username, newPassword.toCharArray());
// send default notification to the user
personService.notifyPerson(username, newPassword);
}
private PolicyComponent policyComponent;
private NodeService nodeService;
private PersonService personService;
private PasswordGenerator passwordGenerator;
private MutableAuthenticationService authenticationService;
public void setPolicyComponent(PolicyComponent policyComponent) {
this.policyComponent = policyComponent;
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setPersonService(PersonService personService) {
this.personService = personService;
}
public void setPasswordGenerator(PasswordGenerator passwordGenerator) {
this.passwordGenerator = passwordGenerator;
}
public void setAuthenticationService(AuthenticationService authenticationService) {
if (authenticationService instanceof MutableAuthenticationService) {
this.authenticationService = (MutableAuthenticationService) authenticationService;
}
}
#Override
public void afterPropertiesSet() throws Exception {
PropertyCheck.mandatory(this, "policyComponent", policyComponent);
PropertyCheck.mandatory(this, "nodeService", nodeService);
PropertyCheck.mandatory(this, "passwordGenerator", passwordGenerator);
PropertyCheck.mandatory(this, "authenticationService", authenticationService);
PropertyCheck.mandatory(this, "personService", personService);
this.policyComponent.bindClassBehaviour(
NodeServicePolicies.OnCreateNodePolicy.QNAME,
ContentModel.TYPE_PERSON,
new JavaBehaviour(this,
NodeServicePolicies.OnCreateNodePolicy.QNAME.getLocalName(),
Behaviour.NotificationFrequency.TRANSACTION_COMMIT
)
);
}
}
When I attempt to compile my Play Framework 2.4 project, I receive this error:
`}' expected but eof found.
In /Users/dylhunn/Documents/workspace/my-project/app/controllers/Application.java
This seems to suggest that I failed to match my braces. However, the braces are in fact correctly matched, and the error persists even when I add extra (arbitrarily many) closing curly braces.
I have already tried "activator clean."
Here is my Application.java:
package controllers;
import model.UserAccountManager;
import play.data.Form;
import play.libs.Json;
import play.mvc.*;
import harmony.core.Harmonizer;
import play.twirl.api.Content;
import views.html.*;
import java.net.URLDecoder;
import java.util.*;
import static play.data.Form.form;
public class Application extends Controller {
public Result index() {
if (validSessionIsActive()) return harmonizepage();
else return landing();
}
public Result about() {
Content html = views.html.auxtemplate.render("title", "content");
return ok(html);
}
public Result contact() {
Content html = views.html.auxtemplate.render("title", "content");
return ok(html);
}
public Result landing() {
return ok(views.html.landing.render(form(Credentials.class)));
}
public Result login(String message) {
if (validSessionIsActive()) return index();
if (message == null) message = "";
return ok(views.html.loginpage.render(Form.form(Credentials.class), message));
}
public Result logout() {
String user = session("user-email");
session().clear();
if (user == null) return login("You were not logged in.");
return login("User " + user + " has been logged out.");
}
public Result harmonizepage() {
if (!validSessionIsActive()) return login("Please sign in to acess this page.");
return ok(views.html.harmonize.render());
}
public Result testRegister() {
return ok(views.html.signuppage.render(Form.form(UserData.class));
}
public static class Credentials {
public String email;
public String password;
}
public static class UserData {
public String email;
public String password;
public String name;
public String location;
public String birthday;
}
public Result loginSubmit() {
Form<Credentials> loginForm = form(Credentials.class).bindFromRequest();
if (UserAccountManager.userRegistered(loginForm.get().email)) {
if (UserAccountManager.authenticate(loginForm.get())) { // success
session("user-email", loginForm.get().email);
return harmonizepage();
} else { // Incorrect password
return login("Incorrect password for that email address.");
}
} else { // New user
session("candidate-email", loginForm.get().email);
session("candidate-password", loginForm.get().password);
session("registration-in-progress", "true");
return login("Sorry -- signups are still closed!");
}
}
public Result signupSubmit() {
if (!session("registration-in-progress").equals("true")) return login("");
session("registration-in-progress", "false");
Form<UserData> suForm = form(UserData.class).bindFromRequest();
UserData data = suForm.get();
data.email = session("candidate-email");
data.password = session("candidate-password");
UserAccountManager.registerUser(data);
return index();
}
/**
* Checks the session cookie to see if a valid username is stored there.
*/
public static boolean validSessionIsActive() {
String email = session("user-email");
return UserAccountManager.userRegistered(email);
}
public Result harmonize(String input) {
if (!validSessionIsActive())
return badRequest("No user is currently signed in. Try closing and reopening the site");
try {
input = URLDecoder.decode(input, "UTF-8");
} catch (Exception e) {
return badRequest("The server received an unsupported URL encoding.");
}
List<String> inputChords = Arrays.asList(input.split(" "));
List<List<String>> result = new ArrayList<>();
String str = "";
for (String s : inputChords) str = str + s + " ";
try {
result = Harmonizer.harmonize(str);
} catch (Exception e) { // Harmonizing failed for some reason
return badRequest(e.getMessage());
}
return ok(Json.toJson(result));
}
}
The error message is confusing, but the problem is in the testRegister method. The render call is not properly closed.
return ok(views.html.signuppage.render(Form.form(UserData.class));
should be
return ok(views.html.signuppage.render(Form.form(UserData.class)));
The error message is probably some kind of Scala thing popping up.
I'm writing a webapp where in there is a table that is to be generated using Ajax. This data is actually pulled from the database. And here I want to use jquery datatable plugin.
Index.jsp
<html>
<head>
</head>
<body>
<marquee>
<h1>This is an example of ajax</h1>
</marquee>
<form name="vinform">
Enter id:<input type="button" id="somebutton" value="Click Me">
</form>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Case Number</th>
<th>Case Owner</th>
<th>Status</th>
<th>Issue</th>
<th>Reason</th>
<th>Date/Time Opened</th>
<th>Age</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Case Number</th>
<th>Case Owner</th>
<th>Status</th>
<th>Issue</th>
<th>Reason</th>
<th>Date/Time Opened</th>
<th>Age</th>
</tr>
</tfoot>
</table>
<span id="somediv"> </span>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="tableGenerator.js"></script>
</body>
</html>
tableGenerator.js
$('#somebutton').click(function() {
$(document).ready(function() {
$('#example').DataTable({
"ajax" : "Controller",
"columns" : [ {
"data" : "userBean.caseNumber"
}, {
"data" : "userBean.caseOwner"
}, {
"data" : "userBean.status"
}, {
"data" : "userBean.issue"
}, {
"data" : "userBean.reason"
}, {
"data" : "userBean.age"
} ]
});
});
});
UserBean.java
package org.bean;
public class UserBean {
private int age;
private String caseOwner, status, issue, reason, dateOpened, caseNumber, resolution, finalStatus, startDate,
endDate;
private Double totalTimeTaken;
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getCaseNumber() {
return caseNumber;
}
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCaseOwner() {
return caseOwner;
}
public void setCaseOwner(String caseOwner) {
this.caseOwner = caseOwner;
}
public String getStatus() {
return status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public void setStatus(String status) {
this.status = status;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getDateOpened() {
return dateOpened;
}
public void setDateOpened(String dateOpened) {
this.dateOpened = dateOpened;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getFinalStatus() {
return finalStatus;
}
public void setFinalStatus(String finalStatus) {
this.finalStatus = finalStatus;
}
public double getTotalTimeTaken() {
return totalTimeTaken;
}
public void setTotalTimeTaken(Double totalTimeTaken) {
this.totalTimeTaken = totalTimeTaken;
}
public UserBean() {
}
public UserBean(String caseNumber, String caseOwner, String issue, int age, String reason, String dateOpened,
String status, String finalStatus, String resolution, String startDate, String endDate,
Double totalTimeTaken) {
this.caseNumber = caseNumber;
this.caseOwner = caseOwner;
this.issue = issue;
this.reason = reason;
this.age = age;
this.dateOpened = dateOpened;
this.status = status;
this.resolution = resolution;
this.finalStatus = finalStatus;
this.startDate = startDate;
this.endDate = endDate;
this.totalTimeTaken = totalTimeTaken;
}
}
Controller.java(Servlet)
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bean.UserBean;
import com.dao.DataDao;
import com.google.gson.Gson;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// String id = request.getParameter("val");
DataDao dataDao = new DataDao();
ArrayList<UserBean> list = dataDao.getFrameWork();
String searchList = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(searchList);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
DBUtility.java
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtility {
private static Connection connection = null;
public static Connection getConnection() throws Exception {
if (connection != null)
return connection;
else {
// Store the database URL in a string
String userName = "sa";
String password = "T!ger123";
String url = "jdbc:sqlserver:XXXXXX;DatabaseName=TEST";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// set the url, username and password for the databse
connection = DriverManager.getConnection(url, userName, password);
return connection;
}
}
}
DataDao.java
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.bean.UserBean;
public class DataDao {
private Connection connection;
public DataDao() throws Exception {
connection = DBUtility.getConnection();
}
public ArrayList<UserBean> getFrameWork() throws SQLException {
ArrayList<UserBean> list = new ArrayList<UserBean>();
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("select * from statusTable");
// ps.setString(1, frameWork);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
UserBean userBean = new UserBean();
userBean.setCaseNumber(rs.getString(1));
userBean.setCaseOwner(rs.getString(2));
userBean.setStatus(rs.getString(3));
userBean.setIssue(rs.getString(4));
userBean.setReason(rs.getString(5));
userBean.setDateOpened(rs.getString(6));
userBean.setAge(rs.getInt(7));
list.add(userBean);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return list;
}
}
When I click on the button, instead of displaying the table data, it is showing nothing apart from the Basic html skeleton created in my index file.
Instead of using
$('#somebutton').click(function() {
$(document).ready(function() {
$('#example').DataTable({
"ajax" : "Controller",
"columns" : [ {
"data" : "userBean.caseNumber"
}, {
"data" : "userBean.caseOwner"
}, {
"data" : "userBean.status"
}, {
"data" : "userBean.issue"
}, {
"data" : "userBean.reason"
}, {
"data" : "userBean.age"
} ]
});
});
});
when i used
$('#somebutton').click(
function() {
$.getJSON('Controller', function(searchList) {
var $table = $('<table>').appendTo($('#somediv'));
$.each(searchList, function(index, userBean) {
$('<tr>').appendTo($table).append(
$('<td>').text(userBean.caseNumber)).append(
$('<td>').text(userBean.caseOwner)).append(
$('<td>').text(userBean.status)).append(
$('<td>').text(userBean.issue)).append(
$('<td>').text(userBean.reason)).append(
$('<td>').text(userBean.age));
});
});
});
A normal html table is getting displayed.
Please let me know how can i display this data.
Thanks
Is there a possibility to get the String of the page's information in the about section?
An Example: https://www.facebook.com/FacebookDevelopers
Here is the info: "Build, grow, and monetize your app with Facebook. https://developers.facebook.com/"
I found out that the Facebook graph api supports this by the Field about on a Page.
Thanks for help in advance!
Best regards,
Dominic
you can below snippet code for getting facebook page information in java :
private static final String FacebookURL_PAGES = "me/accounts?fields=access_token,category,id,perms,picture{url},can_post,is_published,cover,fan_count,is_verified,can_checkin,global_brand_page_name,link,country_page_likes,is_always_open,is_community_page,new_like_count,overall_star_rating,name";
public List<FacebookPageModel> getPages(String accessToken) throws FacebookException, JSONException {
JSONObject posts = getBatch(accessToken,FacebookURL_PAGES);
Gson g =new Gson();
System.out.println(posts);
JSONArray postsData = posts.getJSONArray("data");
System.out.println(g.toJson(postsData));
return getPageList(postsData);
}
private JSONObject getBatch(String accessToken, String url) throws FacebookException{
Gson g = new Gson();
Facebook facebook = getFacebook(accessToken);
BatchRequests<BatchRequest> batch = new BatchRequests<BatchRequest>();
batch.add(new BatchRequest(RequestMethod.GET, url));
List<BatchResponse> results = facebook.executeBatch(batch);
BatchResponse result2 = results.get(0);
System.out.println(g.toJson(result2.asJSONObject()));
return result2.asJSONObject();
}
private Facebook getFacebook(String accessToken){
if(accessToken == null){
System.out.println("Access Token null while request for Facebook Instance !");
return null;
}
Facebook facebook = new FacebookFactory().getInstance();
facebook.setOAuthAppId(appId, appSecret);
facebook.setOAuthPermissions("email,publish_stream, publish_actions");
facebook.setOAuthAccessToken(new AccessToken(accessToken, null));
return facebook;
}
private List<FacebookPageModel> getPageList(JSONArray pagesData) throws JSONException{
Gson g = new Gson();
List<FacebookPageModel> pages = new ArrayList<FacebookPageModel>();
SimpleDateFormat desiredFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = null;
for (int i = 0; i < pagesData.length(); i++) {
FacebookPageModel obj = new FacebookPageModel();
JSONObject page = pagesData.getJSONObject(i);
System.out.println(g.toJson(page));
try{
obj.setAccessToken(page.getString("access_token"));
}catch(Exception ee){
obj.setAccessToken(null);
}
try{
obj.setCategory(page.getString("category"));
}catch(Exception ee){
obj.setCategory(null);
}
try{
obj.setId(page.getString("id"));
}catch(Exception ee){
obj.setId(null);
}
try{
obj.setName(page.getString("name"));
}catch(Exception ee){
obj.setName(null);
}
try{
obj.setCanPost(page.getBoolean("can_post"));
}catch(Exception ee){
obj.setCanPost(false);
}
try{
JSONObject picture = page.getJSONObject("picture");
JSONObject pictureData = picture.getJSONObject("data");
obj.setPageProfilePic(pictureData.getString("url"));
}catch(Exception ee){
obj.setCanPost(false);
}
try{
obj.setPublished(page.getBoolean("is_published"));
}catch(Exception ee){
obj.setPublished(false);
}
try{
obj.setFanCount(page.getLong("fan_count"));
}catch(Exception ee){
obj.setFanCount(0L);
}
try{
obj.setVerified(page.getBoolean("is_verified"));
}catch(Exception ee){
obj.setVerified(false);
}
try{
obj.setCanCheckin(page.getBoolean("can_checkin"));
}catch(Exception ee){
obj.setCanCheckin(false);
}
try{
obj.setGlobalBranPageName(page.getString("global_brand_page_name"));
}catch(Exception ee){
obj.setGlobalBranPageName(null);
}
try{
obj.setPageLink(page.getString("link"));
}catch(Exception ee){
obj.setPageLink(null);
}
try{
obj.setNewLikeCount(page.getLong("new_like_count"));
}catch(Exception ee){
obj.setNewLikeCount(0L);
}
try{
obj.setOverallStarRating(page.getLong("overall_star_rating"));
}catch(Exception ee){
obj.setOverallStarRating(0L);
}
try{
obj.setOverallStarRating(page.getLong("overall_star_rating"));
}catch(Exception ee){
obj.setOverallStarRating(0L);
}
pages.add(obj);
}
System.out.println(g.toJson(pages));
return pages;
}
public class FacebookPageModel {
//access_token
private String accessToken;
//name
private String name;
//id
private String id;
//category
private String category;
// can_post
private boolean canPost;
private String pageProfilePic;
// is_published
private boolean isPublished;
// fan_count
private long fanCount;
// is_verified
private boolean isVerified;
// can_checkin
private boolean canCheckin;
// global_brand_page_name
private String globalBranPageName;
// link
private String pageLink;
// new_like_count
private long newLikeCount;
// overall_star_rating
private long overallStarRating;
public boolean isCanPost() {
return canPost;
}
public void setCanPost(boolean canPost) {
this.canPost = canPost;
}
public String getPageProfilePic() {
return pageProfilePic;
}
public void setPageProfilePic(String pageProfilePic) {
this.pageProfilePic = pageProfilePic;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public boolean isPublished() {
return isPublished;
}
public void setPublished(boolean isPublished) {
this.isPublished = isPublished;
}
public long getFanCount() {
return fanCount;
}
public void setFanCount(long fanCount) {
this.fanCount = fanCount;
}
public boolean isVerified() {
return isVerified;
}
public void setVerified(boolean isVerified) {
this.isVerified = isVerified;
}
public boolean isCanCheckin() {
return canCheckin;
}
public void setCanCheckin(boolean canCheckin) {
this.canCheckin = canCheckin;
}
public String getGlobalBranPageName() {
return globalBranPageName;
}
public void setGlobalBranPageName(String globalBranPageName) {
this.globalBranPageName = globalBranPageName;
}
public String getPageLink() {
return pageLink;
}
public void setPageLink(String pageLink) {
this.pageLink = pageLink;
}
public long getNewLikeCount() {
return newLikeCount;
}
public void setNewLikeCount(long newLikeCount) {
this.newLikeCount = newLikeCount;
}
public long getOverallStarRating() {
return overallStarRating;
}
public void setOverallStarRating(long overallStarRating) {
this.overallStarRating = overallStarRating;
}
}
I use below code to create a workspace :
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import com.ibm.team.repository.client.ITeamRepository;
import com.ibm.team.repository.client.ITeamRepository.ILoginHandler;
import com.ibm.team.repository.client.ITeamRepository.ILoginHandler.ILoginInfo;
import com.ibm.team.repository.client.TeamPlatform;
import com.ibm.team.repository.common.TeamRepositoryException;
import com.ibm.team.scm.client.IWorkspaceConnection;
import com.ibm.team.scm.client.IWorkspaceManager;
import com.ibm.team.scm.client.SCMPlatform;
import com.ibm.team.scm.common.IFlowTable;
public class RTCFirst {
public static void main(String args[]) {
String repositoryURI = "https://rtc.domain.com/jazz";
String userId = "myid";
String password = "****";
IProgressMonitor monitor = new NullProgressMonitor();
try {
ITeamRepository repo = logIntoTeamRepository(repositoryURI,
userId, password, monitor);
IWorkspaceManager wm = SCMPlatform.getWorkspaceManager(repo);
IWorkspaceConnection workspace = wm.createWorkspace(repo.loggedInContributor(), "Example Workspace", "Description", monitor);
IFlowTable ift = workspace.getFlowTable().getWorkingCopy();
} catch (TeamRepositoryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static ITeamRepository logIntoTeamRepository(String repositoryURI,
String userId, String password, IProgressMonitor monitor)
throws TeamRepositoryException {
System.out.println("Trying to log into repository: " + repositoryURI);
TeamPlatform.startup();
ITeamRepository teamRepository = TeamPlatform
.getTeamRepositoryService().getTeamRepository(repositoryURI);
teamRepository.registerLoginHandler(new LoginHandler(userId, password));
teamRepository.login(monitor);
System.out.println("Login succeeded.");
return teamRepository;
}
private static class LoginHandler implements ILoginHandler, ILoginInfo {
private String fUserId;
private String fPassword;
private LoginHandler(String userId, String password) {
fUserId = userId;
fPassword = password;
}
public String getUserId() {
return fUserId;
}
public String getPassword() {
return fPassword;
}
public ILoginInfo challenge(ITeamRepository repository) {
return this;
}
}
}
I think I need to populate the IFlowTable with the stream I want to flow to ? If so how can this be achieved ? I can use below code to find the stream :
IWorkspaceHandle iwh = (IWorkspaceHandle) findConnectionByName(repo , "mystream" , 1 , monitor).get(0);
private static List findConnectionByName(
ITeamRepository teamRepository, String name, int kind,
IProgressMonitor monitor) throws TeamRepositoryException {
IWorkspaceManager wm = SCMPlatform.getWorkspaceManager(teamRepository);
IWorkspaceSearchCriteria criteria = IWorkspaceSearchCriteria.FACTORY
.newInstance().setKind(kind);
if (name != null) {
criteria.setExactName(name);
}
List<IWorkspaceHandle>workspaces= wm.findWorkspaces(criteria,
Integer.MAX_VALUE, monitor);
return workspaces;
}
But once I've found the stream how do I add it as flow target ?
don't know if you still need the answer, but I use below code to add a stream (lv1Stream) as flow target of another stream (lv2Stream):
IFlowTable flowTable = lv2Stream.getFlowTable().getWorkingCopy();
flowTable.addDeliverFlow(lv1Stream.getResolvedWorkspace(), repo.getId(),
repo.getRepositoryURI(), null, lv1Stream.getDescription());
IFlowEntry flowNode =
flowTable.getDeliverFlow(lv1Stream.getResolvedWorkspace());
flowTable.setDefault(flowNode);
flowTable.setCurrent(flowNode);
lv2Stream.setFlowTable(flowTable, null);