I have ABC.action which invokes the doFilter method of Filter Class which is configured properly in web.xml
I need to find action name from request object. How can i achieve this?
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
long t1 = System.nanoTime();
filterChain.doFilter(request, response);
long t2 = System.nanoTime();
long time = t2 - t1;
// Just writing statistics to servlet's log
System.out.println("## " +
"ArriveTime ns " + t1 + " Departtime ns " + t2 + " ServiceTime : " + time);
// System.out.println("Time taken to process request to "
// + ((HttpServletRequest) request).getRequestURI()
// + ": " + totalTime + " ms.");
}
Try below code(working in JBOSS).
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain fc) throws IOException, ServletException {
System.out.println("Request");
System.out.println(req);
// req instance of HttpServletRequest
if (req instanceof HttpServletRequest) {
HttpServletRequest httpReq = (HttpServletRequest) req;
System.out.println(httpReq.getRequestURI());
} else {
// req is not instance of HTTPServletRequest then try reflection
try {
Class clazz = Class
.forName("org.apache.catalina.connector.RequestFacade");
Method method = clazz.getMethod("getContextPath", new Class[0]);
String actionName = (String) method.invoke(req, new Object[0]);
System.out.println(actionName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
I am trying to use jgit to pull the changes from a git repository.
I am facing minor issues with HEAD DETACHED error when I do a pull
I have read other answers here on stackoverflow. Trying those solutions does not seem to help.
I have 2 remote branches
1. staging
2. master
Here is the sample code:
public static void main(String [] args){
final String GIT_STR = "https://github.com/newlifer2/testNewLiferRepo.git";
final String localRepositoryPath = new File("").getAbsolutePath() + File.separatorChar;
try{
//setting up local repository as just testNewLiferRepo
String repoName = localRepositoryPath + "testNewLiferRepo";
File f = new File(repoName);
Repository localRepo = new FileRepository(repoName + File.separatorChar + ".git");
ObjectId oldObjid = null;
Git git = null;
if (f.exists()) {
oldObjid = localRepo.resolve(Constants.HEAD);
git = Git.open(f);
git.pull().call();
ObjectId currentObjid = localRepo.resolve(Constants.HEAD);
git.getRepository().close();
} else {
git = Git.cloneRepository().setURI(GIT_STR).setDirectory(new File(repoName)).call();
ObjectId currentObjid =localRepo.resolve(Constants.HEAD);
if(!localRepo.getBranch().equalsIgnoreCase("staging")){
git.checkout().setName("refs/remotes/origin/staging").setForce(true).call();
}
git.getRepository().close();
}
} catch (InvalidRemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransportException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GitAPIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RevisionSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AmbiguousObjectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IncorrectObjectTypeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You can update the version in the testXML file on the repository to test the pull.
Any pointers are highly appreciated
Thanks
Looks like I had my statements switched. Here is a new solution
public static void main(String [] args){
final String GIT_STR = "https://github.com/newlifer2/testNewLiferRepo.git";
final String localRepositoryPath = new File("").getAbsolutePath() + File.separatorChar;
SSHSessionFactory sessionFactory = new SSHSessionFactory();
sessionFactory.Initialize();
SshSessionFactory.setInstance(sessionFactory);
try{
//setting up local repository as just testNewLiferRepo
String repoName = localRepositoryPath + "testNewLiferRepo";
File f = new File(repoName);
Repository localRepo = new FileRepository(repoName + File.separatorChar + ".git");
ObjectId oldObjid = null;
Git git = null;
if (f.exists()) {
oldObjid = localRepo.resolve(Constants.HEAD);
git = Git.open(f);
Map<String,Ref> m = git.getRepository().getAllRefs();
System.out.println("Current Branch: "+git.getRepository().getBranch());
if(git.getRepository().isValidRefName("refs/remotes/origin/staging")){
System.out.println("Valid");
}
git.pull().call();
git.checkout().setName("staging").call();
ObjectId currentObjid = localRepo.resolve(Constants.HEAD);
git.getRepository().close();
} else {
git = Git.cloneRepository().setURI(GIT_STR).setDirectory(new File(repoName)).call();
ObjectId currentObjid =localRepo.resolve(Constants.HEAD);
if(!localRepo.getBranch().equalsIgnoreCase("staging")){
git.branchCreate().setForce(true).setName("staging").setStartPoint("refs/remotes/origin/staging").call();
}
git.checkout().setName("staging").call();
git.getRepository().close();
}
} catch (InvalidRemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransportException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GitAPIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RevisionSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AmbiguousObjectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IncorrectObjectTypeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is my code. Connection to database is working. When the statement posts = s.executeQuery(query); is executed it is not even entering into loop and executing from finally. unfortunately there is no exception thrown.
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n";
String title = "Trend Blog";
out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title
+ "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n"
+ "<H1 ALIGN=CENTER>" + title + "</H1>\n");
Connection connection = null;
ResultSet posts = null;
ConnectMySql connectMySql = new ConnectMySql();
String query = "select title,post from posts order by desc number";
try {
connection = connectMySql.getConnection("jdbc");
Statement s = connection.createStatement();
posts = s.executeQuery(query);
int i = 1;
while (posts.next()) {
String postTitle = posts.getString(1);
String post = posts.getString(2);
HttpSession session = request.getSession();
out.println("<h4>Welcome " + session.getAttribute("username")
+ "</h4>");
out.println("<p>");
out.print("<h3><strong>" + i + "." + postTitle
+ "</strong></h3>");
out.println("<p>" + post + "</p>");
out.print("</p><hr>");
out.print("</body></html>");
}
} catch (SQLException e) {
} finally {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are catching first exception block, however you are not printing to see what exception it has thrown.
So in your first exception block do as
} catch (SQLException e) {
e.printStackTrace();
} finally {
......
In second catch, it wouldn't have thrown any exception if an exception might have occcured in first try-catch block.
I implemented servlet, that creates XLS file. I am making a request from UI (GWT, RequestBuilder). I get the response, but is it possible to get ready file (with auto "save as" dialog box)?
Should I somehow set headers or something?
Here is my code:
Request implementation
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + "downloadLimitsFile");
try {
rb.setHeader("Content-type", "text/html");
Request response = rb.sendRequest("", new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert("fail");
}
public void onResponseReceived(Request request, Response response) {
Window.alert("file downloaded " + response.getText());
}
});
} catch (RequestException e) {
Window.alert("Failed to send the request: " + e.getMessage());
}
My servlet implementation
public void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setHeader("Content-Disposition", "attachment; filename=File.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
try {
workbook = fileExporter.prepareExcellFile();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
response.setStatus(HttpServletResponse.SC_OK);
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
response.flushBuffer();
}
It was working fine (auto file download) when I was using eg. Anchor with servlet URL, but I have to use RequestBuilder now to make a request.
Can someone help?
I am afraid it is not possible, at least you can use a third party library.
Adding the header "Content-Disposition" won't work.
I have successfully implemented signalR client for android but my problem is to get return data from server. I can able to send messages from side and it is showing at other client when i am broadcasting but i am not getting the message.
Can anybody help me how to get messages by hubproxy.on method.
String host = "serverlink";
connection = new HubConnection(host);
hub = connection.createHubProxy("myHub");
hub.subscribe(MainActivity.this);
hub.on("addChatMessage", new SubscriptionHandler() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("test");
}
});
// connection.start();
SignalRFuture<Void> awaitConnection = connection.start();
try {
awaitConnection.get();
} catch (InterruptedException e) {
System.out.println("<<<Exception>>>" + e.toString() + "<<<>>>"
+ e.getMessage());
} catch (ExecutionException e) {
System.out.println("<<<Exception>>>" + e.toString() + "<<<>>>"
+ e.getMessage());
}
joinButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
hub.invoke("InformUserName", joinEditText.getText().toString()).get();
} catch (InterruptedException e) {
System.out.println("<<<Exception>>>" + e.toString()
+ "<<<>>>" + e.getMessage());
} catch (ExecutionException e) {
System.out.println("<<<Exception>>>" + e.toString()
+ "<<<>>>" + e.getMessage());
}
}
});
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
hub.invoke("Send", joinEditText.getText().toString(), messEditText.getText().toString()).get();
} catch (InterruptedException e) {
System.out.println("<<<Exception>>>" + e.toString() + "<<<>>>"
+ e.getMessage());
} catch (ExecutionException e) {
System.out.println("<<<Exception>>>" + e.toString() + "<<<>>>"
+ e.getMessage());
}
}
});
hub.on is Not Calling how can i initialise subcriptionhandler
I've recently tried to encrypt Saml2 assertion using relaying-party service public key. Unfortunately I can't finalise even the test phase
here is my code
public class EncryptionTest {
public static void main(String args[]){
try {
// The Assertion to be encrypted
FileInputStream fis;
DataInputStream in, in2;
File f = new File("src/main/resources/AssertionTest");
byte[] buffer = new byte[(int) f.length()];
in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();
//Assertion = DataInputStream.readUTF(in);
String in_assert = new String(buffer);
System.out.println(in_assert);
org.apache.axiom.om.OMElement OMElementAssertion = org.apache.axiom.om.util.AXIOMUtil.stringToOM(in_assert);
Assertion assertion = convertOMElementToAssertion2(OMElementAssertion);
// Assume this contains a recipient's RSA public key
Credential keyEncryptionCredential;
keyEncryptionCredential = getCredentialFromFilePath("src/main/resources/cert.pem");
EncryptionParameters encParams = new EncryptionParameters();
encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
KeyEncryptionParameters kekParams = new KeyEncryptionParameters();
kekParams.setEncryptionCredential(keyEncryptionCredential);
kekParams.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
Encrypter samlEncrypter = new Encrypter(encParams, kekParams);
samlEncrypter.setKeyPlacement(KeyPlacement.PEER);
EncryptedAssertion encryptedAssertion = samlEncrypter.encrypt(assertion);
System.out.println(encryptedAssertion);
} catch (EncryptionException e) {
e.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (KeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (XMLStreamException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
public static Credential getCredentialFromFilePath(String certPath) throws IOException, CertificateException, KeyException {
InputStream inStream = new FileInputStream(certPath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(inStream);
inStream.close();
//"Show yourself!"
System.out.println(cert.toString());
BasicX509Credential cred = new BasicX509Credential();
cred.setEntityCertificate((java.security.cert.X509Certificate) cert);
cred.setPrivateKey(null);
//System.out.println(cred.toString());
return cred;
//return (Credential) org.opensaml.xml.security.SecurityHelper.getSimpleCredential( (X509Certificate) cert, privatekey);
}
public static Assertion convertOMElementToAssertion2(OMElement element) {
Element assertionSAMLDOOM = (Element) new StAXOMBuilder(DOOMAbstractFactory.getOMFactory(), element.getXMLStreamReader()).getDocumentElement();
try {
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(Assertion.DEFAULT_ELEMENT_NAME);
return (Assertion) unmarshaller.unmarshall(assertionSAMLDOOM);
} catch (Exception e1) {
System.out.println("error: " + e1.toString());
}
return null;
}
}
I constantly recive Null pointer exception in
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
How can I set GlobalSecurityConfiguration or is there different approach of encrypting Assertion which will work?
This question was laying open for too long. The problem was initialization of OpenSaml.
Simple
DefaultBootstrap.bootstrap();
helped and solved problem.