I am having this form below which performs sometimes first action and sometimes last action instead of both the actions one after another continuously.
Form:
<html>
<head>
</head>
<body>
<script language="Javascript">
function OnButton1()
{
document.Form1.action = "http://localhost:8084/WorldCupFinal/finalsearching1";
document.Form1.target="_blank";
document.Form1.submit();
document.Form1.action = "http://localhost:8084/SemiFinal/finalsearching1";
document.Form1.target="_blank";
document.Form1.submit();
}
</script>
<form name="Form1" method="post" target="_blank">
File Name <input type="text" name="t1" size="10" ><br />
<INPUT type="button" value="Button1"
name=name onclick="OnButton1();" >
</form>
</body>
</html>
finalsearching1 is java servlet program which takes input as filename searches for a file in some system depending on the action(in my local host as well as in other IP address).
But this action is only performed only one time by my servlet. I want
to execute both actions one after another or is there any way that i can execute them concurrently which takes less time. This scenario is performed by me for 2 different buttons(2 actions). I want to perform it using a single button having single text box and multiple actions takes place.
I have searched a lot and i am finding it that this can be performed using AJAX or if possible using javascript.
Could you please provide me solution for it.
Thank you for your concern in advance.
Here is my finalsearching1 program code:
import static java.awt.SystemColor.window;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import static java.io.FileDescriptor.out;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import static org.apache.tomcat.jni.Shm.buffer;
import upload.UploadDownloadFileServlet;
#WebServlet(urlPatterns = {"/finalsearching1"})
public class finalsearching1 extends HttpServlet {
private static String name,name1;
private static int a=0,p=0;
int count=0;
static URL u;
static final int BUFFER_SIZE = 1024*1024;
static HttpServletResponse response;
private static void setContentType(HttpServletResponse response) {
throw new UnsupportedOperationException("Not supported yet.");
}
private static void doGet1(String m1, HttpServletRequest request, HttpServletResponse response) {
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("t1");
if(fileName == null || fileName.equals("")){
throw new ServletException("File Name can't be null or empty");
}
File file = new File(request.getServletContext().getRealPath("")+File.separator+fileName);
if(!file.exists()){
throw new ServletException("File doesn't exists on server.");
}
System.out.println("File location on server::"+file.getAbsolutePath());
ServletContext ctx = getServletContext();
InputStream fis = new FileInputStream(file.getAbsolutePath());
String mimeType = ctx.getMimeType(file.getAbsolutePath());
response.setContentType(mimeType != null? mimeType:"application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream os = response.getOutputStream();
byte[] bufferData = new byte[1024*1024];
int read=0;
while((read = fis.read(bufferData))!= -1){
os.write(bufferData, 0, read);
}
os.flush();
os.close();
fis.close();
System.out.println("File downloaded at client successfully");
}
private static void sendFile(HttpServletResponse response, File clientFileName) throws IOException
{
ServletOutputStream op = null;
setContentType(response);
response.setHeader("Content-Disposition", "attachment; filename=\"" + clientFileName + "\"");
}
private static ServletFileUpload uploader = null;
public static void parseAllFiles(String parentDirectory,HttpServletRequest request,HttpServletResponse response) throws IOException, Exception {
PrintWriter pr=response.getWriter();
response.setContentType("text/html");
File[] filesInDirectory = new File(parentDirectory).listFiles();
if(filesInDirectory != null){
for (File f : filesInDirectory){
if(f.isDirectory()){
parseAllFiles(f.getAbsolutePath(),request,response);
}
else if(name.equalsIgnoreCase(f.getName()))
{
pr.println("File Found with path "+f.getParentFile()+"\\"+name);
String m1=f.getParentFile()+"\\"+name;
System.out.println("File to upload: " + m1);
response.setContentType("text/html");
File file = new File(m1);
System.out.println();
String ext = "."+FilenameUtils.getExtension(m1);
System.out.println(ext);
f = File.createTempFile("tmp",ext, new File("C:\\Users\\Pankaj\\Desktop\\JADE-all-4.3.3\\WorldCupFinal\\build\\web"));
String f1=f.getName();
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(m1);
out = new FileOutputStream(f);
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
System.out.println(c+" Hi");
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
pr.write("Hi..........");
pr.write("<br>");
pr.write("Download "+name+"");
pr.write("<br>");
a++;
}
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter pr=response.getWriter();
name=request.getParameter("t1");
if(name == null || name.equals("")){
throw new ServletException("File Name can't be null or empty");
}
System.out.println("name: "+name);
System.out.println("Starting the execution of a project :");
response.setContentType("text/html");
File[] files = File.listRoots();
for(File f : files){
try {
System.out.println(f.getPath());
System.out.println("response:"+response);
parseAllFiles(f.getPath(),request,response);
} catch (Exception ex) {
Logger.getLogger(finalsearching1.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(a==0)
pr.println("File Not Found");
pr.println("Starting the Execution in system 2nd");
}
public String getServletInfo() {
return "Short description";
}
}
Related
I want to encrypt using RSA_OAEP_SHA256 on the JavaScript side.
I am using the third party library asmcrypto.js :
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/asmCrypto/0.22.0/asmcrypto.js"></script>
<script>
var encrypted = asmCrypto.RSA_OAEP_SHA256.encrypt(stringToBeEncrypted, pubkey, "");
</script>
getting error: Uncaught TypeError: Cannot read property 'encrypt' of undefined.
Does anybody know the solution or any example that would help?
So finally I found the solution, I am sharing it here so that it will be helpful to someone.
I changed the library and used jsencrypt.min.js JSEncrypt
It is an updated one that supports OAEP padding.
JavaScript Code :
<script type="text/javascript" src="/RSO/includes/jsencrypt.min.js"></script>
function get(tmpSubmit)
{
<%
String key = BouncyCastlePemUtils.readPublicKey();
System.out.println("readPublicKey: " + key);
%>
alert('<%=key %>');
var publicKey = '<%=key %>';
var password = "Dhiraj is the author";
var RSAEncrypt = new JSEncrypt();
RSAEncrypt.setPublicKey(publicKey);
var encryptedPass = RSAEncrypt.encrypt(password, true);
document.write("encryptedPass: "+encryptedPass)
}
Generate Public and Private Key using openssl, please check the link below for commands.
openssl commands
Java Class to encrypt and decrypt data:
package com.demo.rsa;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.demo.util.CommonProperties;
public class PEMDemo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public String encrypt(String plainText, RSAPublicKey publicKey) throws Exception {
Cipher cipher = getCipher();
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return DatatypeConverter.printBase64Binary(encryptedText);
}
public String decrypt(String cipherText, RSAPrivateKey privateKey) throws Exception {
byte[] cipherBytes;
cipherBytes = DatatypeConverter.parseBase64Binary(cipherText);
Cipher cipher = getCipher();
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedText = cipher.doFinal(cipherBytes);
return new String(decryptedText, StandardCharsets.UTF_8);
}
private Cipher getCipher() throws Exception {
Security.addProvider(new BouncyCastleProvider());
return Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", new BouncyCastleProvider());
}
public static RSAPublicKey getPublicKey(){
RSAPublicKey publicKey = null;
try {
File publicKeyFile = new File(CommonProperties.propBag.getProperty("RSA_CONFIG_PATH")+"public_key.pem");
publicKey = BouncyCastlePemUtils.readX509PublicKey(publicKeyFile);
} catch (InvalidKeySpecException | NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
}
return publicKey;
}
public static RSAPrivateKey getPrivateKey(){
RSAPrivateKey privateKey = null;
try {
File privateKeyFile = new File(CommonProperties.propBag.getProperty("RSA_CONFIG_PATH")+"private_key.pem");
privateKey = BouncyCastlePemUtils.readPKCS8PrivateKey(privateKeyFile);
} catch (InvalidKeySpecException | NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
}
return privateKey;
}
public static void main(String[] args){
PEMDemo rsaEncriptDecrypt = new PEMDemo();
String encrypted;
try {
encrypted = rsaEncriptDecrypt.encrypt("This is plain text.", getPublicKey());
System.out.println("encrypted: " + encrypted);
// JS Encrypted cipher text
encrypted = "voxgNKCtKy6wGL/g9oi/jUqwm4lnT+Ais4ZaJ5OwJ4gozjTHl3L7yabB04tyV9UmuxfGb6EywZvrpuZRIKtqWPzO+UgW0A+5g9nPjXtDPI0qMzuv7i1E7WVjM4isJBwOC4yPdttXi4h/vbzOaR5J5r8mbyHdnxkqtuDn3o5jXOM=";
String decrypted = rsaEncriptDecrypt.decrypt(encrypted, getPrivateKey());
System.out.println("decrypted: " + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Utility class to read Public and Private Key from .PEM file
package com.demo.rsa;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import com.demo.util.CommonProperties;
public class BouncyCastlePemUtils {
public static RSAPublicKey readX509PublicKey(File file) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException {
KeyFactory factory = KeyFactory.getInstance("RSA");
try (FileReader keyReader = new FileReader(file);
PemReader pemReader = new PemReader(keyReader)) {
PemObject pemObject = pemReader.readPemObject();
byte[] content = pemObject.getContent();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
return (RSAPublicKey) factory.generatePublic(pubKeySpec);
}
}
public static RSAPrivateKey readPKCS8PrivateKey(File file) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException {
KeyFactory factory = KeyFactory.getInstance("RSA");
try (FileReader keyReader = new FileReader(file);
PemReader pemReader = new PemReader(keyReader)) {
PemObject pemObject = pemReader.readPemObject();
byte[] content = pemObject.getContent();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
return (RSAPrivateKey) factory.generatePrivate(privKeySpec);
}
}
public static String readPublicKey() throws IOException {
File publicKeyFile = new File(CommonProperties.propBag.getProperty("RSA_CONFIG_PATH")+"public_key.pem");
StringBuilder st = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(publicKeyFile))){
String s = st.toString();
while ((s = br.readLine()) != null)
st.append(s);
}
return st.toString();
}
}
Maven Dependancy:
6. Maven Dependancy:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
Server side: Spring boot + JWT Auth
Client: React app
I want to connect via websocket but whenever I try to do it I always get error in console:
WebSocket connection to 'ws://localhost:6060/ws/app/add' failed: Error during WebSocket handshake: Unexpected response code: 404
Backend:
1) Websocket configuration
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("http://localhost:6060")
.setAllowedOrigins("http://localhost:8082")
// .setAllowedOrigins("*")
.setHandshakeHandler(new DefaultHandshakeHandler(new TomcatRequestUpgradeStrategy()))
.withSockJS();
registry.addEndpoint("/add");
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
2) Controller for receiving:
#Controller
public class ChatController {
#MessageMapping("/send") // FROM FRONTEND TO HERE
#SendTo("/topic/public") // FROM HERE TO FRONTEND
public ChatMessage sendMessage(#Payload ChatMessage chatMessage) {
return chatMessage;
}
#MessageMapping("/add")
#SendTo("/topic/public")
public ChatMessage addUser(#Payload ChatMessage chatMessage,
SimpMessageHeaderAccessor headerAccessor) {
// Add username in web socket session
headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
return chatMessage;
}
}
3) Security Config
package com.winterrent.winterrent.configuration;
import com.winterrent.winterrent.security.JwtAuthenticationEntryPoint;
import com.winterrent.winterrent.security.JwtAuthenticationFilter;
import com.winterrent.winterrent.service.user.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
CustomUserDetailsService customUserDetailsService;
#Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
#Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
#Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean(BeanIds.AUTHENTICATION_MANAGER)
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
http
.cors()
.and()
.csrf()
.ignoringAntMatchers("/ws/**")
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/auth/**")
.permitAll()
.anyRequest()
.authenticated();
}
}
4) JWT Auth filter
package com.winterrent.winterrent.security;
import com.winterrent.winterrent.service.user.CustomUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
/**
* JWT token got from the request, validated and based on it loads the user associated with the token and pass
* it to Spring Security
*/
public class JwtAuthenticationFilter extends OncePerRequestFilter {
#Autowired
private JwtTokenProvider tokenProvider;
#Autowired
private CustomUserDetailsService customUserDetailsService;
private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
Long userId = tokenProvider.getUserIdFromJWT(jwt);
UserDetails userDetails = customUserDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ex) {
LOGGER.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
LOGGER.debug(request.getHeader("Sec-WebSocket-Protocol"));
if (Objects.nonNull(request.getHeader("Sec-WebSocket-Protocol"))) {
bearerToken = request.getHeader("Sec-WebSocket-Protocol");
return bearerToken.substring(15, bearerToken.length());
}
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
}
5) CORS settings
package com.winterrent.winterrent.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private final long MAX_AGE_SECS = 3600;
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:6060")
.allowedOrigins("http://localhost:8082")
// .allowedOrigins("*")
.allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
.maxAge(MAX_AGE_SECS);
}
}
Client:
const wsx123 = new WebSocket('ws://localhost:6060/ws/app/add',
['Authorization', window.localStorage.getItem('accessToken')], ['Access-Control-Allow-Credentials', 'true']);
I tried many options, but really always 404...
Has anybody any idea?
Regards!
The issue was with really bad path (404 was not stupid error) -
'ws://localhost:6060/resources/ws'
Above was correct because I had resources context path set up.
I'm using Ember for front-end and Java for back-end. On typing localhost:8080, I need to show the Ember homepage index.html. Previously, I used Node.js and the below line did the trick
res.sendfile('./public/index.html');
Now on shifting to Java, I'm unable to achieve the same result. I tried the below code.
public static void main(String[] args) throws Exception
{
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", new HHandler());
server.createContext("/getbookarray", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class HHandler implements HttpHandler
{
#Override
public void handle(HttpExchange t) throws IOException
{
File file = new File("..\\public\\index.html");
String response = FileUtils.readFileToString(file);
String encoding = "UTF-8";
t.getResponseHeaders().set("Content-Type", "text/html; charset=" + encoding);
t.getResponseHeaders().set("Accept-Ranges", "bytes");
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes("UTF-8"));
os.close();
}
}
But, unfortunately I'm getting the below error on trying to load the home page.
"Uncaught SyntaxError: Unexpected token <"
The same Ember application when processed using Node.js works fine. I guess I'm not sending the HTTP response properly. Any help is appreciated.
Maybe you have an issue with the path of your file. Also notice that the readFileToString is deprecated.
Here is a working server that will send your index.html to your frontend.
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.commons.io.FileUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
public class myServer {
public static void main(String[] args) throws Exception {
System.out.println("server ...");
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", new HHandler());
//server.createContext("/getbookarray", new HHandler());
//server.setExecutor(null); // creates a default executor
server.start();
//server.getExecutor();
}
static class HHandler implements HttpHandler {
#Override
public void handle(HttpExchange t) throws IOException {
Headers h = t.getResponseHeaders();
String line;
String resp = "";
try {
File newFile = new File("src/index.html");
System.out.println("*****lecture du fichier*****");
System.out.println("nom du fichier: " + newFile.getName());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(newFile)));
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
resp += line;
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
h.add("Content-Type", "application/json");
t.sendResponseHeaders(200, resp.length());
OutputStream os = t.getResponseBody();
os.write(resp.getBytes());
os.close();
}
}
}
You can use the lightweight server nanoHttpd. With the following code you can send your index.html file to your frontend also.
import fi.iki.elonen.NanoHTTPD;
import java.io.*;
public class App extends NanoHTTPD {
public App() throws IOException {
super(8080);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n");
}
public static void main(String[] args) {
try {
new App();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
}
}
#Override
public Response serve(NanoHTTPD.IHTTPSession session) {
File newFile = new File("src/index.html");
System.out.println("*****lecture du fichier*****");
System.out.println("nom du fichier: " + newFile.getName());
String line;
String reponse = "";
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(newFile)));
while ((line = bufferedReader.readLine()) != null){
reponse += line;
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return newFixedLengthResponse(reponse);
}
}
My first thread: Anything I try to store on database enters with value '0'
I solved that, but now I'm having another problem:
Why am I having this error when I try to login?
09-11 17:20:46.382 2577-5031/com.example.gustavo.loginregister D/NetworkSecurityConfig: No Network Security Config specified, using platform default
09-11 17:20:47.415 2577-5031/com.example.gustavo.loginregister E/Volley: [145] BasicNetwork.performRequest: Unexpected response code 404 for https://xxxxxxx.000webhostapp.com/Login.php
09-11 17:22:39.640 2577-6700/com.example.gustavo.loginregister E/Volley: [152] BasicNetwork.performRequest: Unexpected response code 404 for https://xxxxxxx.000webhostapp.com/Login.php
LoginActivity.java file:
package com.example.gustavo.loginregister;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText edtEmail = (EditText) findViewById(R.id.edtEmail);
final EditText edtSenha = (EditText) findViewById(R.id.edtSenha);
final Button btnLogin = (Button) findViewById(R.id.btnLogin);
final TextView txtCadastreSe = (TextView) findViewById(R.id.txtCadastreSe);
txtCadastreSe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registroIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registroIntent);
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = edtEmail.getText().toString();
final String password = edtSenha.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
String lastname = jsonResponse.getString("lastname");
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("lastname", lastname);
intent.putExtra("email", email);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(email, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
LoginRequest.java file:
package com.example.gustavo.loginregister;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL="https://wavecheck.000webhostapp.com/Login.php";
private Map<String, String> params;
public LoginRequest(String email, String password, Response.Listener<String> listener){
super(Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("email", email);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Login.php file:
<?php
require("Password.php");
$con = mysqli_connect("localhost", "xxx", "xxx", "xxxx");
$email = $_POST["email"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE email = ?");
mysqli_stmt_bind_param($statement, "s", $email);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colLastname, $colEmail, $colPassword);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
if (password_verify($password, $colPassword)) {
$response["success"] = true;
$response["name"] = $colName;
$response["lastname"] = $colLastname;
$response["email"] = $colEmail;
}
}
echo json_encode($response);
?>
When you visit https://wavecheck.000webhostapp.com/Login.php directly it doesn't return JSON. It returns a 404 error page "There's nothing here, yet.
This domain is ready to be registered.". This is a message from the host. Apparently you're using a FREE host, and the "wavecheck" subdomain isn't there. So you'd need to re-host your PHP script, or get in contact with the free host to figure out what happened.
I am working in a project. In which i am trying to get username from session created using the following code:-
GetCurrentUserInfo.java
package servlet;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetCurrentUserInfo extends HttpServlet
{
ServletContext contx = null;
public void init(ServletConfig config) throws ServletException
{
contx = config.getServletContext();
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
try
{
OutputStream outer = res.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outer);
String userName = (String) req.getSession().getAttribute("username");
oos.writeChars(userName);
oos.flush();
oos.close();
}
catch (Throwable e)
{
e.printStackTrace();
}
}
}
Calling.js
function getUserInfo()
{
var userInfoHttp;
if (window.XMLHttpRequest)
{
userInfoHttp = new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
userInfoHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
userInfoHttp.open("POST", "GetCurrentUserInfo", false);
userInfoHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
userInfoHttp.onreadystatechange = function ()
{
if (userInfoHttp.readyState == 4)
{
if (userInfoHttp.status == 200)
{
var res = TrimString(userInfoHttp.responseText);
alert(res);
}
}
}
userInfoHttp.send(null);
isAnnotationUpdate = false;
}
I res i am getting userName with some extra characters like this:- "���w�s�#�s�.�c�o�m"
In actual my userName is s#s.com only.
I think that 2 things can fix your encoding problem
Firstly use the OutputStreamWriter and give it encoding value
OutputStream stream = response.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
String userName=(String)req.getSession().getAttribute("username");
writer.write(userName);
writer.flush();
and then make sure your response has the correct encoding
response.setCharacterEncoding("UTF-8");
Related article : Unexpected character when downloading file client side from a servlet
UPDATE
And something else i forgot in original answer. Set the ContentTyoe of the response Object to text/plain because you are actually returning plain text chars
response.setContentType("text/plain");