Error enlarging buttons on eclipse - eclipse

Hello im trying to enlarge my buttons on eclipse. I found this code on the web that suppose to fix it
but it keeps giving me the error
Error: Could not find or load main class testEclipse.FixIcons
Any idea what can i do?
Im pretty new at this .. thanks
package testEclipse;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.imgscalr.Scalr;
import com.mortennobel.imagescaling.AdvancedResizeOp;
import com.mortennobel.imagescaling.ResampleOp;
/**
* Small utility to double the size of eclipse icons for QHD monitors.
*
* #author David Levy
* #since 2014/04/10
*
*/
public class FixIcons {
private static final Logger logger = Logger.getLogger(FixIcons.class);
public static final void main(String[] args) {
try {
Options options = new Options();
options.addOption(new Option("b", "baseDir", true,
"This is the base directory where we'll parse jars/zips"));
options.addOption(new Option("o", "outputDir", true,
"This is the base directory where we'll place output"));
for (Option o : new ArrayList<Option>(options.getOptions())) {
o.setRequired(true);
}
GnuParser parser = new GnuParser();
CommandLine commandLine = parser.parse(options, args);
String baseDirArg = "D:\\things\\tools\\eclipse";
logger.info("Base directory: " + baseDirArg);
String outputDirArg = "D:\\things\\tools\\eclipsetmp";
logger.info("Output directory: " + outputDirArg);
File base = new File(baseDirArg);
if (!base.exists() || !base.canRead() || !base.isDirectory()) {
logger.error("Unable to read from base directory");
return;
}
File output = new File(outputDirArg);
if (!output.exists() || !output.canRead() || !output.canWrite()
|| !output.isDirectory()) {
logger.error("Unable to write to output director");
return;
}
if (base.list() == null || base.list().length == 0) {
logger.error("The base directory is empty");
return;
}
if (output.list() != null && output.list().length != 0) {
logger.error("The output directory is not empty");
return;
}
processDirectory(base, output);
} catch (ParseException e) {
logger.error("Unable to parse arguments: " + e.getMessage());
} catch (Exception e) {
logger.error("Unexpected error: " + e.getMessage(), e);
}
}
public static void processDirectory(File directory, File outputDirectory)
throws Exception {
logger.info("Processing directory [" + directory.getAbsolutePath()
+ "]");
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
File targetDir = new File(outputDirectory.getAbsolutePath()
+ File.separator + file.getName());
logger.info("Creating directory: "
+ targetDir.getAbsolutePath());
targetDir.mkdir();
processDirectory(file, targetDir);
} else {
File targetFile = new File(outputDirectory.getAbsolutePath()
+ File.separator + file.getName());
if (file.getName().toLowerCase().endsWith(".zip")
|| file.getName().toLowerCase().endsWith(".jar")) {
logger.info("Processing archive file: "
+ file.getAbsolutePath());
ZipFile zipSrc = new ZipFile(file);
Enumeration<? extends ZipEntry> srcEntries = zipSrc.entries();
ZipOutputStream outStream = new ZipOutputStream(
new FileOutputStream(targetFile));
while (srcEntries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) srcEntries.nextElement();
logger.info("Processing zip entry [" + entry.getName()
+ "]");
ZipEntry newEntry = new ZipEntry(entry.getName());
try {
outStream.putNextEntry(newEntry);
} catch (Exception e) {
if (!e.getMessage().startsWith("duplicate entry: ")) {
logger.error("error: ", e);
} else {
logger.info(e.getMessage(), e);
}
outStream.closeEntry();
continue;
}
BufferedInputStream bis = new BufferedInputStream(
zipSrc.getInputStream(entry));
if (ImageType.findType(entry.getName()) != null) {
processImage(zipSrc.getName() + "!/" + entry.getName(), bis, outStream);
} else {
IOUtils.copy(bis, outStream);
}
outStream.closeEntry();
bis.close();
}
zipSrc.close();
outStream.close();
} else if (ImageType.findType(file.getName()) != null) {
logger.info("Processing image: " + file.getAbsolutePath());
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(targetFile);
processImage(file.getName(), inStream, outStream);
} finally {
IOUtils.closeQuietly(inStream);
IOUtils.closeQuietly(outStream);
}
} else {
logger.info("Processing : " + file.getAbsolutePath());
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(targetFile);
IOUtils.copy(inStream, outStream);
} finally {
IOUtils.closeQuietly(inStream);
IOUtils.closeQuietly(outStream);
}
}
}
}
}
public static void processImage(String fileName, InputStream input,
OutputStream output) throws IOException {
logger.info("Scaling image: " + fileName);
boolean imageWriteStarted = false;
try {
BufferedImage out = ImageIO.read(input);
int outWidth = out.getWidth() * 2;
int outHeight = out.getHeight() * 2;
BufferedImage rescaledOut = createResizedCopy(out, outWidth, outHeight);
ImageIO.write(rescaledOut, ImageType.findType(fileName).name(),
output);
} catch (Exception e) {
if (imageWriteStarted) {
throw new RuntimeException("Failed to scale image [" + fileName
+ "]: " + e.getMessage(), e);
} else {
logger.error(
"Unable to scale [" + fileName + "]: " + e.getMessage(),
e);
IOUtils.copy(input, output);
}
}
}
private static BufferedImage createResizedCopy(BufferedImage originalImage, int scaledWidth, int scaledHeight) {
try {
// Resample failed - maybe the image was too small, try another way (Scalr)
BufferedImage scaledBI = Scalr.resize(originalImage, Scalr.Method.ULTRA_QUALITY, scaledWidth, scaledHeight);
return scaledBI;
} catch (RuntimeException e) {
return scale(originalImage, 2.0);
}
}
private static BufferedImage scale(BufferedImage source,double ratio) {
int w = (int) (source.getWidth() * ratio);
int h = (int) (source.getHeight() * ratio);
BufferedImage bi = getCompatibleImage(w, h);
Graphics2D g2d = bi.createGraphics();
double xScale = (double) w / source.getWidth();
double yScale = (double) h / source.getHeight();
AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
g2d.drawRenderedImage(source, at);
g2d.dispose();
return bi;
}
private static BufferedImage getCompatibleImage(int w, int h) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
return image;
}
}

Related

How to read datamatrix embedded in document?

I try to read a datamatrix which is embedded into a document.
This is for an opensource project which helps to create and read 2DCODE standard.
I try with this code :
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ZxingTest {
#Test
public void test() {
readQRCode("sfr-facture-1048469311-1.jpg");
readQRCode("sfr-facture-1048469311-1.png");
}
public static void readQRCode(String fileName) {
System.out.println("Try reading " + fileName);
File file = new File(fileName);
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (image == null)
return;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
// hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(BarcodeFormat.DATA_MATRIX));
decode(image, hints);
}
public static void decode(BufferedImage tmpBfrImage, Hashtable<DecodeHintType, Object> hintsMap) {
if (tmpBfrImage == null)
throw new IllegalArgumentException("Could not decode image.");
LuminanceSource tmpSource = new BufferedImageLuminanceSource(tmpBfrImage);
BinaryBitmap tmpBitmap = new BinaryBitmap(new HybridBinarizer(tmpSource));
MultiFormatReader tmpBarcodeReader = new MultiFormatReader();
Result tmpResult;
String tmpFinalResult;
try {
if (hintsMap != null && !hintsMap.isEmpty())
tmpResult = tmpBarcodeReader.decode(tmpBitmap, hintsMap);
else
tmpResult = tmpBarcodeReader.decode(tmpBitmap);
// setting results.
tmpFinalResult = String.valueOf(tmpResult.getText());
System.out.println("tmpFinalResult=" + tmpFinalResult);
} catch (Exception tmpExcpt) {
tmpExcpt.printStackTrace();
}
}
}
and those images found on the net :
sfr-facture-1048469311-1.jpg
sfr-facture-1048469311-1.png
But I get this exception regardless of the image format: com.google.zxing.NotFoundException
May you advise me an lib which parses the page and detect the datamatrix coordinates for a pre-processing cropping?
Or a better a example of code which read the datamatrix?
I have a solution to my problem. I use opencv to locate any barcode then, after extraction according to the returned coordinates, I read them with zxing.
I based my solution the work of http://karthikj1.github.io/BarcodeLocalizer/
this the code i use :
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import barcodelocalizer.Barcode;
import barcodelocalizer.CandidateResult;
import barcodelocalizer.ImageDisplay;
import barcodelocalizer.MatrixBarcode;
import barcodelocalizer.TryHarderFlags;
public class OpencvUtils {
private static boolean SHOW_INTERMEDIATE_STEPS = false;
private static boolean showImages = false;
public static String process_bufferedImage(BufferedImage bufferedImage) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(bufferedImage, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding buffered image " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
public static String process_image(String imgFile) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(imgFile, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding " + imgFile + " " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
private static String decodeBarcode(List<CandidateResult> candidateCodes, String filename, String caption) {
// decodes barcode using ZXing and either print the barcode text or says no
// barcode found
BufferedImage decodedBarcode = null;
String title = null;
Result result = null;
String barcodeText = null;
for (CandidateResult cr : candidateCodes) {
BufferedImage candidate = cr.candidate;
decodedBarcode = null;
LuminanceSource source = new BufferedImageLuminanceSource(candidate);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
try {
result = reader.decode(bitmap, hints);
decodedBarcode = candidate;
title = filename + " " + caption + " - barcode text " + result.getText() + " " + cr.getROI_coords();
} catch (ReaderException re) {
}
if (decodedBarcode == null) {
title = filename + " - no barcode found - " + cr.getROI_coords();
if (showImages)
ImageDisplay.showImageFrame(candidate, title);
} else {
if (showImages)
ImageDisplay.showImageFrame(decodedBarcode, title);
System.out.println("Barcode text for " + filename + " is " + result.getText());
barcodeText = result.getText();
}
}
return barcodeText;
}
}
i added the method process_bufferedImage which process a java.awt.image.BufferedImage of a String filename.
And this sub-method to get the matrix of the BufferedImage bi.
protected Mat loadBufferedImage(BufferedImage bi) throws IOException {
// reads the BufferedImage passed in parameter
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bi, "png", byteArrayOutputStream);
byteArrayOutputStream.flush();
Mat mat = Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.IMREAD_UNCHANGED);
return mat;
}

Send Message to All in Client Server Chat Application in JavaFX

I was able to send message to clients connected to server but when
When Client Bunny sends message to Joel(receives message) and vice versa.
When second time Bunny sends message to Joel (doesn't receive message).
How do I iterate hashtable loop again to send and receive messages.
Server Class
import java.io.*; //Input and output to read and write data.
import java.net.*; //serversocket and initaddress
import java.util.Date; //to get date
import java.util.Enumeration; //enumeration
import java.util.Hashtable; // hashtable
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javafx.application.Application; //
import javafx.application.Platform; //platformrun later to append text
import javafx.event.EventHandler; // on click actions
import javafx.geometry.Insets; //insets
import javafx.geometry.Pos; //position
import javafx.scene.Scene; //scene
import javafx.scene.control.TextArea; //textarea
import javafx.scene.layout.StackPane; //stackpane
import javafx.stage.Stage; //stage
import javafx.stage.WindowEvent; //event close
public class Server extends Application { //class server
static InetAddress inetAddress; //inetaddress
private final Hashtable<Object, Object> outputStreams = new Hashtable(); //hashtable
TextArea textarea = new TextArea(); //textarea
static DataInputStream inputFromClient = null; //datainputstream
static DataOutputStream outputToClient = null; //dataoutputstream
static int clientNo = 0; //client connected
static ServerSocket serverSocket; //server socket
Hashtable<Object, Object> hmap = new Hashtable<>();
#Override // Override the start method in the Application class
public void start(Stage primaryStage) { //Stage to show everything
StackPane root = new StackPane(); //root add all the elements
root.setPadding(new Insets(10, 10, 10, 10)); //padding
root.setAlignment(textarea, Pos.CENTER); //positioning textarea to center
textarea.setMaxSize(400, 400); //maxsize of textarea
textarea.setWrapText(true); //wraptext for the textarea
new Thread(() -> { //thread to hold the server for the connections
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8001); //The server creates a server socket and, once a connection to a client is established, connects to the client with a client socket.
textarea.appendText("MultiThreadServer started at " + new Date() + '\n'); //server started with date.
while (true) { //accept multiple connections
// Listen for a new connection request
Socket socket = serverSocket.accept(); //listening for new connection from server port.
// inputFromClient = new DataInputStream(socket.getInputStream());
outputToClient = new DataOutputStream(socket.getOutputStream()); //outputstream to output to client
// Increment clientNo
clientNo++;
Platform.runLater(() -> {
// Display the client number
textarea.appendText("Starting thread for client " + clientNo + " at " + new Date() + '\n');
// Find the client's host name, and IP address
InetAddress inetAddress = socket.getInetAddress();
textarea.appendText("Client " + clientNo + "'s host name is " + inetAddress.getHostName() + "\n");
textarea.appendText("Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + "\n");
});
HandleAClient hd = new HandleAClient(socket);
hmap.put(socket, outputToClient);
hd.start();
// outputStreams.put(socket, outputToClient); //using hashtable to store client socket and outputstream
// Create and start a new thread for the connection
// new HandleAClient(this, socket);
}
} catch (IOException ex) {
textarea.appendText(ex + " \n");
}
}).start();
root.getChildren().addAll(textarea); // add UI elements to the root
Scene scene = new Scene(root, 450, 400); // creating scene of size 450 width and height 500
primaryStage.setTitle("Server"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { //close scene
#Override
public void handle(WindowEvent t) {
primaryStage.close();
Platform.exit();
System.exit(0);
}
});
}
// Used to get the output streams
Enumeration getOutputStreams() {
return outputStreams.elements();
}
// Used to send message to all clients
void sendToAll(String message) {
// Go through hashtable and send message to each output stream
for (Enumeration e = getOutputStreams(); e.hasMoreElements();) {
DataOutputStream dout = (DataOutputStream) e.nextElement();
try {
// Write message
dout.writeUTF(message);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
class HandleAClient extends Thread {
private Socket socket; // A connected socket
private String text = "";
/**
* Construct a thread
*/
public HandleAClient(Socket socket) throws IOException {
this.socket = socket;
}
/**
* Run a thread
*/
public void run() {
try {
// Create data input stream
inputFromClient = new DataInputStream(socket.getInputStream()); //receive input from client
textarea.appendText(new Date() + " Connection from " + socket + "\n");//showing connection from client
text = inputFromClient.readUTF(); // read string or message from client
// serversocket.sendToAll(text);
Set set = hmap.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println("key " + entry.getKey() + " : " + entry.getValue());
DataOutputStream dout = (DataOutputStream) entry.getValue();
dout.writeUTF(text);
dout.flush();
}
Platform.runLater(() -> {
textarea.appendText(new Date() + " " + text + "\n");//append text
});
} catch (IOException e) {
textarea.appendText("Error " + e + " \n");
try {
this.socket.close(); //socket close
} catch (IOException ex) {
textarea.appendText("Error " + e + " \n");
}
e.printStackTrace();
}
}
}
public static void main(String[] args) { //The keyword void simply tells the compiler that main( ) does not return a value.
launch(args);
}
}
Client Class
import java.io.*; //Input and output to read and write data.
import java.net.*; //serversocket and initaddress
import javafx.application.Application; //
import javafx.application.Platform; //platformrun later to append text
import javafx.event.EventHandler; // on click actions
import javafx.geometry.Insets; //insets
import javafx.geometry.Pos; //position
import javafx.scene.Scene; //scene
import javafx.scene.control.TextArea; //textarea
import javafx.scene.layout.StackPane; //stackpane
import javafx.stage.Stage; //stage
import javafx.stage.WindowEvent; //event close
import javafx.scene.control.Button; // button
import javafx.scene.control.Label; //label
import javafx.scene.control.TextField; //textfield
public class Client extends Application {
// IO streams
static DataOutputStream toServer = null; //datainputstream
static DataInputStream fromServer = null; //dataoutputstream
Label usernamelabel = new Label("Set your name :"); //set name label
Label textarealabel = new Label("Type your message in the textarea"); //text label
Label textlabel = new Label("Enter Text :"); //enter text
TextField textfield = new TextField(); //textfield
TextField namefield = new TextField(); //name field
Button send = new Button("Send"); //sendbutton
TextArea messagefield = new TextArea(); //textarea
static ServerSocket serverSocket; //serversocket
// Override the start method in the Application class
public void start(Stage primaryStage) throws IOException {
StackPane root = new StackPane(); //stacpane
root.setPadding(new Insets(10, 10, 10, 10));
StackPane.setAlignment(usernamelabel, Pos.TOP_LEFT);
namefield.setMaxWidth(200);
StackPane.setAlignment(namefield, Pos.TOP_CENTER);
StackPane.setMargin(textlabel, new Insets(30, 0, 0, 0));
StackPane.setMargin(textfield, new Insets(30, 0, 0, 0));
StackPane.setAlignment(textlabel, Pos.TOP_LEFT);
textfield.setMaxWidth(200);
StackPane.setAlignment(textfield, Pos.TOP_CENTER);
StackPane.setAlignment(send, Pos.BOTTOM_CENTER);
messagefield.setMaxSize(450, 250);
StackPane.setAlignment(textarealabel, Pos.BOTTOM_CENTER);
StackPane.setMargin(textarealabel, new Insets(0, 0, 35, 0));
StackPane.setAlignment(messagefield, Pos.CENTER);
root.getChildren().addAll(usernamelabel, namefield, send, messagefield, textarealabel, textlabel, textfield); //adding all the UI elements
// Create a scene and place it in the stage
Scene scene = new Scene(root, 500, 400);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
send.setOnAction(e -> { //send button action
try {
if (namefield.getText().trim().length() == 0) { //name field is empty
messagefield.appendText("Name field is empty. Please enter your name\n");
} else if (textfield.getText().trim().length() == 0) { //message field is empty
messagefield.appendText("Message field is empty. Please enter your message to send\n");
}
// Send the radius to the server
if (namefield.getText().trim().length() > 0 && textfield.getText().trim().length() > 0) {
toServer.writeUTF(namefield.getText().trim() + " : " + textfield.getText().trim());
toServer.flush();
}
} catch (IOException ex) {
messagefield.appendText(ex+" \n");
}
});
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8001); //socket with port number to connect server
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
new ReceiveMessage(socket); // send socket receieve class
// }
} catch (Exception ex) {
messagefield.setText(ex.toString() + '\n');
}
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { //scene close
#Override
public void handle(WindowEvent t) {
Platform.exit();
System.exit(0);
}
});
}
class ReceiveMessage implements Runnable { //class receive message
private final Socket socket;//socket
public ReceiveMessage(Socket socket) { // constructor
this.socket = socket; //socket intializes
Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start();
}
public void run() {
try {
fromServer = new DataInputStream(socket.getInputStream()); //to read from server
while (true) { // to continously receieve messages
// Get area from the server
String textmessage = fromServer.readUTF(); //read message from server
toServer.flush(); // flush
Platform.runLater(() -> {
messagefield.appendText(textmessage + " \n"); //append to textarea
});
}
} catch (IOException e) {
messagefield.appendText("Error " + e);
}
}
}
public static void main(String[] args) { //The keyword void simply tells the compiler that main( ) does not return a value.
launch(args);
}
}
Server class executed and taking clients
Client one connected
Client Two connected
Thank you.
The mistake I made in the code was after client sends message to server and sends message to all the clients connected to the server after that server connection is paused or halted I don't know why. I have used enumeration method to send messages to all the clients connected to the server. This is how I solved the issue. Hope my answer will help someone who is trying to implement client-server (multiple clients) chat application using thread.
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class Server extends Application {
static InetAddress inetAddress;
private final Hashtable<Object, Object> outputStreams = new Hashtable();
TextArea textarea = new TextArea();
static int clientNo = 0;
static ServerSocket serverSocket;
Hashtable<Object, Object> hmap = new Hashtable<>();
ArrayList<Object> clients = new ArrayList<Object>();
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.setPadding(new Insets(10, 10, 10, 10));
root.setAlignment(textarea, Pos.CENTER);
textarea.setMaxSize(400, 400);
textarea.setWrapText(true);
root.getChildren().addAll(textarea);
Scene scene = new Scene(root, 450, 400);
primaryStage.setTitle("Server");
primaryStage.setScene(scene);
primaryStage.show(); // Display the stage
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
primaryStage.close();
Platform.exit();
System.exit(0);
}
});
new Thread(() -> {
listen();
}).start();
}
private void listen() {
try {
// Create a server socket
serverSocket = new ServerSocket(8001);
textarea.appendText("MultiThreadServer started at " + new Date() + '\n');
while (true) {
Socket socket = serverSocket.accept();
inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
clientNo++;
Platform.runLater(() -> {
textarea.appendText("Starting thread for client " + clientNo + " at " + new Date() + '\n');
InetAddress inetAddress = socket.getInetAddress();
textarea.appendText("Client " + clientNo + "'s host name is " + inetAddress.getHostName() + "\n");
textarea.appendText("Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + "\n");
});
hmap.put(socket, outputToClient);
new HandleAClient(socket);
}
} catch (IOException ex) {
textarea.appendText(ex + " \n");
}
}
Enumeration getOutputStreams() {
return hmap.elements();
}
void sendToAll(String message) {
for (Enumeration e = getOutputStreams(); e.hasMoreElements();) {
DataOutputStream dout = (DataOutputStream) e.nextElement();
try {
dout.writeUTF(message);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
void All(String text) throws IOException {
Set set = hmap.entrySet();
Iterator it = set.iterator();
System.out.println("Text " + text);
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println("key " + entry.getKey() + " : " + entry.getValue());
DataOutputStream dout = (DataOutputStream) entry.getValue();
dout.writeUTF(text);
dout.flush();
}
}
class HandleAClient extends Thread {
private final Socket socket; // A connected socket
private String text = "";
/**
* Construct a thread
*/
public HandleAClient(Socket socket) throws IOException {
this.socket = socket;
start();
}
/**
* Run a thread
*/
public void run() {
try {
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream()); //receive input from client
while (true) {
textarea.appendText(new Date() + " Connection from " + socket + "\n");
text = inputFromClient.readUTF();
serversocket.sendToAll(text);
All(text);
Platform.runLater(() -> {
textarea.appendText(new Date() + " " + text + "\n");
});
}
} catch (IOException e) {
textarea.appendText("Error " + e + " \n");
try {
this.socket.close();
} catch (IOException ex) {
textarea.appendText("Error " + e + " \n");
}
e.printStackTrace();
}
}
}
public static void main(String[] args) { //The keyword void simply tells the compiler that main( ) does not return a value.
launch(args);
}
}

how to keep connect socket in java

i programmed multi connection ( client - server ) with socket
When connecting multiple servers,
The file is not transferred but an error message is displayed on the client side.
Should i use threads in your client?
client.java
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static void main(String[] args) {
try {
while (true) {
Socket sock = new Socket("192.168.0.77", 9999);
// Socket sock = new Socket("127.0.0.1", 9999);
// Socket sock = new Socket("127.0.0.1", 9999);
System.out.println("connection");
Scanner scan = new Scanner(System.in);
System.out.print("file name : ");
String fileName = scan.next();
File f = new File(fileName);
DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
dos.writeUTF(f.getName());
dos.flush();
byte b[] = new byte[1024];
int n = 0;
FileInputStream fis = new FileInputStream(fileName);
long fileSize = 0;
while ((n = fis.read(b)) != -1) {
dos.write(b, 0, n);
fileSize += n;
}
System.out.println("Transfer completed");
dos.close();
fis.close();
sock.close();
}
} catch (UnknownHostException ue) {
//System.out.println(ue.getMessage());
} catch (IOException ie) {
System.out.println(ie.getMessage());
}
}
}
server.java
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class server {
public static void main(String[] args) {
ServerSocket server = null;
// final int Server_port = 9999;
DataInputStream dis = null;
String fileName = null;
FileOutputStream fos = null;
try {
/*
* server = new ServerSocket(); String localHostAddress =
* InetAddress.getLocalHost().getHostAddress(); server.bind(new
* InetSocketAddress(localHostAddress, Server_port));
* System.out.println("[server] binding \naddress : " + localHostAddress +
* ", port : " + Server_port);
*/
/*
* InetSocketAddress remoteSocketAddress = (InetSocketAddress)
* socket.getRemoteSocketAddress(); String remoteHostName =
* remoteSocketAddress.getAddress().getHostAddress(); int remoteHostPort =
* remoteSocketAddress.getPort();
* System.out.println("[server] connected! \nconnected socket address:" +
* remoteHostName + ", port:" + remoteHostPort);
*/
while (true) {
server = new ServerSocket(9999);
AcceptThread acceptThread = new AcceptThread (server);
System.out.println("wait");
Socket sock = server.accept();
System.out.println("Client accept");
new Thread(acceptThread).start();
dis = new DataInputStream(sock.getInputStream());
// if (dis.available() > 0) {
fileName = dis.readUTF();
fos = new FileOutputStream(fileName);
byte[] b = new byte[1024];
int n = 0;
long fileSize = 0;
while ((n = dis.read(b)) != -1) {
fos.write(b, 0, n);
fileSize += n;
}
System.out.println("accepted");
fos.close();
dis.close();
sock.close();
server.close();
}
// }
} catch (IOException ie) {
System.out.println(ie.getMessage());
}
}
}
AcceptThread.class
import java.net.*;
public class AcceptThread extends Thread {
ServerSocket server;
Socket sock;
public AcceptThread(ServerSocket server) {
this.server = server;
}
#Override
public void run() {
while (true) {
try {
sock = server.accept();
System.out.println("connected client" + sock);
} catch (Exception e) {
}
}
}
}
and it gave me an error in client
Connection reset by peer: socket write error
i want to know how to connect multi client to server
can u provide a link or some tips / examples ?
You send name with DataOutputStream, but file.getName() is string! Convert to byte array like this

How to fetch unread email using javax.mail pop3 from outlook

I am trying to fetch unread email from Inbox(Outlook.office365.com) and also copy the read message to another folder. But I am getting some of the following issues.
Email is being re-read again, even if we mark the email as being
read programmatically.
Unable to copy an email to another folder even when we open the Inbox is RW(Read&Write) mode.
Attached my code as well.
package com.xyz.mail;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;
public class ReadEmail {
private static final String TRUE = "true";
private static final String MAIL_POP3_HOST = "mail.pop3.host";
private static final String MAIL_POP3_PORT = "mail.pop3.port";
private static final String MAIL_POP3_STARTTLS_ENABLE = "mail.pop3.starttls.enable";
private static final String MAIL_FOLDER_INBOX = "INBOX";
public static void check(String host, String storeType, String user, String password) throws Exception {
Store store = null;
Folder emailFolder = null;
try {
Properties properties = new Properties();
properties.put(MAIL_POP3_HOST, host);
properties.put(MAIL_POP3_PORT, "995");
properties.put(MAIL_POP3_STARTTLS_ENABLE, TRUE);
Session emailSession = Session.getDefaultInstance(properties);
// create the POP3 store object and connect with the pop server
store = emailSession.getStore(storeType);
store.connect(host, user, password);
emailFolder = store.getFolder(MAIL_FOLDER_INBOX);
emailFolder.open(Folder.READ_WRITE);
Message[] messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
System.out.println("messages.length---" + messages.length);
if (messages.length == 0) {
System.out.println("No new messages found.");
} else {
for (int i = 0, len = messages.length; i < len; i++) {
Message message = messages[i];
boolean hasAttachments = hasAttachments(message);
if (hasAttachments) {
System.out.println(
"Email #" + (i + 1) + " with subject " + message.getSubject() + " has attachments.");
readAttachment(message);
} else {
System.out.println("Email #" + (i + 1) + " with subject " + message.getSubject()
+ " does not have any attachments.");
continue;
}
Folder copyFolder = store.getFolder("copyData");
if (copyFolder.exists()) {
System.out.println("copy messages...");
copyFolder.copyMessages(messages, emailFolder);
message.setFlag(Flags.Flag.DELETED, true);
}
}
}
} catch (Exception e) {
throw new Exception(e);
} finally {
emailFolder.close(false);
store.close();
}
}
public static void main(String[] args) throws Exception {
String host = "outlook.office365.com";
String username = "emailtest#xyz.com";
String password = "passw0rd{}";
String mailStoreType = "pop3s";
check(host, mailStoreType, username, password);
}
private static boolean hasAttachments(Message msg) throws Exception {
if (msg.isMimeType("multipart/mixed")) {
Multipart mp = (Multipart) msg.getContent();
if (mp.getCount() > 1) {
return true;
}
}
return false;
}
public static void readAttachment(Message message) throws Exception {
Multipart multiPart = (Multipart) message.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String destFilePath = "/home/user/Documents/" + part.getFileName();
System.out.println("Email attachement ---- " + destFilePath);
FileOutputStream output = new FileOutputStream(destFilePath);
InputStream input = part.getInputStream();
byte[] buffer = new byte[4096];
int byteRead;
while ((byteRead = input.read(buffer)) != -1) {
output.write(buffer, 0, byteRead);
}
output.close();
}
}
}
}
How to I fetch only unread email and copy the email to another folder.
change the protocal to imap and change the prot respecitvely ..using pop3 we can access only inbox that is the reason why you are unable to copy the mail to another folder

Google maps API v2 Android, not drawing polygon when offline

I have a test application that I draw a Polygon using google maps API.
The problem is that, when I have no cache of any maps (new installed application) the Polygon does not draw.
Its not a problem not having the maps loaded, but I do need the Polygons drawn in my screen.
Is there a way I can do that?
Sry for my bad english
Heres the code I have:
package ngvl.testegmaps_v2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import ngvl.testegmaps_v2.VO.GeoPosicionamento;
import ngvl.testegmaps_v2.VO.Layer;
import ngvl.testegmaps_v2.VO.Secao;
import ngvl.testegmaps_v2.VO.Talhao;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MainActivity extends FragmentActivity {
private List<Secao> secoes;
private List<Polygon> poligonos = new ArrayList<Polygon>();
private HashMap<String,Object[]> informacoes = new HashMap<String,Object[]>();
private GoogleMap map;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = fragment.getMap();
map.getUiSettings().setRotateGesturesEnabled(false);
// Setting a click event handler for the map
LatLng latLng = new LatLng(-20.9957152, -47.3241304);
// map.addMarker(new
// MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)).title("Av. Paulista").snippet("São Paulo"));
configuraPosicao(map, latLng);
Button button = (Button)findViewById(R.id.button1);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
}
private void configuraPosicao(GoogleMap map, LatLng latLng) {
/*
* 3D map.moveCamera( CameraUpdateFactory.newLatLngZoom(latLng, 15));
* map.animateCamera( CameraUpdateFactory.zoomTo(10), 2000, null);
*
* CameraPosition cameraPosition = new CameraPosition.Builder()
* .target(latLng) .zoom(17) .bearing(90) .tilt(45) .build();
*
* map.animateCamera( CameraUpdateFactory.newCameraPosition(
* cameraPosition));
*/
map.setMapType(GoogleMap.MAP_TYPE_NONE);
// map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
try {
String json = readFileAsString("geo.json");
Gson gson = new Gson();
this.secoes = gson.fromJson(json, new TypeToken<List<Secao>>() {
}.getType());
json = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
escrevePoligons(map);
}
private String readFileAsString(String fileName) throws IOException {
InputStream is = getAssets().open(fileName);
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
private void escrevePoligons(GoogleMap map) {
float stroke = (float) 1.5;
for (Secao secao : secoes) {
for (Talhao talhao : secao.getTalhoes()) {
for (Layer layer : talhao.getLayers()) {
// PolygonOptions rectOptions = new PolygonOptions();
List<LatLng> latlngs = new ArrayList<LatLng>();
for (GeoPosicionamento geoPosicionamento : layer.getGeoPosicionamentos()) {
latlngs.add(new LatLng(geoPosicionamento.getLatitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue(), geoPosicionamento
.getLongitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue()));
}
int color = 0x1F00FF00;
int color2 = 0x5F000000;
PolygonOptions polygonOptions = new PolygonOptions()
.fillColor(color).addAll(latlngs)
.strokeColor(color2).strokeWidth(stroke);
Polygon p = map.addPolygon(polygonOptions);
poligonos.add(p);
informacoes.put( p.getId(), new Object[]{ secao, talhao , layer } );
//System.out.println(polygonOptions.getPoints());
polygonOptions = null;
latlngs = null;
}
}
}
this.secoes = null;
// String mUrl =
// "https://khms0.google.com.br/kh/v=124&src=app&z={z}&x={x}&y={y}";
// MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256,
// mUrl);
// mTileProvider.tilesRange();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
//String mUrl = "http://a.tile.openstreetmap.org/{z}/{x}/{y}.png";
//MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256, mUrl);
//map.addTileOverlay(new TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
// TileProvider tileProvider = TileProviderFactory.getTileProvider();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(tileProvider));
// map.moveCamera(CameraUpdateFactory.newLatLngZoom(new
// LatLng(-20.9957152, -47.3241304), 15));
map.setOnMapClickListener(new OnMapClickListener()
{
public void onMapClick(LatLng point)
{
Polygon p = isPointInPolygon(point);
if( p != null){
p.setFillColor(getRandomColor());
Object[] clicado = informacoes.get( p.getId() );
Secao secao_clicada = (Secao) clicado[0];
Talhao talhao_clicada = (Talhao) clicado[1];
Layer layer_clicada = (Layer) clicado[2];
//System.out.println(secao_clicada);
//System.out.println(talhao_clicada);
//System.out.println(layer_clicada);
//System.out.println("=======================");
StringBuilder texto = new StringBuilder();
texto.append("Seção: " + secao_clicada.getDesc() + "\n");
texto.append("Talhão: " + talhao_clicada.getTalhao() + "\n");
texto.append("Variedade: " + talhao_clicada.getVariedade() + " - " + talhao_clicada.getDescVariedade() + "\n");
texto.append("Layer: " + layer_clicada.getSequencia() + "\n");
//Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
addMarker(point,texto);
}//else
//Toast.makeText(MainActivity.this,"Clicou fora da Área de um Poligono", Toast.LENGTH_LONG).show();
}
});
}
public void addMarker(LatLng point, StringBuilder texto) {
/*map.addMarker(new MarkerOptions().position(point).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.title("Caracteristicas: ")
.snippet( texto );
*/
Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
}
private Polygon isPointInPolygon(LatLng tap) {
for( Polygon p : poligonos){
int intersectCount = 0;
List<LatLng> vertices = p.getPoints();
for(int j=0; j<vertices.size()-1; j++) {
if( rayCastIntersect(tap, vertices.get(j), vertices.get(j+1)) ) {
intersectCount++;
}
}
if(((intersectCount % 2) == 1)){
return p;
}
}
return null;// odd = inside, even = outside;
}
private boolean rayCastIntersect(LatLng tap, LatLng vertA, LatLng vertB) {
double aY = vertA.latitude;
double bY = vertB.latitude;
double aX = vertA.longitude;
double bX = vertB.longitude;
double pY = tap.latitude;
double pX = tap.longitude;
if ( (aY>pY && bY>pY) || (aY<pY && bY<pY) || (aX<pX && bX<pX) ) {
return false; // a and b can't both be above or below pt.y, and a or b must be east of pt.x
}
double m = (aY-bY) / (aX-bX); // Rise over run
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m; // algebra is neat!
return x > pX;
}
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
}
};
public int getRandomColor() {
int color;
Random rnd = new Random();
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
return color;
}
}
Setting map type to MAP_TYPE_NONE like example above does not solve the problem
I will this as marked solved by using Maps Forge Open Source API
If someone did with Google Maps Api please share and I would change the answer.
The answer I found is that its impossible to render or access anything without rendering the map first (online or via cache)
This is actually a bug of GoogleMaps Api v2 for Android.
It is referenced here:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=5017
Star it if you want to accelerate the bug fix!