File list checker blocks deleting and naming of files? - java

In the code below some output is created, some numbers. One of the numbers is a hashvalue. The hashvalue is calculated from a folder.
While the folder is calculated it seems somehow restricted to delete, add and name files. Is this a normal behavior, or could be changed something in the code of the TaskStartPart or TaskPart class ?
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class RestartTest {
StringBuilder sb;
String dtf = "============================";
String hexRes2 = "";
int i1 = 0;
int i2 = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws InterruptedException, IOException, NoSuchAlgorithmException {
// TODO code application logic here
new RestartTest().startApp();
}
public void startApp() throws InterruptedException, IOException, NoSuchAlgorithmException {
TaskStart startTask = new TaskStart();
startTask.startCalc();
}
class TaskStart {
public void startCalc() throws InterruptedException, IOException, NoSuchAlgorithmException {
while(!Thread.currentThread().isInterrupted()) {
i1 = (int) (Math.random() * 1000);
System.out.println("Value 1: " + i1);
new TaskStart2().startCalc2();
new TaskStartPart().calculHash();
dateiSpeichern(i1,i2,"");
}
}
}
class TaskStart2 {
public void startCalc2() throws InterruptedException, IOException {
i2 = (int) (Math.random() * 1000);
System.out.println("Value 2: " + i2);
dateiSpeichern(i1,i2,"");
}
}
class TaskStartPart {
public void calculHash() throws InterruptedException, IOException, NoSuchAlgorithmException {
try {
DigestInputStream digestInputStream=null ;
MessageDigest messageDigest=MessageDigest.getInstance("SHA-512") ;
digestInputStream=new DigestInputStream(new TaskPart(new File("C:\\Users\\win7p\\Documents/t")),messageDigest) ;
//System.out.println("Path :" + direc.toString()) ;
while(digestInputStream.read()>=0) ;
//System.out.print("\nsha-512 sum=") ;
for(byte b: messageDigest.digest()) {
hexRes2 += String.format("%02x",b);
} sb = new StringBuilder(hexRes2);
dateiSpeichern(0,0,sb.substring(hexRes2.length() - 128,hexRes2.length())); System.out.println(sb.substring(hexRes2.length() - 128,hexRes2.length()));
digestInputStream.close();
} catch (IOException ex ) {ex.printStackTrace();}
}
}
class TaskPart extends InputStream {
private File mFile ;
private List<File> mFiles ;
private InputStream mInputStream ;
public TaskPart(File file) throws FileNotFoundException {
mFile=file ;
if(file.isDirectory()) {
mFiles=new ArrayList<File>(Arrays.asList(file.listFiles())) ;
Collections.sort(mFiles) ;
mInputStream=nextInputStream() ;
} else {
mFiles=new ArrayList<File>() ;
mInputStream=new FileInputStream(file) ;
}
}
#Override
public int read() throws IOException {
int result=mInputStream==null?-1:mInputStream.read() ;
if(result<0 && (mInputStream=nextInputStream())!=null)
return read() ;
else return result ;
}
protected String getRelativePath(File file) {
return file.getAbsolutePath().substring(mFile.getAbsolutePath().length()) ;
}
protected InputStream nextInputStream() throws FileNotFoundException {
if(!mFiles.isEmpty()) {
File nextFile=mFiles.remove(0) ;
return new SequenceInputStream(
new ByteArrayInputStream(getRelativePath(nextFile).getBytes()),
new TaskPart(nextFile)) ;
}
else return null ;
}
}
private void dateiSpeichern(int i1, int i2, String hexR) throws InterruptedException, IOException {
try {
String tF = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss").format(new Date().getTime());
try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\win7p\\Documents/hashLog.txt", true))) {
writer.append(tF);
writer.newLine();
writer.append(dtf);
writer.newLine();
writer.append("Hash Value: ");
//If(hexR.length() == alHash.get(0))
//alHash.add(hexR);
writer.append(hexR);
writer.newLine();
writer.append("-----");
writer.append("Value 1:");
String si1 = Integer.toString(i1);
writer.append(si1);
writer.newLine();
writer.append("*****");
writer.append("Value 2:");
String si2 = Integer.toString(i2);
writer.append(si2);
writer.newLine();
writer.flush();
writer.close();
}
} catch(IOException ex) {System.out.print("konnte Datei nicht speichern");}
catch(NullPointerException nex) {System.out.println("no Log-File, try again...");}
} }

I think I have find the problem.
In the method protected InputStream nextInputStream() of the class class TaskPart extends InputStream is a List private List mFiles;.
The problem was the List<> remained filled, so it needed to be cleared once the method was called, with mFiles.clear() in calculhash().
So that the files are not longer listed in that stream, and blocked.
Thank you

Related

I'm trying to read a text file and store it in an arraylist of objects

I'm trying to read a text file and store it in an arraylist of objects, but I keep getting an error saying I cannot convert a String to an Item, which is type of arraylist I am using. I have tried various solutions, but am not quite sure how its is suppossed to be done. I am new to coding and have this assignment due soon. Anything helps!
private void loadFile(String FileName)
{
Scanner in;
Item line;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
line = in.nextLine();
MyStore.add(line);
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
my apologies for not adding the Item class
public class Item
{
private int myId;
private int myInv;
//default constructor
public Item()
{
myId = 0;
myInv = 0;
}
//"normal" constructor
public Item(int id, int inv)
{
myId = id;
myInv = inv;
}
//copy constructor
public Item(Item OtherItem)
{
myId = OtherItem.getId();
myInv = OtherItem.getInv();
}
public int getId()
{
return myId;
}
public int getInv()
{
return myInv;
}
public int compareTo(Item Other)
{
int compare = 0;
if (myId > Other.getId())
{
compare = 1;
}
else if (myId < Other.getId())
{
compare = -1;
}
return compare;
}
public boolean equals(Item Other)
{
boolean equal = false;
if (myId == Other.getId())
{
equal = true;;
}
return equal;
}
public String toString()
{
String Result;
Result = String.format("%8d%8d", myId, myInv);
return Result;
}
}
This is the creation of my arraylist.
private ArrayList MyStore = new ArrayList ();
Here is a sample of my text file.
3679 87
196 60
12490 12
18618 14
2370 65
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.rosmery;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author Sem-6-INGENIERIAINDU
*/
public class aaa {
public static void main(String arg[]) throws FileNotFoundException, IOException{
BufferedReader files=new BufferedReader(new FileReader(new File("")));
List<String> dto=new ArrayList<>();
String line;
while((line= files.readLine())!= null){
line= files.readLine();
dto.add(line);
//Hacer la logica para esos datos
}
}
}
in.nextLine() returns a String.
So, you cannot assign in.nextLine() to an instance of Item.
Your code may need to correct it as:
List<String> myStore = new ArrayList<String>();
private void loadFile(String FileName)
{
Scanner in;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
myStore.add(in.nextLine());
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
If you want to have a list of Item after reading a file, then you need provide the logic that convert given line of information into an instance of Item.
let's say your file content is in the following format.
id1,inv1
id2,inv2
.
.
Then, you can use the type Item as the following.
List<Item> myStore = new ArrayList<Item>();
private void loadFile(String FileName)
{
Scanner in;
String[] line;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
line = in.nextLine().split(",");
myStore.add(new Item(line[0], line[1]));
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
One of the possible solutions (assuming that the data in file lines is separated by a comma), with using streams:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
List<Item> items = loadFile("myfile.txt");
System.out.println(items);
}
private static List<Item> loadFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream
.map(s -> Stream.of(s.split(",")).mapToInt(Integer::parseInt).toArray())
.map(i -> new Item(i[0], i[1]))
.collect(Collectors.toList());
}
}
}
or with foreach:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
List<Item> items = new ArrayList<>();
for (String line : loadFile("myfile.txt")) {
String[] data = line.split(",");
int id = Integer.parseInt(data[0]);
int inv = Integer.parseInt(data[1]);
items.add(new Item(id, inv));
}
System.out.println(items);
}
private static List<String> loadFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream.collect(Collectors.toList());
}
}
}

JUnit tests for writing to file pass locally but fail on Travis CI

The problem
Me and my group members have been instructed by our teacher to implement a logger for our game. This logger should be well tested with JUnit and so we did. One problem we are dealing with for a while now is that all these tests pass locally but are failing every now and then on Travis CI.
Our analysis
We suspect that there is not enough time for these tests to actually create and remove the logging file before the assertion is executed. However, we aren't really sure if this is what causing our tests to fail on Travis.
Our code
Logger.java
package logging;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.sql.Timestamp;
import java.util.Calendar;
public final class Logger extends Thread {
private static volatile boolean debug = false;
private static volatile StringBuilder queue = new StringBuilder();
private static volatile File file = new File("log.log");
private static volatile int logLength = 10000;
private static Logger logger;
/**
* supported logging types.
*
*/
public enum LogType {
INFO, WARNING, ERROR
}
private Logger() {
} // unreachable because static
/**
* The logger runs in his own thread to prevent concurrent writing
* exceptions on the log file if multiple threads are logging.
*/
public void run() {
while (debug) {
try {
sleep(10000);
if (queue.length() > 0) {
try {
writeToFile();
} catch (IOException exception) {
exception.printStackTrace();
}
}
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
}
private void writeToFile() throws IOException {
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.write(queue.toString());
writer.close();
capFileSize();
}
private void capFileSize() throws IOException {
int fileLength = countLines();
if (fileLength > logLength) {
String line;
File tempFile = File.createTempFile("TETRIS_LOG_", ".log");
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
skipLines(fileLength - logLength, reader);
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} finally {
reader.close();
}
} finally {
writer.close();
}
Files.move(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
private void skipLines(int lines, BufferedReader file) throws IOException {
for (int i = 0; i < lines; i++) {
file.readLine();
}
}
private int countLines() throws IOException {
char[] buffer = new char[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
while ((readChars = reader.read(buffer)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (buffer[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
reader.close();
}
}
/**
* Log lets you log a line in the log file, conditional on the debug mode
* being on.
*
* #param sender
* the object invoking the log statement
* #param logtype
* the log type, for homogeneity constrained in the LogType enum
* #param message
* the message that is logged
*/
public static void log(Object sender, LogType logtype, String message) {
if (debug) {
String msg = String.format("[%s] message #[%s] from object %s: %s\r\n",
logtype.toString(),
new Timestamp(Calendar.getInstance().getTimeInMillis()).toString(),
sender.toString(), message);
queue.append(msg);
}
}
public static void info(Object sender, String message) {
Logger.log(sender, LogType.INFO, message);
}
public static void error(Object sender, String message) {
Logger.log(sender, LogType.ERROR, message);
}
public static void warning(Object sender, String message) {
Logger.log(sender, LogType.WARNING, message);
}
/**
* clearLog truncates the log, in case you accidentally logged a nude
* picture or something.
*/
public static void clearLog() {
try {
Files.deleteIfExists(file.toPath());
} catch (IOException exception) {
exception.printStackTrace();
}
}
/* getters / setters */
public static int getLogLength() {
return logLength;
}
public static void setLogLength(int length) {
logLength = length;
}
public static void setLogDir(String path) {
file = new File(path);
}
public static String getLogDir() {
return file.toString();
}
/**
* switch debug on.
*/
public static synchronized void setDebugOn() {
if (!debug) {
debug = true;
logger = new Logger();
logger.start();
}
}
/**
* switch debug off.
*/
public static void setDebugOff() {
if (debug) {
debug = false;
try {
logger.join();
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
logger = null;
}
}
LoggerTest.java
package logging;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class LoggerTest {
#Test
public void test_logcreate() {
String testloc = "test.log";
Logger.setLogDir(testloc);
Logger.clearLog();
Logger.setDebugOn();
Logger.log(this, Logger.LogType.ERROR, "test 1");
Logger.setDebugOff();
assertTrue(new File(testloc).exists());
}
#Test
public void test_logdelete() {
String testloc = "test.log";
Logger.setLogDir(testloc);
Logger.setDebugOn();
Logger.log(this, Logger.LogType.ERROR, "test 1");
assertTrue(new File(testloc).exists());
Logger.setDebugOff();
Logger.clearLog();
assertFalse(new File(testloc).exists());
}
#Test
public void test_debugMode() {
String testloc = "test.log";
Logger.setLogDir(testloc);
Logger.setDebugOff();
Logger.clearLog();
Logger.log(this, Logger.LogType.ERROR, "test 1");
assertFalse(new File(testloc).exists());
}
#Test
public void test_capLog() throws IOException, InterruptedException {
String testloc = "test.log";
Logger.setLogDir(testloc);
Logger.setLogLength(10);
Logger.clearLog();
Logger.setDebugOn();
for (int i = 0; i < 100; i++) {
Logger.log(this, Logger.LogType.ERROR, "test 1");
}
Logger.setDebugOff();
Thread.sleep(1000);
assertTrue(new File(testloc).exists());
int count = 0;
File file = new File(testloc);
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
while (reader.readLine() != null) {
++count;
}
reader.close();
assertEquals(10, count);
}
}
Travis job log
[...]
:test
Download https://jcenter.bintray.com/org/jacoco/org.jacoco.agent/0.7.7.201606060606/org.jacoco.agent-0.7.7.201606060606.pom
Download https://jcenter.bintray.com/org/jacoco/org.jacoco.build/0.7.7.201606060606/org.jacoco.build-0.7.7.201606060606.pom
Download https://jcenter.bintray.com/org/jacoco/org.jacoco.agent/0.7.7.201606060606/org.jacoco.agent-0.7.7.201606060606.jar
tetris.LoggerTest > test_logcreate FAILED
java.lang.AssertionError at LoggerTest.java:26
tetris.LoggerTest > test_logdelete FAILED
java.lang.AssertionError at LoggerTest.java:35
47 tests completed, 2 failed
:test FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
[...]
EDIT #1
I have used Awaitility but Travis is still struggling with file creation/deletion. Even with one minute timeout.
LoggerTest.java
package tetris;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.Callable;
import org.junit.Test;
import static com.jayway.awaitility.Awaitility.with;
import static com.jayway.awaitility.Duration.*;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import logging.Logger;
public class LoggerTest {
#Test
public void test_logcreate() throws Exception {
String testloc = "test.log";
Logger.setLogDir(testloc);
Logger.clearLog();
Logger.setDebugOn();
Logger.log(this, Logger.LogType.ERROR, "test 1");
Logger.setDebugOff();
asyncWaitForFileCreation(testloc);
assertTrue(new File(testloc).exists());
}
#Test
public void test_logdelete() throws Exception {
String testloc = "test.log";
Logger.setLogDir(testloc);
Logger.setDebugOn();
Logger.log(this, Logger.LogType.ERROR, "test 1");
asyncWaitForFileCreation(testloc);
assertTrue(new File(testloc).exists());
Logger.setDebugOff();
Logger.clearLog();
asyncWaitForFileRemoval(testloc);
assertFalse(new File(testloc).exists());
}
#Test
public void test_debugMode() throws Exception {
String testloc = "test.log";
Logger.setLogDir(testloc);
Logger.setDebugOff();
Logger.clearLog();
Logger.log(this, Logger.LogType.ERROR, "test 1");
asyncWaitForFileRemoval(testloc);
assertFalse(new File(testloc).exists());
}
#Test
public void test_capLog() throws Exception {
String testloc = "test.log";
Logger.setLogDir(testloc);
Logger.setLogLength(10);
Logger.clearLog();
Logger.setDebugOn();
for (int i = 0; i < 100; i++) {
Logger.log(this, Logger.LogType.ERROR, "test 1");
Logger.info(this, "test 1");
Logger.warning(this, "test 1");
Logger.error(this, "test 1");
}
Logger.setDebugOff();
File testlocFile = new File(testloc);
asyncWaitForFileCreation(testloc);
assertTrue(testlocFile.exists());
int count = 0;
File file = new File(testloc);
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
while (reader.readLine() != null) {
++count;
}
reader.close();
assertEquals(10, count);
}
#Test
public void test_getters() throws ClassCastException {
assertTrue(Logger.getLogDir() instanceof String);
assertTrue(Logger.getLogLength() == Logger.getLogLength());
}
private void asyncWaitForFileCreation(String testloc) throws Exception {
with().pollDelay(ONE_HUNDRED_MILLISECONDS)
.and().with().pollInterval(TWO_HUNDRED_MILLISECONDS)
.and().with().timeout(ONE_MINUTE)
.await("file creation")
.until(fileIsCreatedOnDisk(testloc), equalTo(true));
}
private void asyncWaitForFileRemoval(String testloc) throws Exception {
with().pollDelay(ONE_HUNDRED_MILLISECONDS)
.and().with().pollInterval(TWO_HUNDRED_MILLISECONDS)
.and().with().timeout(ONE_MINUTE)
.await("file removal")
.until(fileIsRemovedFromDisk(testloc), equalTo(true));
}
private Callable<Boolean> fileIsCreatedOnDisk(final String filename) {
return () -> {
File file = new File(filename);
return file.exists();
};
}
private Callable<Boolean> fileIsRemovedFromDisk(final String filename) {
return () -> {
File file = new File(filename);
return !file.exists();
};
}
}
Travis job log
:test
Download https://jcenter.bintray.com/org/jacoco/org.jacoco.agent/0.7.7.201606060606/org.jacoco.agent-0.7.7.201606060606.pom
Download https://jcenter.bintray.com/org/jacoco/org.jacoco.build/0.7.7.201606060606/org.jacoco.build-0.7.7.201606060606.pom
Download https://jcenter.bintray.com/org/jacoco/org.jacoco.agent/0.7.7.201606060606/org.jacoco.agent-0.7.7.201606060606.jar
tetris.LoggerTest > test_logcreate FAILED
java.util.concurrent.TimeoutException at LoggerTest.java:36
tetris.LoggerTest > test_capLog FAILED
java.util.concurrent.TimeoutException at LoggerTest.java:94
47 tests completed, 2 failed
:test FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
In your first test case, you give your Logger Thread not enough time to create the file. This may work on some OSes, but Travis CI is sloooow. Recommendation: Create a method which polls for a condition (in this case, file exists) for some time (at least five seconds) with some interval (e.g. 100ms).
private static boolean pollForCondition(Callable<Boolean> condition) {
while (/* ... */) {
if (condition.call().booleanValue()) {
return true;
}
// ...
}
return false;
}
This method should be used from all your test cases (from within an assertTrue()).
Also, consider that the execution order of your test cases is not determined (starting with Java 6 or 7, AFAIK). Do you delete created files somewhere before the next test case is starting?

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

Extracting links of a facebook page

How can I extract all the links of a facebook page. Can I extract it using jsoup and pass "like" link as parameter to extract all the user's info who liked that particular page
private static String readAll(Reader rd) throws IOException
{
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1)
{
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readurl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try
{
BufferedReader rd = new BufferedReader
(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
}
finally
{
is.close();
}
}
public static void main(String[] args) throws IOException,
JSONException, FacebookException
{
try
{
System.out.println("\nEnter the search string:");
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
JSONObject json = readurl("https://graph.facebook.com/"+s);
System.out.println(json);
}}
CAN i MODIFY THIS AND INTEGRATE THIS CODE. BELOW CODE EXTRACTS ALL LINKS OF A PARTICULAR PAGE. i TRIED TO THE ABOVE CODE BUT IT'S NOT WORKING
String url = "http://www.firstpost.com/tag/crime-in-india";
Document doc = Jsoup.connect(url).get();
Elements links = doc.getElementsByTag("a");
System.out.println(links.size());
for (Element link : links)
{
System.out.println(link.absUrl("href") +trim(link.text(), 35));
}
}
public static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width-1) + ".";
else
return s;
}
}
you can try alternative way also like this :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public class URLExtractor {
private static class HTMLPaserCallBack extends HTMLEditorKit.ParserCallback {
private Set<String> urls;
public HTMLPaserCallBack() {
urls = new LinkedHashSet<String>();
}
public Set<String> getUrls() {
return urls;
}
#Override
public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
#Override
public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
private void handleTag(Tag t, MutableAttributeSet a, int pos) {
if (t == Tag.A) {
Object href = a.getAttribute(HTML.Attribute.HREF);
if (href != null) {
String url = href.toString();
if (!urls.contains(url)) {
urls.add(url);
}
}
}
}
}
public static void main(String[] args) throws IOException {
InputStream is = null;
try {
String u = "https://www.facebook.com/";
URL url = new URL(u);
is = url.openStream(); // throws an IOException
HTMLPaserCallBack cb = new HTMLPaserCallBack();
new ParserDelegator().parse(new BufferedReader(new InputStreamReader(is)), cb, true);
for (String aUrl : cb.getUrls()) {
System.out.println("Found URL: " + aUrl);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
}
Kind of works, but im not sure you could use jsoup for this I would rather look into casperjs or phantomjs
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class getFaceBookLinks {
public static Elements getElementsByTag_then_FilterBySelector (String tag, String httplink, String selector){
Document doc = null;
try {
doc = Jsoup.connect(httplink).get();
} catch (IOException e) {
e.printStackTrace();
}
Elements links = doc.getElementsByTag(tag);
return links.select(selector);
}
//Test functionality
public static void main(String[] args){
// The class name for the like links on facebook is UFILikeLink
Elements likeLinks = getElementsByTag_then_FilterBySelector("a", "http://www.facebook.com", ".UFILikeLink");
System.out.println(likeLinks);
}
}

FileNotFound exception while files already exist

this code couldn't find the files that the buffered reader is supposed to read from it and i have the files in the src folder in eclipse project and it still doesn't read from file so does anybody have any idea about what the problem is.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.*;
import java.util.ArrayList;
public class Encrypt {
public static ArrayList<String> data = new ArrayList<String>();
public static BigInteger [] keys = new BigInteger[3];
public static BigInteger n;
public static double e;
public static BigInteger d;
public static String line;
public static String result;
public static String [] temp;
public static BigInteger tempVar;
public static BigInteger tempResult;
public static int tempVar2;
public static void encryption(ArrayList<String> data) throws IOException{
for (int i = 0; i<data.size(); i++){
if(data.get(i)!= null){
temp = new String[data.get(i).split(" ").length];
temp = data.get(i).split(" ");
for(int j = 0; j<temp.length;j++){
for (int k = 0; k< temp[j].length(); k++){
tempVar2 = (int)temp[j].charAt(k);
tempVar=BigInteger.valueOf((long)Math.pow(tempVar2,e));
tempResult = (tempVar.remainder(n));
result =""+ tempResult;
LogEncrypt(result);
}
}
}
}
}
public static void read() throws IOException{
try {
BufferedReader br = new BufferedReader(new FileReader("plainText.txt"));
System.out.println(br.ready());
while ((line = br.readLine()) != null) {
data.add(br.readLine());
}
System.out.println("done with text");
} catch (FileNotFoundException e) {
System.out.println("please add the text file");
e.printStackTrace();
}
try {
BufferedReader ba = new BufferedReader(new FileReader("Key.txt"));
System.out.println(ba.ready());
int i =0;
while ((line = ba.readLine()) != null) {
keys[i] = new BigInteger(ba.readLine());
i++;
}
n = keys[0];
e = keys[1].doubleValue();
d = keys[2];
System.out.println("done with key");
} catch (FileNotFoundException e) {
System.out.println("please add the key file");
e.printStackTrace();
}
}
public static void LogEncrypt(String result) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
try {
out.write(result);
out.newLine();
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
}
}
public static void main(String[]args) throws IOException{
read();
encryption(data);
}
}
Put the file outside of the src, or at least add "src/" to the file location

Categories

Resources