Read gml file using GraphML Reader Prefuse - prefuse

I am new to Prefuse.I am facing problem reading the polbooks.gml file using GraphML Reader.
It can successfully read a xml file but not a gml file.Please suggest a solution how to read a gml file in Prefuse.
Below is my code for GraphML Reader
package practise;
import prefuse.data.Graph;
import prefuse.data.io.DataIOException;
import prefuse.data.io.GraphMLReader;
public class practise1 {
static Graph graph = null;
public static void main(String[] args){
try{
graph=new GraphMLReader().readGraph("polbooks.gml");
}
catch(DataIOException e){
System.out.print("File Not Found");
}
//System.out.print(graph.getDegree(2));
}
}

Prefuse currently doesn't have a GML reader, only a graphml reader. There is a gml reader that may work here:
http://nwb.cns.iu.edu/svn/nwb/trunk/plugins/visualization/edu.iu.nwb.visualization.prefuse.alpha.smallworld/src/edu/iu/nwb/visualization/prefuse/alpha/smallworld/types/GMLGraphReader.java

Related

How to import JSON data files to mongodb with Spring Boot?

As you know, when using spring boot jpa module, below codes in application.properties import pre-defined sql data to rdb.
spring.datasource.initialization-mode = always
spring.datasource.data = classpath:/sql/spring-boot-mysql.sql
But when using mongodb as storage, what properties codes in application.properties file can import pre-defined JSON data of external files? If such properties do not exit, how can the JSON data be imported from the external files with spring boot?
I don't know if there is a solution using application.properties but here is my solution to import documents from a file containing one document per line.
public static void importDocumentsFromJsonFile(File file) {
//Read each line of the json file. Each file is one observation document.
List<Document> observationDocuments = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file.getPath()));) {
String line;
while ((line = br.readLine()) != null) {
observationDocuments.add(Document.parse(line));
}
} catch (IOException ex) {
ex.getMessage();
}
mongoTemplate.getCollection("yourCollection").insertMany(observationDocuments);
}
You can have a look at this following Test class, provided by "flapdoodle". The test shows how to import a JSON file containing the collection dataset: MongoImportExecutableTest.java
You could theoretically also import a whole dump of a database. (using MongoDB restore): MongoRestoreExecutableTest.java

jar file not up updating values in file

I have a javafx project that I am preparing for distributions. The project works perfectly from the debugger inside NetBeans. I am working on Linux.
But when I run the project from the jar file, there is one function in all the others that does not work. This function is supposed to open the settings file on a button click and alter some values from true to false.
I have changed the settings file's location and tried around google, but all to no avail.
I am still quite a newbie to java, fx, netbeans and java (not so much programming) and making my first experiences.
Any idea why this happens?
#FXML
private void openSettingsFile(ActionEvent event) throws IOException {
// this test works ....
ProcessBuilder processBuilder = new ProcessBuilder("terminal");
processBuilder.start();
// this part only replaces the values when I use the debugger ..
Path path = Paths.get("src/desktop_launcher/Settings.java");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path));
content = content.replaceAll(" \"true\"" , " \"false\"");
Files.write(path, content.getBytes(charset));
Your approach (which, as far as I understand it, is to try to programmatically change the source file that generates the properties file) will not work at deployment time for a number of reasons.
The first is that the source files are generally not available at runtime: your jar file contains the class files and other resources required to run the application, but typically not the source code (and it's not desirable to include it in the application, in general).
Secondly, you are trying to locate this file from a relative path passed to Paths.get(..). This will resolve relative to the working directory, which is essentially arbitrary (basically "where the application was run from"). So even if the source code were available at runtime, this would not be a reliable way to find it. (My guess is that your debugger runs with the working directory fortuitously set to the parent directory of src, but when you run the jar file the most likely location of the working directory is the directory in which the jar file is located. But that is just a guess: it really depends on the configuration of your IDE, debugger, etc etc.)
Thirdly, and probably most importantly, even if the code does find the source file and rewrite it, that's all it will do. Next time you execute the application from the jar file, it won't magically know there is a new version of the source code that has to be compiled and then the resulting class file(s) incorporated into the jar file. So you would have to also include code to compile the new version of your source code (where will you get a compiler? AFAIK not all Java runtimes will include a compiler) and then programmatically insert the new class file(s) into the jar file (how do you even figure out where the jar file is: that is certainly non-trivial and I don't think it can be done in a reliable manner). What if the current user doesn't have permissions to write the directory containing the jar (which is a pretty common scenario..)?
The usual way to load and save startup configuration values is to use the java.util.Properties API. You need an external location to store the properties file, that you can be certain exists on the user's computer: a convenient way to do this is to create an application-specific directory in the user's home directory. The user's home directory can be accessed via System.getProperty("user.home"); (The system property user.home is one of those that is guaranteed to exist.).
I would recommend using a separate class to manage the configuration properties. For example:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Properties;
public class PropertiesAccessor {
private static final Path USER_HOME = Paths.get(System.getProperty("user.home"));
private Properties props ;
private Path path ;
public PropertiesAccessor(String relativePath) {
path = USER_HOME.resolve(relativePath);
props = new Properties();
if (Files.exists(path)) {
try {
props.load(Files.newBufferedReader(path));
} catch (IOException exc) {
System.err.println("Warning: could not load properties file. Using defaults.");
exc.printStackTrace(System.err);
loadDefaults();
}
} else {
loadDefaults();
}
}
public Boolean getBooleanValue(String key) {
String value = props.getProperty(key);
return value == null ? null : Boolean.valueOf(value) ;
}
public void updateBooleanValue(String key, boolean value) {
props.setProperty(key, Boolean.toString(value));
}
public void writeProperties() throws IOException {
if (! Files.exists(path)) {
Files.createDirectories(path.getParent());
Files.createFile(path);
}
props.store(Files.newBufferedWriter(path), "Properties updated "+LocalDateTime.now());
}
private final void loadDefaults() {
// in real life, you might keep a default properties file bundled with
// the application and read that here, e.g.
// props.load(getClass().getResourceAsStream("/default-startup.properties"));
props.setProperty("config.value1", "true");
props.setProperty("config.value2", "false");
}
}
And now you can use this in your application. Just load the properties in the init() method and save them back in the stop() method. Note that executing this will create a directory called .myApp in your home directory, and a file called startup.properties inside it.
import java.io.IOException;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class StartupPropertiesExample extends Application {
private PropertiesAccessor config ;
private CheckBox value1 ;
private CheckBox value2 ;
#Override
public void init() {
config = new PropertiesAccessor(".myApp/startup.properties");
}
#Override
public void start(Stage primaryStage) {
value1 = new CheckBox("Value 1");
value2 = new CheckBox("Value 2");
value1.setSelected(config.getBooleanValue("config.value1"));
value2.setSelected(config.getBooleanValue("config.value2"));
Button exit = new Button("Exit");
exit.setOnAction(e -> Platform.exit());
VBox root = new VBox(10, value1, value2, exit);
root.setPadding(new Insets(10));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
#Override
public void stop() {
config.updateBooleanValue("config.value1", value1.isSelected());
config.updateBooleanValue("config.value2", value2.isSelected());
try {
config.writeProperties();
} catch (IOException exc) {
System.err.println("Warning: could not save properties");
exc.printStackTrace(System.err);
}
}
public static void main(String[] args) {
launch(args);
}
}

POI insert photo into excel but fail

below is my code copied from somewhere on the web used to copy an image file to a excel file worksheet.
but it has error on running statement
"int my_picture_id = my_workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);"
with error "Exception in thread "main" java.lang.NoClassDefFoundError:
org/apache/commons/codec/digest/DigestUtils
at org.apache.poi.hssf.usermodel.HSSFWorkbook.addPicture(HSSFWorkbook.java:1610)
at Addphoto.main(Addphoto.java:19)"
I cannot find the reason as i am really a newbie on java. Please help to solve this trouble.
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
public class Addphoto {
public static void main(String[] args) throws Exception{
HSSFWorkbook my_workbook = new HSSFWorkbook();
HSSFSheet my_sheet = my_workbook.createSheet("MyBanner");
InputStream my_banner_image = new FileInputStream("C:/path/123.jpg");
byte[] bytes = IOUtils.toByteArray(my_banner_image);
int my_picture_id = my_workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
my_banner_image.close();
HSSFPatriarch drawing = my_sheet.createDrawingPatriarch();
ClientAnchor my_anchor = new HSSFClientAnchor();
my_anchor.setCol1(2);
my_anchor.setRow1(1);
HSSFPicture my_picture = drawing.createPicture(my_anchor, my_picture_id);
my_picture.resize();
FileOutputStream out = new FileOutputStream(new File("C:/path/uploadphoto-test.xls"));
my_workbook.write(out);
out.close();
}
}
I hope you get your answer.....
But to help other I am posting this.
This problem happens if you are missing the JAR file commons-codec-1.7.jar which is a part of Apache Commons Codec distribution. POI needs this JAR file to add the image to the workbook. So, make sure you have this JAR file (or equivalent version) in your classpath.

How to edit a maven POM at runtime?

I need editing POM at runtime. I used Dom4j for read pom and after that set some data. But i need know if exist another form for to do this. Exist a maven utilities for this?
Use MavenXpp3Reader to read and MavenXpp3Writer to write Model objects. Simple example:
String baseDir = "/your/project/basedir/";
//Reading
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(new FileInputStream(new File(baseDir, "/pom.xml")));
//Editing
model.setUrl("http://stackoverflow.com");
//Writing
MavenXpp3Writer writer = new MavenXpp3Writer();
writer.write(new FileOutputStream(new File(baseDir, "/pom.xml")), model);
And notice that any comment, extra white spaces or lines will be removed from the file.
Depending on what you are changing, there may be maven plugins. For example the maven release plugin updates the version information in the pom.xml and checks the changes into version control.
Try searching for the specific task you are trying to accomplish (e.g. "maven plugin version number update") rather than the more generic "modify pom.xml".
This code works for me:
package or.jrichardsz;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
public class TestMavenPomEdit {
public static void main(String[] args) throws Exception {
//read initial pom
Model model = parsePomXmlFileToMavenPomModel("C:\\Users\\User\\Desktop\\initial_pom.xml");
//add some pom modification
Plugin plugin = new Plugin();
plugin.setGroupId("com.jelastic");
model.getBuild().addPlugin(plugin);
//write new pom
parseMavenPomModelToXmlString("C:\\Users\\User\\Desktop\\final_pom.xml", model);
}
public static Model parsePomXmlFileToMavenPomModel(String path) throws Exception {
Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
reader = new FileReader(path);
model = mavenreader.read(reader);
return model;
}
public static void parseMavenPomModelToXmlString(String path,Model model) throws Exception {
MavenXpp3Writer mavenWriter = new MavenXpp3Writer();
Writer writer = new FileWriter(path);
mavenWriter.write(writer, model);
}
}
TestMavenPomEdit.java
HTH

convert MHT files to images

Are there any libraries or APIs available to convert MHT files to images? Can we use Universal Document Converter software to do this? Appreciate any thoughts.
If you really want to do this programatically,
MHT
Archived Web Page. When you save a Web
page as a Web archive in Internet
Explorer, the Web page saves this
information in Multipurpose Internet
Mail Extension HTML (MHTML) format
with a .MHT file extension. All
relative links in the Web page are
remapped and the embedded content is
included in the .MHT file.
you can use the JEditorPane to convert this into an Image
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class Test {
private static volatile boolean loaded;
public static void main(String[] args) throws IOException {
loaded = false;
URL url = new URL("http://www.google.com");
JEditorPane editorPane = new JEditorPane();
editorPane.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("page")) {
loaded = true;
}
}
});
editorPane.setPage(url);
while (!loaded) {
Thread.yield();
}
File file = new File("out.png");
componentToImage(editorPane, file);
}
public static void componentToImage(Component comp, File file) throws IOException {
Dimension prefSize = comp.getPreferredSize();
System.out.println("prefSize = " + prefSize);
BufferedImage img = new BufferedImage(prefSize.width, comp.getPreferredSize().height,
BufferedImage.TYPE_INT_ARGB);
Graphics graphics = img.getGraphics();
comp.setSize(prefSize);
comp.paint(graphics);
ImageIO.write(img, "png", file);
}
}

Resources