How to make multithreads code with 2 loops - java

I trying to make my code faster with multi-threads.
I have 2 bigs arrays (in my code above I put small arrays for the example).
This is my code that I tryied, but its stuck and not make anything:
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
private ArrayList<String> blackList = new ArrayList<String>();
String[] cities = {
"London",
"Paris",
"Barcelona"
};
String[] cats = {
"Animals",
"Jobs",
"Env",
"B"
};
public static void main(String[] args) {
Main m = new Main();
m.run();
}
public void run() {
ExecutorService svc = Executors.newCachedThreadPool();
int chunks = Runtime.getRuntime().availableProcessors();
long iterationsCities = cities.length;
long iterationsCats = cats.length;
for (int i = 0; i < chunks; ++i) {
int startCities = (int) (iterationsCities / chunks * i);
int endCities = (int) (iterationsCities / chunks * (i + 1));
int startCats = (int) (iterationsCats / chunks * i);
int endCats = (int) (iterationsCats / chunks * (i + 1));
svc.execute(new Task(startCities, endCities, startCats, endCats));
}
}
public class Task implements Runnable {
int startCities;
int endCities;
int startCats;
int endCats;
public Task(int startCities, int endCities, int startCats, int endCats) {
this.startCities = startCities;
this.endCities = endCities;
this.startCats = startCats;
this.endCats = endCats;
}
public void launch() throws IOException, InterruptedException {
for(int i=startCities; i<endCities; i++)
{
for(int j=startCats; j<endCats; j++)
{
String link = "https://.../pro/search/" + cats[j] + "/" + cities[i];
//System.out.println(link);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(link))
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
//System.out.println(link);
String html = response.body();
Pattern pattern = Pattern.compile("data-count=\"([A-Za-z0-9_]*)\"");
Matcher matcher = pattern.matcher(html);
boolean matchFound = matcher.find();
if(matchFound)
{
int dataCount = Integer.parseInt(matcher.group(1));
if(dataCount == 0)
{
String l = cats[j] + "/" + cities[i];
if(!blackList.contains(l)) {
blackList.add(l);
}
}
}
}
}
}
#Override
public void run() {
try {
launch();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
My code makes http request, gets value in the meta tag of the HTML and asks if the value equal to 0, if yes it saves the URL in the blacklist.

Related

I am trying to write a method that will DETECT recursion in a file but am having trouble iterating through the methods of that file

This is what my recursion detector looks like (with an error of "The method contains(String) is undefined for Method Declaration" in if (md.contains(methodName))). I am not sure how I should change this to make it work. I hope to have some advice on what I could do to iterate through each individual method and check for its methodName in it. Thank you!
RecursionDetector.java
package detectors;
import java.awt.*;
import java.util.*;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
public class RecursionDetector extends VoidVisitorAdapter <Breakpoints> {
#Override
public void visit(MethodDeclaration md, Breakpoints collector) {
String className = getClass().getName();
String methodName = md.getName().asString();
int startline = md.getRange().get().begin.line;
int endline = md.getRange().get().end.line;
final StackTraceElement[] trace = Thread.currentThread().getStackTrace();
if (md.contains(methodName)) {
}
for (int i=0; i < trace.length-1; i++) {
if( trace[i].equals(trace[trace.length-1]) ) {
super.visit(md, collector);
collector.addEmpty(className, methodName, startline, endline);
}
}
}
}
I also have a Breakpoints.java that looks like this:
package detectors;
import java.util.ArrayList;
public class Breakpoints {
private ArrayList<String> collector = new ArrayList<String>();
public Breakpoints() { }
public void addClass(String currentClass) { }
public void addMethod(String currentMethod) { }
public ArrayList<String> returnCollector() {
return new ArrayList<String>(this.collector);
}
public void addEmpty(String currentClass, String currentMethod, int startLine, int endLine) {
String n = ("className: " + currentClass + ", methodName: " + currentMethod + ", startline : " + startLine
+ ", endline : " + endLine + "\n");
if (collector.contains(n)) {
return;
}
collector.add(n);
}
}
And a Driver.java that looks like this:
package detectors;
import java.io.*;
import java.util.Scanner;
import com.github.javaparser.*;
import com.github.javaparser.ast.CompilationUnit;
public class Driver {
public static String data;
public static String data2 = "";
public static void main(String[] args) {
try {
File myFile = new File("/Users/weihanng/Desktop/Calculator.java");
Scanner myReader = new Scanner(myFile);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
data2 = data2.concat(data);
}
myReader.close();
CompilationUnit cu = JavaParser.parse(myFile);
Breakpoints collector = new Breakpoints();
cu.accept(new RecursionDetector(), collector);
System.out.println("Recursions: ");
System.out.println(collector.returnCollector());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Is there a way to get values of stocks to Java faster?

I made a simple java program that lets you create a stocks scanner/screener. There aren't many features yet, but there is a problem with existing features. I have a class that has a method that creates an array of all stock tickers and returns it. Here it is:
package classes;
import Utility.ArrayModification;
import variables.Ticker;
import java.io.*;
import java.util.Scanner;
public class Market {
public static Ticker[] getAllTickers() throws FileNotFoundException {
Ticker[] allTickers = {};
File currentDirectory = new File(new File("").getAbsolutePath());
String allTickersDirectory = currentDirectory + "\\src\\AllTickers.txt";
Scanner scanner = new Scanner(new File(allTickersDirectory));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!(line.contains("^"))) {
allTickers = ArrayModification.appendTicker(allTickers, new Ticker(line));
}
}
return allTickers;
}
}
AllTickers.txt is a text file with the names of all tickers in it. I also have another class that stores a datatype, Ticker. Here it is:
package variables;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Ticker {
private String savedSymbol;
public Ticker(String symbol) {
savedSymbol = symbol;
}
public String getTicker() {
return savedSymbol;
}
public Ticker setTicker(String symbol) {
savedSymbol = symbol;
return this;
}
public double getPrice() throws IOException {
try {
String stringURL = "https://markets.businessinsider.com/stocks/" + savedSymbol + "-stock";
URL url = new URL(stringURL);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
String stringPrice = "-1";
String line = buff.readLine();
while (line != null) {
if (line.contains("price: ")) {
int target = line.indexOf("price: ");
int deci = line.indexOf(".", target);
int start = deci;
int stop = deci;
while (line.charAt(start) != ' ') {
start--;
}
while (line.charAt(stop) != ',') {
stop++;
}
stringPrice = line.substring(start + 1, stop);
break;
}
line = buff.readLine();
}
double price = Double.parseDouble(stringPrice);
return price;
}
catch(Exception e) {
return -1;
}
}
public double getMarketCap() throws IOException {
try {
String stringURL = "https://finviz.com/quote.ashx?t=" + savedSymbol;
URL url = new URL(stringURL);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
String stringMarketCap = "-1";
double finalMarketCap = -1;
String line = buff.readLine();
while (line != null) {
if (line.contains(">Market Cap<")) {
int deci = line.indexOf(".");
int start = deci;
int stop = deci;
while (line.charAt(start) != '>') {
start--;
}
while (line.charAt(stop) != '<') {
stop++;
}
stringMarketCap = line.substring(start + 1, stop - 1);
double marketCap = Double.parseDouble(stringMarketCap);
if (line.charAt(stop - 1) == 'B') {
finalMarketCap = marketCap * 1000000000;
} else if (line.charAt(stop - 1) == 'M') {
finalMarketCap = marketCap * 1000000;
}
break;
}
line = buff.readLine();
}
return finalMarketCap;
}
catch(Exception e) {
return -1;
}
}
}
Using all of these, you can create a simple scanner that scans for stocks with a price of, for example, 0 - 15. You can do this by doing this:
import classes.Market;
import variables.Ticker;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Ticker[] allTickers = Market.getAllTickers();
for(int i = 0; i< allTickers.length; i++){
Ticker ticker = allTickers[i];
if(ticker.getPrice() > 0 && ticker.getPrice() < 15) {
System.out.println(ticker.getTicker());
}
}
}
}
It prints out all of the qualifying stocks. However, it is EXTREMELY slow. So slow that it's basically unusable. It is this way because the ticker.getPrice() method has to connect to markets.businessinsider.com, extract the HTML code, find the correct index, and get the price for every single stock out of the 6000 in AllTIckers.txt. Would there be a way to do this faster?

Simple HTTP server keeps CPU at full load despite TaskManager and Netbeans telling otherwise

I made a HTTP server out of boredom and made it single file program.
The problem is, when serving a large file, for example 1.2GB, the CPU ramps up all the way up to 100% and my Lenovo X220 jumps immediately to 80C.
The catch is that the Netbeans profile nor Task Manager report it using that much CPU. Let's take a look:
Here it is serving the large file, this is task manager sorted by CPU and showing all processes:
Nothing suspicious, but in the Performance tab all hell is breaking loose:
All four cores locked to almost 99% with my i5 2520m at full turbo (3.2GHz)
Here is the server itself, just copy it into a file named JavaApplication1.java
What is going on here?
package javaapplication1;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class JavaApplication1 {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(80);
ServiceManager manager = ServiceManager.getManager();
while (true) {
Socket sock = server.accept();
HttpResponse response = new HttpResponse(sock);
manager.submit(response);
}
}
}
class ServiceManager {
private static ServiceManager instance;
private static ExecutorService executor;
private static ArrayList<Future<?>> taskPool;
private static final int MAX_WORKERS = 150;
private ServiceManager() {
executor = Executors.newFixedThreadPool(MAX_WORKERS);
taskPool = new ArrayList<>();
}
public static ServiceManager getManager() {
if (instance == null) {
instance = new ServiceManager();
}
return instance;
}
public void registerService(Runnable runnable) {
taskPool.add(executor.submit(runnable));
}
void submit(HttpResponse response) {
executor.submit(response);
}
}
class HttpAccept {
private final ByteArrayOutputStream baos;
private final InputStream in;
private final Callback<HttpAccept> back;
public HttpAccept(InputStream in, Callback<HttpAccept> back) {
baos = new ByteArrayOutputStream(512);
this.in = in;
this.back = back;
}
public void readAndRespond() {
byte[] buf = new byte[512];
int b;
try {
while ((b = in.read(buf)) > 0) {
baos.write(buf, 0, b);
if (HttpTools.endsWithCrlfCrlf(baos.toByteArray())) {
back.callback(this);
return;
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
public void call(Callback<HttpAccept> back) {
back.callback(this);
}
public String getHttpHeader() {
return new String(baos.toByteArray(), StandardCharsets.UTF_8);
}
}
interface Callback<E> {
void callback(E a);
}
class HttpHeader {
private final ByteArrayOutputStream baos;
private final String raw;
public HttpHeader(String raw) {
baos = new ByteArrayOutputStream(512);
this.raw = raw;
}
public String getRequestPath() {
char[] workset = raw.toCharArray();
for (char c : workset) {
baos.write((byte) c);
if (HttpTools.endsWithCrlf(baos.toByteArray())) {
String response[] = baos.toString().split(" ");
if (response.length == 0) return "./error.html";
if (response[1].equals("/")) return "./index.html";
return ".".concat(response[1]);
}
}
return "./";
}
}
abstract class HttpTools {
private static final byte[] CRLFCRLF = {13, 10, 13, 10};
private static final byte[] CRLF = {13, 10};
public static boolean endsWithCrlfCrlf(byte[] arr) {
if (arr.length < 4) {
return false;
}
int len = arr.length - 1;
return (arr[len] == CRLFCRLF[3]
&& arr[len - 1] == CRLFCRLF[2]
&& arr[len - 2] == CRLFCRLF[1]
&& arr[len - 3] == CRLFCRLF[0]);
}
public static boolean endsWithCrlf(byte[] arr) {
if (arr.length < 2) {
return false;
}
int len = arr.length - 1;
return (arr[len] == CRLF[1]
&& arr[len - 1] == CRLF[0]);
}
}
class HttpResponse implements Runnable {
private final Socket conn;
public HttpResponse(Socket conn) {
this.conn = conn;
}
public void respond() throws IOException {
HttpAccept accept = new HttpAccept(conn.getInputStream(), (httpAcc) -> {
try (OutputStream out = conn.getOutputStream()) {
HttpHeader header = new HttpHeader(httpAcc.getHttpHeader());
String path = header.getRequestPath();
File file = new File(path);
if (file.exists()) {
writeResponse(out, 200);
FileInputStream in = new FileInputStream(file);
byte[] buf = new byte[4096];
int b;
while ((b = in.read(buf)) > 0) {
out.write(buf, 0, b);
}
} else {
writeResponse(out, 404);
}
writeEnd(out);
} catch (IOException e) {
System.err.println(e);
}
});
accept.readAndRespond();
}
#Override
public void run() {
try {
respond();
} catch (IOException ex) {
System.err.println(ex);
}
}
private void writeResponse(OutputStream out, int i) throws IOException {
char[] resp = String.format("HTTP/1.1 %s OK\r\n\r\n", i).toCharArray();
for (char c : resp) {
out.write((int) c);
}
if (i == 404) {
char[] four0four = "<b>404 - Not found</b>".toCharArray();
for (char c : four0four) {
out.write((int) c);
}
}
}
private void writeEnd(OutputStream out) throws IOException {
char[] resp = "\r\n\r\n".toCharArray();
for (char c : resp) {
out.write((int) c);
}
}
}

How to convert dicom file to jpg conversion

How we can convert a dicom file(.dcm) to a jpeg image using java?
Here is my code:
import java.io.File;
import java.io.IOException;
import org.dcm4che2.tool.dcm2jpg.Dcm2Jpg;
public class MainClass {
public static void main(String[] args) throws IOException{
Dcm2Jpg conv = new Dcm2Jpg();
conv.convert(new File("C:\\Users\\lijo.joseph\\Desktop\\Dicom\\IM-0001-0001.dcm"), new File("C:\\Users\\lijo.joseph\\Desktop\\Dicom\\IM-0001-0001.jpg"));
}
}
and i am getting the following error while running the project
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/cli/ParseException
at MainClass.main(MainClass.java:7)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.cli.ParseException
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
please help and thanks in advance
Here is the link Converting DICOM to JPEG using dcm4che 2
Following is my code which works perfectly.I have placed it with imports so it might be use-full.
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Examplke1 {
static BufferedImage myJpegImage=null;
public static void main(String[] args) {
File file = new File("test5/12840.dcm");
Iterator<ImageReader> iterator =ImageIO.getImageReadersByFormatName("DICOM");
while (iterator.hasNext()) {
ImageReader imageReader = (ImageReader) iterator.next();
DicomImageReadParam dicomImageReadParam = (DicomImageReadParam) imageReader.getDefaultReadParam();
try {
ImageInputStream iis = ImageIO.createImageInputStream(file);
imageReader.setInput(iis,false);
myJpegImage = imageReader.read(0, dicomImageReadParam);
iis.close();
if(myJpegImage == null){
System.out.println("Could not read image!!");
}
} catch (IOException e) {
e.printStackTrace();
}
File file2 = new File("/test.jpg");
try {
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file2));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
encoder.encode(myJpegImage);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Completed");
}
}
}
Jars Used to Run it
dcm4che-imageio-2.0.28.jar
dcm4che-image-2.0.28.jar
jai_imageio-1.1.jar
dcm4che-core-2.0.28.jar
slf4j-api-1.7.7.jar
slf4j-log4j12-1.7.7.jar
apache-logging-log4j.jar
Hope it helps.
This Code is used for Converting Dicom Image to JPG Image
import java.io.File;
import java.io.IOException;
public class Dcm2JpgTest {
public static void main(String[] args) throws IOException {
try{
File src = new File("d:\\Test.dcm");
File dest = new File("d:\\Test.jpg");
Dcm2Jpeg dcm2jpg= new Dcm2Jpeg();
dcm2jpg.convert(src, dest);
System.out.println("Completed");
} catch(IOException e){
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
}
Dcm2Jpeg.java File
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import org.dcm4che2.io.DicomInputStream;
import org.dcm4che2.util.CloseUtils;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Dcm2Jpeg {
private static final String USAGE =
"dcm2jpg [Options] <dcmfile> <jpegfile>\n" +
"or dcm2jpg [Options] <dcmfile>... <outdir>\n" +
"or dcm2jpg [Options] <indir>... <outdir>";
private static final String DESCRIPTION =
"Convert DICOM image(s) to JPEG(s)\nOptions:";
private static final String EXAMPLE = null;
private int frame = 1;
private float center;
private float width;
private String vlutFct;
private boolean autoWindowing;
private DicomObject prState;
private short[] pval2gray;
private String fileExt = ".jpg";
private void setFrameNumber(int frame) {
this.frame = frame;
}
private void setWindowCenter(float center) {
this.center = center;
}
private void setWindowWidth(float width) {
this.width = width;
}
public final void setVoiLutFunction(String vlutFct) {
this.vlutFct = vlutFct;
}
private final void setAutoWindowing(boolean autoWindowing) {
this.autoWindowing = autoWindowing;
}
private final void setPresentationState(DicomObject prState) {
this.prState = prState;
}
private final void setPValue2Gray(short[] pval2gray) {
this.pval2gray = pval2gray;
}
public final void setFileExt(String fileExt) {
this.fileExt = fileExt;
}
public void convert(File src, File dest) throws IOException {
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = iter.next();
DicomImageReadParam param =
(DicomImageReadParam) reader.getDefaultReadParam();
param.setWindowCenter(center);
param.setWindowWidth(width);
param.setVoiLutFunction(vlutFct);
param.setPresentationState(prState);
param.setPValue2Gray(pval2gray);
param.setAutoWindowing(autoWindowing);
ImageInputStream iis = ImageIO.createImageInputStream(src);
BufferedImage bi;
OutputStream out = null;
try {
reader.setInput(iis, false);
bi = reader.read(frame - 1, param);
if (bi == null) {
System.out.println("\nError: " + src + " - couldn't read!");
return;
}
out = new BufferedOutputStream(new FileOutputStream(dest));
JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
enc.encode(bi);
} finally {
CloseUtils.safeClose(iis);
CloseUtils.safeClose(out);
}
//System.out.print('.');
}
public int mconvert(List<String> args, int optind, File destDir)
throws IOException {
int count = 0;
for (int i = optind, n = args.size() - 1; i < n; ++i) {
File src = new File(args.get(i));
count += mconvert(src, new File(destDir, src2dest(src)));
}
return count;
}
private String src2dest(File src) {
String srcname = src.getName();
return src.isFile() ? srcname + this.fileExt : srcname;
}
public int mconvert(File src, File dest) throws IOException {
if (!src.exists()) {
System.err.println("WARNING: No such file or directory: " + src
+ " - skipped.");
return 0;
}
if (src.isFile()) {
try {
convert(src, dest);
} catch (Exception e) {
System.err.println("WARNING: Failed to convert " + src + ":");
e.printStackTrace(System.err);
System.out.print('F');
return 0;
}
System.out.print('.');
return 1;
}
File[] files = src.listFiles();
if (files.length > 0 && !dest.exists()) {
dest.mkdirs();
}
int count = 0;
for (int i = 0; i < files.length; ++i) {
count += mconvert(files[i], new File(dest, src2dest(files[i])));
}
return count;
}
#SuppressWarnings("unchecked")
public static void main(String args[]) throws Exception {
CommandLine cl = parse(args);
Dcm2Jpeg dcm2jpg = new Dcm2Jpeg();
if (cl.hasOption("f")) {
dcm2jpg.setFrameNumber(
parseInt(cl.getOptionValue("f"),
"illegal argument of option -f",
1, Integer.MAX_VALUE));
}
if (cl.hasOption("p")) {
dcm2jpg.setPresentationState(loadDicomObject(
new File(cl.getOptionValue("p"))));
}
if (cl.hasOption("pv2gray")) {
dcm2jpg.setPValue2Gray(loadPVal2Gray(
new File(cl.getOptionValue("pv2gray"))));
}
if (cl.hasOption("c")) {
dcm2jpg.setWindowCenter(
parseFloat(cl.getOptionValue("c"),
"illegal argument of option -c"));
}
if (cl.hasOption("w")) {
dcm2jpg.setWindowWidth(
parseFloat(cl.getOptionValue("w"),
"illegal argument of option -w"));
}
if (cl.hasOption("sigmoid")) {
dcm2jpg.setVoiLutFunction(DicomImageReadParam.SIGMOID);
}
dcm2jpg.setAutoWindowing(!cl.hasOption("noauto"));
if (cl.hasOption("jpgext")) {
dcm2jpg.setFileExt(cl.getOptionValue("jpgext"));
}
final List<String> argList = cl.getArgList();
int argc = argList.size();
File dest = new File(argList.get(argc-1));
long t1 = System.currentTimeMillis();
int count = 1;
if (dest.isDirectory()) {
count = dcm2jpg.mconvert(argList, 0, dest);
} else {
File src = new File(argList.get(0));
if (argc > 2 || src.isDirectory()) {
exit("dcm2jpg: when converting several files, "
+ "last argument must be a directory\n");
}
dcm2jpg.convert(src, dest);
}
long t2 = System.currentTimeMillis();
System.out.println("\nconverted " + count + " files in " + (t2 - t1)
/ 1000f + " s.");
}
private static DicomObject loadDicomObject(File file) {
DicomInputStream in = null;
try {
in = new DicomInputStream(file);
return in.readDicomObject();
} catch (IOException e) {
exit(e.getMessage());
throw new RuntimeException();
} finally {
CloseUtils.safeClose(in);
}
}
private static short[] loadPVal2Gray(File file) {
BufferedReader r = null;
try {
r = new BufferedReader(new InputStreamReader(new FileInputStream(
file)));
short[] pval2gray = new short[256];
int n = 0;
String line;
while ((line = r.readLine()) != null) {
try {
int val = Integer.parseInt(line.trim());
if (n == pval2gray.length) {
if (n == 0x10000) {
exit("Number of entries in " + file + " > 2^16");
}
short[] tmp = pval2gray;
pval2gray = new short[n << 1];
System.arraycopy(tmp, 0, pval2gray, 0, n);
}
pval2gray[n++] = (short) val;
} catch (NumberFormatException nfe) {
// ignore lines where Integer.parseInt fails
}
}
if (n != pval2gray.length) {
exit("Number of entries in " + file + ": " + n
+ " != 2^[8..16]");
}
return pval2gray;
} catch (IOException e) {
exit(e.getMessage());
throw new RuntimeException();
} finally {
CloseUtils.safeClose(r);
}
}
private static CommandLine parse(String[] args) {
Options opts = new Options();
OptionBuilder.withArgName("frame");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"frame to convert, 1 (= first frame) by default");
opts.addOption(OptionBuilder.create("f"));
OptionBuilder.withArgName("prfile");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"file path of presentation state to apply");
opts.addOption(OptionBuilder.create("p"));
OptionBuilder.withArgName("center");
OptionBuilder.hasArg();
OptionBuilder.withDescription("Window Center");
opts.addOption(OptionBuilder.create("c"));
OptionBuilder.withArgName("width");
OptionBuilder.hasArg();
OptionBuilder.withDescription("Window Width");
opts.addOption(OptionBuilder.create("w"));
opts.addOption("sigmoid", false,
"apply sigmoid VOI LUT function with given Window Center/Width");
opts.addOption("noauto", false,
"disable auto-windowing for images w/o VOI attributes");
OptionBuilder.withArgName("file");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"file path of P-Value to gray value map");
opts.addOption(OptionBuilder.create("pv2gray"));
OptionBuilder.withArgName(".xxx");
OptionBuilder.hasArg();
OptionBuilder.withDescription(
"jpeg file extension used with destination directory argument,"
+ " default: '.jpg'.");
opts.addOption(OptionBuilder.create("jpgext"));
opts.addOption("h", "help", false, "print this message");
opts.addOption("V", "version", false,
"print the version information and exit");
CommandLine cl = null;
try {
cl = new GnuParser().parse(opts, args);
} catch (ParseException e) {
exit("dcm2jpg: " + e.getMessage());
throw new RuntimeException("unreachable");
}
if (cl.hasOption('V')) {
Package p = Dcm2Jpeg.class.getPackage();
System.out.println("dcm2jpg v" + p.getImplementationVersion());
System.exit(0);
}
if (cl.hasOption('h') || cl.getArgList().size() < 2) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE);
System.exit(0);
}
return cl;
}
private static int parseInt(String s, String errPrompt, int min, int max) {
try {
int i = Integer.parseInt(s);
if (i >= min && i <= max)
return i;
} catch (NumberFormatException e) {
// parameter is not a valid integer; fall through to exit
}
exit(errPrompt);
throw new RuntimeException();
}
private static float parseFloat(String s, String errPrompt) {
try {
return Float.parseFloat(s);
} catch (NumberFormatException e) {
exit(errPrompt);
throw new RuntimeException();
}
}
private static void exit(String msg) {
System.err.println(msg);
System.err.println("Try 'dcm2jpg -h' for more information.");
System.exit(1);
}
}
Jars Files Used to Run this code
dcm4che-core-2.0.23.jar
dcm4che-image-2.0.23.jar
dcm4che-imageio-2.0.23.jar
dcm4che-imageio-rle-2.0.23.jar
slf4j-log4j12-1.5.0.jar
slf4j-api-1.5.0.jar
log4j-1.2.13.jar
commons-cli-1.2.jar
If you don't want to use direct Dcm2Jpg.java file then you can include below jar file.
dcm4che-tool-dcm2jpg-2.0.23.jar
In this jar you can import org.dcm4che2.tool.dcm2jpg.Dcm2Jpg this java file

JFOREX SDK - How to send HTTPS GET request to www server ssl connection

how to add this
public class JavaHttpsExample
{
public static void main(String[] args)
throws Exception
{
String httpsURL = "https://localhost/send.php&json=somevalue";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}
in.close();
}
}
to
Jforex maven sdk for eclipse:
http://www.dukascopy.com/client/jforexlib/JForex-SDK.zip
and
http://www.dukascopy.com/wiki/#IClient_functionality
package singlejartest_old;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.*;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* This small program demonstrates how to initialize Dukascopy client and start a strategy
*/
public class MainStopFromConsole {
private static final Logger LOGGER = LoggerFactory.getLogger(MainStopFromConsole.class);
private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
private static String userName = "";
private static String password = "";
public static void main(String[] args) throws Exception {
//get the instance of the IClient interface
final IClient client = ClientFactory.getDefaultInstance();
//set the listener that will receive system events
client.setSystemListener(new ISystemListener() {
private int lightReconnects = 3;
#Override
public void onStart(long processId) {
LOGGER.info("Strategy started: " + processId);
}
#Override
public void onStop(long processId) {
LOGGER.info("Strategy stopped: " + processId);
if (client.getStartedStrategies().size() == 0) {
System.exit(0);
}
}
#Override
public void onConnect() {
LOGGER.info("Connected");
lightReconnects = 3;
}
#Override
public void onDisconnect() {
LOGGER.warn("Disconnected");
if (lightReconnects > 0) {
LOGGER.error("TRY TO RECONNECT, reconnects left: " + lightReconnects);
client.reconnect();
--lightReconnects;
} else {
try {
//sleep for 10 seconds before attempting to reconnect
Thread.sleep(10000);
} catch (InterruptedException e) {
//ignore
}
try {
client.connect(jnlpUrl, userName, password);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
});
LOGGER.info("Connecting...");
//connect to the server using jnlp, user name and password
client.connect(jnlpUrl, userName, password);
//wait for it to connect
int i = 10; //wait max ten seconds
while (i > 0 && !client.isConnected()) {
Thread.sleep(1000);
i--;
}
if (!client.isConnected()) {
LOGGER.error("Failed to connect Dukascopy servers");
System.exit(1);
}
//subscribe to the instruments
Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(Instrument.EURUSD);
LOGGER.info("Subscribing instruments...");
client.setSubscribedInstruments(instruments);
//start the strategy
LOGGER.info("Starting strategy");
final long strategyId = client.startStrategy(new IStrategy(){
public Instrument instrument = Instrument.EURUSD;
private IConsole console;
public void onStart(IContext context) throws JFException {
console = context.getConsole();
}
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if ( instrument == this.instrument){
console.getOut().println(" bar: " + period + " " + askBar);
}
}
public void onTick(Instrument instrument, ITick tick) throws JFException { }
public void onMessage(IMessage message) throws JFException { }
public void onAccount(IAccount account) throws JFException { }
public void onStop() throws JFException { }
});
//now it's running
//every second check if "stop" had been typed in the console - if so - then stop the strategy
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Scanner s = new Scanner(System.in);
while(true){
while(s.hasNext()){
String str = s.next();
if(str.equalsIgnoreCase("stop")){
System.out.println("Strategy stop by console command.");
client.stopStrategy(strategyId);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
i need send some values(account balance or open positions) to WWW serwer from strategy
Thanks
zix
package master;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.*;
import java.awt.Color;
import java.awt.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Array;
import java.net.URL;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.JFrame;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import singlejartest.JavaHttpsExample;
public class MainStopFromConsole {
private static final Logger LOGGER = LoggerFactory.getLogger(MainStopFromConsole.class);
private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
private static String userName = "DEMO2PRFwj";
private static String password = "PRFwj";
//static String[] columns = {"Open Time", "Id", "Label", "Comment", "Instrument", "Side", "Amount", "Original Amount", "Open Price", "Stop Loss", "Take Profit", "Profit (Pips)", "Profit Currency", "Profit in USD", "Commission", "Commission USD"};
static String[] columns = {"Id", "Instrument", "Side", "Amount", "Open Price", "Stop Loss", "Take Profit"};
//static String[][] data = {{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"},
static String[][] data = new String[50][11];
//static String[][] data = null;
//static JFrame jf = new JFrame();
public static void main(String[] args) throws Exception {
//get the instance of the IClient interface
final IClient client = ClientFactory.getDefaultInstance();
//set the listener that will receive system events
client.setSystemListener(new ISystemListener() {
private int lightReconnects = 3;
public void onStart(long procid) {
//IConsole console = context.getConsole();
LOGGER.info("Strategy started: ");
}
public void onStop(long processId) {
LOGGER.info("Strategy stopped: " + processId);
if (client.getStartedStrategies().size() == 0) {
System.exit(0);
}
}
#Override
public void onConnect() {
LOGGER.info("Connected");
lightReconnects = 3;
}
#Override
public void onDisconnect() {
LOGGER.warn("Disconnected");
if (lightReconnects > 0) {
LOGGER.error("TRY TO RECONNECT, reconnects left: " + lightReconnects);
client.reconnect();
--lightReconnects;
} else {
try {
//sleep for 10 seconds before attempting to reconnect
Thread.sleep(10000);
} catch (InterruptedException e) {
//ignore
}
try {
client.connect(jnlpUrl, userName, password);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
});
LOGGER.info("Connecting...");
//connect to the server using jnlp, user name and password
client.connect(jnlpUrl, userName, password);
//wait for it to connect
int i = 10; //wait max ten seconds
while (i > 0 && !client.isConnected()) {
Thread.sleep(1000);
i--;
}
if (!client.isConnected()) {
LOGGER.error("Failed to connect Dukascopy servers");
System.exit(1);
}
//subscribe to the instruments
Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(Instrument.EURUSD);
LOGGER.info("Subscribing instruments...");
client.setSubscribedInstruments(instruments);
//start the strategy
LOGGER.info("Starting strategy");
final long strategyId = client.startStrategy(new IStrategy(){
public Instrument instrument = Instrument.EURUSD;
private IConsole console;
private IEngine engine;
public void onStart(IContext context) throws JFException {
console = context.getConsole();
engine = context.getEngine();
}
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if ( instrument == this.instrument){
//console.getOut().println(" bar: " + period + " " + askBar);
}
}
public void onTick(Instrument instrument, ITick tick) throws JFException {
try {
int xx = 0;
//data[0][1] = "1";
for(IOrder o : engine.getOrders()){
if(o.getProfitLossInUSD() != 987654231){
console.getOut().println("Order: " + o.getInstrument() + " " + o.getProfitLossInPips() + " " + o.getOrderCommand());
// Copy orders to array
String userHash = "1";
String positionOpenTime = "" + o.getFillTime();
String positionId = "" + o.getId();
String positionInstrument = "" + o.getInstrument();
String positionIsbuy = "" + o.getOrderCommand().isLong();
String positionVolume = "" + o.getAmount();
String positionOpen = "" + o.getOpenPrice();
String positionSl = "" + o.getStopLossPrice();
String positionTp = "" + o.getTakeProfitPrice();
String positionComment = "" + o.getComment();
data[xx][0] = userHash;
data[xx][1] = positionOpenTime;
data[xx][2] = positionId;
data[xx][3] = positionInstrument;
data[xx][4] = positionIsbuy;
data[xx][5] = positionVolume;
data[xx][6] = positionOpen;
data[xx][7] = positionSl;
data[xx][8] = positionTp;
data[xx][9] = positionComment;
xx++;
}
}
xx=0;
/*
int i = 0;
int j = 0;
String string = "";
for(j = 0; j<10; j++){
for(i = 0; i<10; i++){
string += data[j][i] + "#";
}
string += "$$";
}
}
console.getOut().println("=====================================================================================" );
console.getOut().println(string);
*/
console.getOut().println("=====================================================================================" );
String txt ="";
txt = Arrays.deepToString(data);
txt = txt.replaceAll(",", "aa");
txt = txt.replaceAll(" ", "zz");
System.out.println(txt);
console.getOut().println("=====================================================================================" );
//=================================================================== send get == need commerciall ssl like startssl.com and serveralias and servername in virtualhost
URL hp = new URL("https://breakermind.com/index.php?line="+txt);
HttpsURLConnection hpCon = (HttpsURLConnection) hp.openConnection();
boolean isProxy = hpCon.usingProxy();
System.out.println("is using proxy " + isProxy);
InputStream obj = hpCon.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
String s;
while ((s = br.readLine()) != null) {
s = s.replaceAll("zz", " ");
s = s.replaceAll("aa", ",");
System.out.println(">>>" + s);
}
//===================================================================== end
} catch (Exception e) {
console.getErr().println(e.getMessage());
e.printStackTrace(console.getErr());
// context.stop();
}
console.getOut().println("=====================================================================================" );
}
public void onMessage(IMessage message) throws JFException { }
public void onAccount(IAccount account) throws JFException { }
public void onStop() throws JFException { }
});
//now it's running
//every second check if "stop" had been typed in the console - if so - then stop the strategy
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Scanner s = new Scanner(System.in);
while(true){
while(s.hasNext()){
String str = s.next();
if(str.equalsIgnoreCase("stop")){
System.out.println("Strategy stop by console command.");
client.stopStrategy(strategyId);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}

Categories

Resources