How to select particular textfile - apache-poi

Using Apache POI to parse text documents and search for keywords inside them

I just simply create resume parser that parse each document(.doc, .docx) to find given keywords in folder or in sub-folder. Please read the Java-Doc of HWPFDocument.
Here is code
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.hwpf.HWPFDocument;
public class ResumeParser {
HWPFDocument document;
FileInputStream fileInputStream;
String rootFolderPath;
Map<String, List<String>> displayContent = new HashMap<String, List<String>>();
List<String> keywordList;
public ResumeParser(String rootFolderPath, List<String> keywordList) throws IOException {
this.rootFolderPath = rootFolderPath;
this.keywordList = keywordList;
startParsing();
}
public void startParsing() throws IOException {
createDisplayContent(rootFolderPath);
printContent(displayContent);
}
/**
* Creates the display content it parse the each file under given folder and
* also in sub folder. folder
*
* #param rootFolderPath
* the root folder path
*/
public void createDisplayContent(String rootFolderPath) {
File fileL = new File(rootFolderPath);
File[] fileArrL = fileL.listFiles();
for (int i = 0; i < fileArrL.length; i++) {
File fileTempL = fileArrL[i];
if (fileTempL.isFile()) {
String name = fileTempL.getName();
String extension = name.substring(name.indexOf('.') + 1, name.length()).toUpperCase();
if (extension.equals("DOC") || extension.equals("DOCX")) {
parseDocFile(fileTempL.getAbsolutePath());
}
} else if (fileTempL.isDirectory()) {
createDisplayContent(fileTempL.getAbsolutePath());
}
}
}
public void parseDocFile(String filePath) {
try {
fileInputStream = new FileInputStream(filePath);
document = new HWPFDocument(fileInputStream);
String text = document.getText().toString().toUpperCase();
Iterator<String> iteratorL = keywordList.iterator();
List<String> matchKeywordListL = new ArrayList<String>();
String keywordL = "";
while (iteratorL.hasNext()) {
keywordL = iteratorL.next().toUpperCase();
if (text.contains(keywordL)) {
matchKeywordListL.add(keywordL.toLowerCase());
}
}
displayContent.put(filePath, matchKeywordListL);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void printContent(Map<String, List<String>> displayContent) {
Iterator<String> iteratorL = displayContent.keySet().iterator();
String keyL = "";
while (iteratorL.hasNext()) {
keyL = iteratorL.next();
System.out.println("File Name: " + keyL + " Match Keywords: " + displayContent.get(keyL));
}
}
public static void main(String args[]) throws IOException {
List<String> keywordListL = new ArrayList<String>();
keywordListL.add("Java");
keywordListL.add("PHP");
keywordListL.add("Andriod");
keywordListL.add("John");
new ResumeParser("D:\\Doc", keywordListL);
}
}

Related

getDeviceId: The user 10214 does not meet the requirements to access device identifiers

I am trying to modify this app. But for the first time I have to solve the permission problem which is not happening to me. I have pasted the code and the logcat. Please tell me a solution.
getDeviceId: The user 10214 does not meet the requirements to access
device identifiers
Splah
package com.xitij.spintoearn.Activity;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.facebook.ads.AudienceNetworkAds;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;
import com.xitij.spintoearn.Models.Settings;
import com.xitij.spintoearn.Models.User;
import com.xitij.spintoearn.R;
import com.xitij.spintoearn.Util.Constant;
import com.xitij.spintoearn.Util.Ex;
import com.xitij.spintoearn.Util.Method;
import com.xitij.spintoearn.Util.RestAPI;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import cz.msebera.android.httpclient.Header;
public class Splash extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 2000;
private Constant constant;
private String GetDeviceID(){
TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String deviceID = null;
int readIMEI= ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE);
if(deviceID == null) {
if (readIMEI == PackageManager.PERMISSION_GRANTED) {
deviceID = tm.getDeviceId().toString();
}
}
return deviceID;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AudienceNetworkAds.initialize(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
Constant.DeviceID = GetDeviceID();
login(Constant.DeviceID);
//Toast.makeText(Splash.this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
finish();
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setDeniedMessage("If you reject permission,you can not use this service\n\nPlease turn on permissions at [Setting] > [Permission]")
.setPermissions(Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_NETWORK_STATE,Manifest.permission.RECORD_AUDIO)
.check();
constant = new Constant(Splash.this);
Constant.DeviceID = GetDeviceID();
Ex.getIPaddress();
if(Ex.isConnectionEnable(this) && Ex.checkAndRequestPermissions(this,this)){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//login(Constant.DeviceID);
}
},SPLASH_TIME_OUT);
}
}
public void login(final String deviceid) {
String login = RestAPI.API_Device_Login + "&deviceid=" + deviceid;
AsyncHttpClient client = new AsyncHttpClient();
client.get(login, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Response", new String(responseBody));
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
JSONArray jsonArray = jsonObject.getJSONArray(Constant.AppSid);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String success = object.getString("success");
if (success.equals("1")) {
String user_id = object.getString("user_id");
String name = object.getString("name");
String sendEmail = object.getString("email");
String userPhone = object.getString("phone");
String userCode = object.getString("user_code");
constant.sharedEditor.putBoolean(constant.isLogin, true);
constant.sharedEditor.putString(constant.profileId, user_id);
constant.sharedEditor.putString(constant.userName, name);
constant.sharedEditor.putString(constant.userEmail, sendEmail);
constant.sharedEditor.putString(constant.userPhone, userPhone);
constant.sharedEditor.putString(constant.userCode, userCode);
constant.sharedEditor.commit();
LoadSettings();
Constant.user =new User("00",name,sendEmail,"000",userPhone,userCode);
Method.UserLoginLogs(user_id,"Login",Constant.DeviceID);
Intent intent=new Intent(getBaseContext(),MainActivity.class);
startActivity(intent);
finish();
} else {
Intent inst = new Intent(Splash.this, Login.class);
inst.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inst);
finish();
// Ex.okAlertBox(getResources().getString(R.string.login_failed_message));
//Toast.makeText(Login.this, getResources().getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Splash.this);
alertDialogBuilder.setTitle("Server Maintenance");
alertDialogBuilder.setMessage("System is Undergoing Maintenance. Please try again later.");
alertDialogBuilder.setPositiveButton(getApplication().getResources().getString(R.string.ok_message),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
public void LoadSettings() {
AsyncHttpClient client = new AsyncHttpClient();
client.get(RestAPI.API_Settings, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Response-ls", new String(responseBody));
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
JSONArray jsonArray = jsonObject.getJSONArray(Constant.AppSid);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String app_name = object.getString("app_name");
String app_logo = object.getString("app_logo");
String app_version = object.getString("app_version");
String app_author = object.getString("app_author");
String app_contact = object.getString("app_contact");
String app_email = object.getString("app_email");
String app_website = object.getString("app_website");
String app_description = object.getString("app_description");
String app_developed_by = object.getString("app_developed_by");
String app_faq = object.getString("app_faq");
String app_privacy_policy = object.getString("app_privacy_policy");
String publisher_id = object.getString("publisher_id");
boolean interstital_ad = Boolean.parseBoolean(object.getString("interstital_ad"));
String interstital_ad_id = object.getString("interstital_ad_id");
String interstital_ad_click = object.getString("interstital_ad_click");
boolean banner_ad = Boolean.parseBoolean(object.getString("banner_ad"));
String banner_ad_id = object.getString("banner_ad_id");
boolean rewarded_video_ads = Boolean.parseBoolean(object.getString("rewarded_video_ads"));
String rewarded_video_ads_id = object.getString("rewarded_video_ads_id");
String redeem_currency = object.getString("redeem_currency");
String redeem_points = object.getString("redeem_points");
String redeem_money = object.getString("redeem_money");
String minimum_redeem_points = object.getString("minimum_redeem_points");
String payment_method1 = object.getString("payment_method1");
String payment_method2 = object.getString("payment_method2");
String payment_method3 = object.getString("payment_method3");
String payment_method4 = object.getString("payment_method4");
String daily_spin_limit = object.getString("daily_spin_limit");
String ads_frequency_limit= object.getString("ads_frequency_limit");
String video_add_point= object.getString("video_add_point");
String app_refer_reward= object.getString("app_refer_reward");
String registration_reward= object.getString("registration_reward");
String video_ads_limit= object.getString("daily_rewarded_video_ads_limits");
Constant.settings = new Settings(app_name, app_logo, app_version, app_author, app_contact, app_email, app_website, app_description, app_developed_by,
app_faq, app_privacy_policy, publisher_id, interstital_ad_id, interstital_ad_click, banner_ad_id, rewarded_video_ads_id, redeem_currency, redeem_points,
redeem_money, minimum_redeem_points, payment_method1, payment_method2, payment_method3, payment_method4, interstital_ad, banner_ad, rewarded_video_ads,daily_spin_limit,ads_frequency_limit,video_add_point,app_refer_reward,registration_reward,video_ads_limit);
Log.d("Response-ls",ads_frequency_limit );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
}
Constant
package com.xitij.spintoearn.Util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import com.xitij.spintoearn.Models.CoinHistory;
import com.xitij.spintoearn.Models.Settings;
import com.xitij.spintoearn.Models.SpinCounter;
import com.xitij.spintoearn.Models.User;
import com.xitij.spintoearn.Models.UserBalance;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.reward.RewardedVideoAd;
public class Constant {
public static final String AppSid="spin";
public static final int POINT_VIDEO_MIN=1;
public static final int POINT_VIDEO_MAX=100;
public static final int RATE_POINT=1000;
public static final int DAILY_CHECK=100;
public static String Total_Point;
//Enter milliseconds
public static final int Waitsecond=8000;
public static String PublicIP;
public static String DeviceID;
public static final String ReferPoint = "10";
public static final String VIDEO_AD_ID="ca-app-pub-3940256099942544/8691691433";
public static final String INSTE_AD_ID="ca-app-pub-3940256099942544/1033173712";
public static final String AD_ID= "#";
public static int AD_COUNT = 0;
public static int VIDEO_AD_COUNT= 0;
public static InterstitialAd mInterstitial;
public static RewardedVideoAd mRewardedVideoAd;
public static User user;
public static UserBalance userBalance;
public static CoinHistory coinHistory;
public static Settings settings;
public static SpinCounter spinCounter;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor sharedEditor;
private Activity activity;
private final String loginPerfm = "login";
public String isLogin = "isLogin";
private String deviceId = "deviceId";
public String profileId = "profileId";
public String userEmail = "userEmail";
public String userPassword = "userPassword";
public String userName = "userName";
public String userPhone = "userPhone";
public String userCode = "userCode";
public String Spin_Count = "Spin_Count";
#SuppressLint("CommitPrefEdits")
public Constant(Activity activity) {
this.activity = activity;
sharedPreferences = activity.getSharedPreferences(loginPerfm, 0); // 0 - for private mode
sharedEditor = sharedPreferences.edit();
}
}
logcat
2021-03-08 08:05:02.525 14296-14296/? E/itij.spintoear: Unknown bits set in runtime_flags: 0x8000
2021-03-08 08:05:04.622 14296-14296/com.xitij.spintoearn E/fdsan: attempted to close file descriptor 74, expected to be unowned, actually owned by FILE* 0x76c3b37018
2021-03-08 08:05:04.758 14296-14296/com.xitij.spintoearn E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xitij.spintoearn, PID: 14296
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xitij.spintoearn/com.xitij.spintoearn.Activity.Splash}: java.lang.SecurityException: getDeviceId: The user 10214 does not meet the requirements to access device identifiers.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3547)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7581)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.SecurityException: getDeviceId: The user 10214 does not meet the requirements to access device identifiers.
at android.os.Parcel.createException(Parcel.java:2071)
at android.os.Parcel.readException(Parcel.java:2039)
at android.os.Parcel.readException(Parcel.java:1987)
at com.android.internal.telephony.ITelephony$Stub$Proxy.getDeviceId(ITelephony.java:10389)
at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:1620)
at com.xitij.spintoearn.Activity.Splash.GetDeviceID(Splash.java:53)
at com.xitij.spintoearn.Activity.Splash.onCreate(Splash.java:99)
at android.app.Activity.performCreate(Activity.java:7805)
at android.app.Activity.performCreate(Activity.java:7794)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3378)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3547) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:264) 
at android.app.ActivityThread.main(ActivityThread.java:7581) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980) 

Using Hashmap making plagiarism checker based on Java

it reads input.txt file and compared with target file.
If more than 3words are same as input file, the program should say plagiarized from .
I used substring so the program only compares first 3 letters.
should use tokenized? or how can it compared
Here is my code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class CheckPlagiarism{
public static void main(String args[]) throws FileNotFoundException
{
//Init HashMap
HashMap<String, Integer> corpus = new HashMap<>();
String fileName = args[0];
String tragetName = args[1];
int matchCount = Integer.parseInt(args[2]);
Scanner scanner = new Scanner(new File(fileName));
while(scanner.hasNext())
{
String[] line = scanner.nextLine().split(":");
corpus.put(line[1], Integer.parseInt(line[0]));
}
boolean found = false;
scanner = new Scanner(new File(tragetName));
while(scanner.hasNext())
{
String line = scanner.nextLine();
line = line.string(0,matchCount);
for(Entry<String, Integer> temp: corpus.entrySet()){
String key=temp.getKey();
if(key.contains(line))
{
System.out.println("Plagiarized from " + temp.getValue());
found = true;
break;
}
}
}
if(!found)
{
System.out.println("Not Plagiarized");
}
}
}

Proper way to send e-mail in managed bean

I'm using this Java code to send messages in JSF page:
import com.web.utils.SendEmail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.mail.MessagingException;
import javax.servlet.http.Part;
#Named
#ViewScoped
public class Contacts implements Serializable
{
private static final long serialVersionUID = 1L;
private Part file;
private String name;
private String senderEmail;
private String telephone;
private String comment;
private String result;
public Contacts()
{
}
public void sendEmail() throws IOException, MessagingException
{
String[] to =
{
"test#gmail.com"
}; // list of recipient email addresses
String subject = name + " " + senderEmail + " " + telephone;
SendEmail mail = new SendEmail();
result = mail.intiSendEmail(to, subject, comment, file);
}
public void upload()
{
if (file != null)
{
try (InputStream inputStream = file.getInputStream(); FileOutputStream outputStream = new FileOutputStream("D:" + File.separator + "files" + File.separator + file.getSubmittedFileName()))
{
int bytesRead = 0;
final byte[] chunck = new byte[1024];
while ((bytesRead = inputStream.read(chunck)) != -1)
{
outputStream.write(chunck, 0, bytesRead);
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload successfully ended!"));
}
catch (IOException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload failed!"));
}
}
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSenderEmail()
{
return senderEmail;
}
public void setSenderEmail(String senderEmail)
{
this.senderEmail = senderEmail;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public String getComment()
{
return comment;
}
public void setComment(String comment)
{
this.comment = comment;
}
public String getResult()
{
return result;
}
public void setResult(String result)
{
this.result = result;
}
public Part getFile()
{
return file;
}
public void setFile(Part file)
{
this.file = file;
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.http.Part;
public class SendEmail implements Serializable
{
private String USER_NAME = "test";
private String PASSWORD = "test!";
public String intiSendEmail(String[] to, String subject, String body, Part file) throws IOException, MessagingException
{
String status;
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", USER_NAME);
props.put("mail.smtp.password", PASSWORD);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(USER_NAME));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++)
{
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++)
{
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
/**
* If file is not attached skip setting content
*/
if (file != null)
{
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
ByteArrayDataSource ds = new ByteArrayDataSource(file.getInputStream(), file.getContentType());
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
Transport transport = session.getTransport("smtp");
transport.connect(host, USER_NAME, PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae)
{
ae.printStackTrace();
return status = "Cannot send Message!";
}
catch (MessagingException me)
{
me.printStackTrace();
return status = "Cannot send Message!";
}
return status = "Message is send!";
}
/**
* For testing
*/
public void upload()
{
Part file = null;
if (file != null)
{
try (InputStream inputStream = file.getInputStream(); FileOutputStream outputStream = new FileOutputStream("D:" + File.separator + "files" + File.separator + file.getSubmittedFileName()))
{
int bytesRead = 0;
final byte[] chunck = new byte[1024];
while ((bytesRead = inputStream.read(chunck)) != -1)
{
outputStream.write(chunck, 0, bytesRead);
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload successfully ended!"));
}
catch (IOException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload failed!"));
}
}
}
}
I added thread pool in order to speedup page performance. But I as you can see the code execution is not properly handled when package is redeployed. What it the proper way to stop Thread pool in JSF?

Read text file and display it in Jtable?

i need to read the contents of text file, line by line and display it on the Jtable, the table should be editable by users as needed, Any help Appreciated. I am new to Java. Thank You.
My Text File: File Name(people.txt)
COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY COLUMN_DEFAULT EXTRA
Names VARCHAR(500) NO
Address VARCHAR(500) NO
My Code So Far:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class readtext {
static public void main(String[] arg){
JScrollPane scroll;
JTable table;
DefaultTableModel model;
String fname="people";
try
{
FileInputStream fstream = new FileInputStream("D:/joy/text/"+fname+".txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine,str = null;
//Read File Line By Line
String text = "";
Vector myVector = new Vector();
while ((strLine = br.readLine()) != null) //loop through each line
{
myVector.add(strLine );
// Print the content on the console
text +=(strLine+"\n"); // Store the text file in the string
}
in.close();//Close the input stream
int i=0;
String fline=myVector.elementAt(0).toString();
String[] sp=fline.split("\\s+");
for(String spt:sp){
System.out.println(spt);
//model = new DefaultTableModel(spt, ); // I dont know how to put the strings
into Jtable here
table = new JTable(){
public boolean isCellEditable(int row, int column){
return false;
}
};
int a=0;// for text box name
for(i=1;i<myVector.size();i++){
str=myVector.elementAt(i).toString();
String[] res =str.split("\\s+");
int k=0;
for(String st:res)
System.out.println(st);
k++;a++; }
} }
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thank You.
File Content: (Each attribute is separated by a semicolon and each line is a record.)
Hello1;123
World1;234
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class FileToJTable {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
new FileToJTable().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
try {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JTable table = new JTable();
String readLine = null;
StudentTableModel tableModel = new StudentTableModel();
File file = new File(""/*Give your File Path here*/);
FileReader reader = new FileReader(file);
BufferedReader bufReader = new BufferedReader(reader);
List<Student> studentList = new ArrayList<Student>();
while((readLine = bufReader.readLine()) != null) {
String[] splitData = readLine.split(";");
Student student = new Student();
student.setName(splitData[0]);
student.setNumber(splitData[1]);
studentList.add(student);
}
tableModel.setList(studentList);
table.setModel(tableModel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.setTitle("File to JTable");
frame.pack();
frame.setVisible(true);
} catch(IOException ex) {}
}
class Student {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
class StudentTableModel extends AbstractTableModel {
private List<Student> list = new ArrayList<Student>();
private String[] columnNames = {"Name", "Number"};
public void setList(List<Student> list) {
this.list = list;
fireTableDataChanged();
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return list.size();
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return list.get(rowIndex).getName();
case 1:
return list.get(rowIndex).getNumber();
default:
return null;
}
}
}
}
Well i didnt read ur code...however i'm telling u one of the simplest way of doing this...hope this helps
Define a DefaultTableModel:
String columns[] = { //Column Names// };
JTable contactTable = new JTable();
DefaultTableModel tableModel;
// specify number of columns
tableModel = new DefaultTableModel(0,2);
tableModel.setColumnIdentifiers(columns);
contactTable.setModel(tableModel);
Reading from text file:
String line;
BufferedReader reader;
try{
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null)
{
tableModel.addRow(line.split(", "));
}
reader.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();
}
Also, if you want to allow users to edit the data, then you need to set a TableCellEditor on the cells that you want people to edit. You probably also want to start using a TableModel instead of hard coding the data in the JTable itself.
See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

Javafx, get the object referenced by a TableCell

I have the following Callback listening on the selected Cell of a TableView:
Callback<TableColumn<MyFTPFile,String>, TableCell<MyFTPFile,String>> cellFactory =
new Callback<TableColumn<MyFTPFile,String>, TableCell<MyFTPFile,String>>() {
public TableCell<MyFTPFile,String> call(TableColumn<MyFTPFile,String> p) {
TableCell<MyFTPFile,String> cell = new TableCell<MyFTPFile, String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : getString());
setGraphic(null);
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
};
cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getClickCount() > 1) {
TableCell<MyFTPFile,String> c = (TableCell<MyFTPFile,String>) event.getSource();
ftpObservablelist = MyFTPClient.getInstance().getFtpObservableList();
ftpTable.setItems(ftpObservablelist);
}
}
});
Now, I would like to get the MyFTPFile object which is referenced by the cell, which is doubleclicked, so that i can pass it to another class and do stuff... Any Idea how to do that???
Thanks in advance.
The MyFTPFile object is associated with the cell's row, so, as the asker pointed out in his comment, it is retrievable via cell.getTableRow().getItem().
At first I thought this should be cell.getItem(), which returns the data value associated with the cell. However, most of the time, the cell data value will be a property of the backing item rather than the object itself (for example a filename field of a MyFTPFile object).
Executable sample for the curious:
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TableClickListener extends Application {
public static void main(String[] args) {
launch(args);
}
class FTPTableCell<S, T> extends TextFieldTableCell<S, T> {
FTPTableCell() {
super();
addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getClickCount() > 1 && getItem() != null) {
System.out.println("Sending " + getTableRow().getItem() + " to the FTP client");
}
}
});
}
}
final Callback<TableColumn<MyFTPFile, String>, TableCell<MyFTPFile, String>> FTP_TABLE_CELL_FACTORY =
new Callback<TableColumn<MyFTPFile, String>, TableCell<MyFTPFile, String>>() {
public TableCell<MyFTPFile, String> call(TableColumn<MyFTPFile, String> p) {
return new FTPTableCell<>();
}
};
#Override
public void start(final Stage stage) {
final TableView<MyFTPFile> table = new TableView<>();
final TableColumn<MyFTPFile, String> filenameColumn = new TableColumn<>("Filename");
filenameColumn.setCellValueFactory(new PropertyValueFactory<MyFTPFile, String>("filename"));
filenameColumn.setCellFactory(FTP_TABLE_CELL_FACTORY);
filenameColumn.setMinWidth(150);
final TableColumn<MyFTPFile, String> ratingColumn = new TableColumn<>("Rating");
ratingColumn.setCellValueFactory(new PropertyValueFactory<MyFTPFile, String>("rating"));
ratingColumn.setCellFactory(FTP_TABLE_CELL_FACTORY);
ratingColumn.setMinWidth(20);
table.getColumns().setAll(filenameColumn, ratingColumn);
table.getItems().setAll(
new MyFTPFile("xyzzy.txt", 10),
new MyFTPFile("management_report.doc", 1),
new MyFTPFile("flower.png", 7)
);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
stage.setScene(new Scene(new Group(table)));
stage.show();
}
public class MyFTPFile {
private final String filename;
private final int rating;
MyFTPFile(String filename, int rating) {
this.filename = filename;
this.rating = rating;
}
public String getFilename() {
return filename;
}
public int getRating() {
return rating;
}
#Override
public String toString() {
return "MyFTPFile{" +
"filename='" + filename + '\'' +
", rating=" + rating +
'}';
}
}
}

Resources