iText7 Encryption PdfDocument - itext7

In upgrading iText7 I see there need to be a EncryptionConstants.ENCRYPTION_AES_128 Is that correct. I am also not seeing how to add the writerProperties to my PdfDocument
Old Version
pdfDocument.Writer.SetEncryption(true, null, null, PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
New Version
WriterProperties writerProperties = new WriterProperties();
writerProperties.SetStandardEncryption(null, null, EncryptionConstants.ALLOW_PRINTING | EncryptionConstants.ALLOW_COPY, EncryptionConstants.ENCRYPTION_AES_128);

Please check the below code of iText 7 for adding or encrypting pdf files with owner and user password.
public class EncryptPdf
{
public static readonly String DEST = "results/sandbox/security/encrypt_pdf.pdf";
public static readonly String SRC = "../../../resources/pdfs/hello.pdf";
public static readonly String OWNER_PASSWORD = "World";
public static readonly String USER_PASSWORD = "Hello";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new EncryptPdf().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument document = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest,
new WriterProperties().SetStandardEncryption(
Encoding.UTF8.GetBytes(USER_PASSWORD),
Encoding.UTF8.GetBytes(OWNER_PASSWORD),
EncryptionConstants.ALLOW_PRINTING,
EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA
)));
document.Close();
}
}

Related

wicket; images from file system. I added resourse folder, and still working

What I want is adding resource folder from file system for storing images and displaying them. I added the folder in the Application, and still working.
WicketTestApplication#init
getResourceSettings().getResourceFinders().add( new WebApplicationPath( getServletContext(), "C:\\image" ) );
And TestPage
public class TestPage extends WebPage {
private static final long serialVersionUID = 1L;
public TestPage() {
add( new ContextImage( "image", "C:/image/rhodes.jpg" ) );
}
}
Do I miss something?
WebApplicationPath is a IResourceFinder that will look for resources in the web application path, except in WEB-INF/ folder. So you cannot use it to load something from your file system.
I'd suggest you to use FileSystemResource[Reference] instead or a specialization of DynamicImageResource.
private static class ImageResource extends DynamicImageResource {
#Override
protected byte[] getImageData(Attributes attributes) {
PageParameters parameters = attributes.getParameters();
StringValue name = parameters.get("name");
byte[] imageBytes = null;
if (name.isEmpty() == false) {
imageBytes = getImageAsBytes(name.toString());
}
return imageBytes;
}
private byte[] getImageAsBytes(String imageName) {
// read the image from the file system, e.g. with FileInputStream(folder, imageName);
}
#Override
public boolean equals(Object that) {
return that instanceof ImageResource;
}
}
An article explaining this approach can be found at: http://wicketinaction.com/2011/07/wicket-1-5-mounting-resources/

How to refresh tableview after adding the new data in JavaFx

I am currently working on JAVA FX application to fetch the user's information from JIRA REST API. I want to have a refresh button and on clicking it,the table view must be shown with the newly added data.
Please have a look at the code.
My POJO class
public class Issues {
private String jiraKey;
private String jiraSummary;
private String jiraPriority;
private String jiraAssignee;
private String jiraIssueType;
private Hyperlink hyperLink;
private String loghours;
private String commentLogHours;
public Issues(String jiraKey, String jiraSummary, String jiraPriority, String jiraAssignee, String jiraIssueType) {
super();
this.hyperLink = new Hyperlink(jiraKey);
this.jiraSummary = jiraSummary;
this.jiraPriority = jiraPriority;
this.jiraAssignee = jiraAssignee;
this.jiraIssueType = jiraIssueType;
this.hyperLink = hyperLink;
this.loghours = loghours;
this.commentLogHours = commentLogHours;
}
public String getJiraKey() {
return jiraKey;
}
public void setJiraKey(String jiraKey) {
this.jiraKey = jiraKey;
}
//getters and setters
}
My Observable list method which populates the data to table
Class ABC{
public ObservableList<Issues> issueJsonList(){
// A processed arraylist
ObservableList<Issues> data = FXCollections.observableList(list);
return data;
}
}
Here's my tableview code.
#SuppressWarnings({ "unchecked", "rawtypes" })
public TableView<Issues> initTable() throws IOException, URISyntaxException {
TableView<Issues> table = new TableView<Issues>();
table.setEditable(true);
TableColumn<Issues, Hyperlink> jiraKey = new TableColumn<>(keyField);
jiraKey.setCellValueFactory(new PropertyValueFactory("hyperLink"));
jiraKey.setCellFactory(new HyperlinkCell());
TableColumn jiraPriority = new TableColumn(priorityField);
TableColumn jiraIssueType = new TableColumn(issueTypeField);
TableColumn jiraSummary = new TableColumn(summaryField);
TableColumn jiraAssignee = new TableColumn(assigneeField);
TableColumn workLogCol = new TableColumn(workLogField);
TableColumn timeSpent = new TableColumn(timeSpentField);
TableColumn commentTimeLog = new TableColumn(commentField);
workLogCol.getColumns().addAll(timeSpent, commentTimeLog);
jiraSummary.setCellValueFactory(new PropertyValueFactory("jiraSummary"));
jiraIssueType.setCellValueFactory(new PropertyValueFactory("jiraIssueType"));
jiraPriority.setCellValueFactory(new PropertyValueFactory("jiraPriority"));
jiraAssignee.setCellValueFactory(new PropertyValueFactory("jiraAssignee"));
timeSpent.setCellValueFactory(new PropertyValueFactory("getTimeSpent"));
timeSpent.setCellFactory(TextFieldTableCell.forTableColumn());
commentTimeLog.setCellValueFactory(new PropertyValueFactory("getComment"));
commentTimeLog.setCellFactory(TextFieldTableCell.forTableColumn());
timeSpent.setOnEditCommit(new EventHandler<CellEditEvent<JiraAuth, String>>() {
public void handle(CellEditEvent<JiraAuth, String> t) {
JiraAuth.setTimeSpent(t.getNewValue());
}
});
commentTimeLog.setCellFactory(TextFieldTableCell.forTableColumn());
commentTimeLog.setOnEditCommit(new EventHandler<CellEditEvent<JiraAuth, String>>() {
public void handle(CellEditEvent<JiraAuth, String> t) {
JiraAuth.setWorkLogComment(t.getNewValue());
int i = t.getTablePosition().getRow();
String abc = table.getColumns().get(0).getCellData(i).toString();
String finalStr = abc.substring(abc.indexOf("]") + 1);
JiraAuth.setWorkLogJiraKey(finalStr);
}
});
table.getColumns().setAll(jiraKey, jiraSummary, jiraPriority, jiraAssignee, jiraIssueType);
IssuesJsonParser issueObject = new IssuesJsonParser();
ObservableList<Issues> data = issueObject.issueJsonList();
table.setItems(data);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
return table;
}
upon calling the refresh button,
buttons[0] = new Button("Refresh");
buttons[0].setOnAction(event->{
initTable().refresh();
});
nothing happens. Please help!!

IO streams to JPanel, GUI with InputStream and OutputStream in a JPanels JTextField and JTextArea

I'm trying to write a GUI where the user sees the System output in a JTextArea and where he writes the input in a JTextField, both object inside a JPanel.
How do I do to connect the System output stream to the JTextArea and the System input stream to the JTextField? I have googled and searched these forums but havnt found the solution. I would be very happy if someone could help me with this.
I have a Master class that calls the JPanel with the GUI, and I will have work executed in different threads later on, but right now I struggle with the basic issue of connecting IO streams to the JPanel. Down below is the 2 classes:
public class MainTest {
public static void main(String[] args) throws IOException {
JPanelOUT testpanel = new JPanelOUT();
JFrame frame = new JFrame();
frame.add(testpanel);
frame.setVisible(true);
frame.pack();
/*
System.setOut(CONVERT TEXTAREA TO AN OUTPUTSTREAM SOMEHOW??(JPanelOUT.textArea)));
System.setIn(CONVERT STRING TO AN INPUTSTREAM SOMEHOW?? JPanelOUT.textField);
*/
String text = Sreadinput();
System.out.println(text);
}
public static String Sreadinput() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(JPanelOUT.is));
String input=in.readLine();
return input;
}
}
public class JPanelOUT extends JPanel implements ActionListener {
protected static JTextField textField;
protected static JTextArea textArea;
public static InputStream is;
private final static String newline = "\n";
public JPanelOUT() throws UnsupportedEncodingException, FileNotFoundException {
super(new GridBagLayout());
JLabel label1 = new JLabel("OUTPUT:");;
JLabel label2 = new JLabel("INPUT:");;
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
textArea.setBackground(Color.black);
textArea.setForeground(Color.white);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(500,200));
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(label1, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
add(label2, c);
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
String WelcomeText1 = "Hello and welcome to the TEST";
String WelcomeText2 = "Trying to get the input field below to become the System.in and this output";
String WelcomeText3 = "field to become the System.out (preferrably both with UTF-8 encoding where";
String WelcomeText4 = "the scrollpane automatically scrolls down to the last output line)!";
textArea.append(WelcomeText1 + newline + newline + WelcomeText2 + newline + WelcomeText3 + newline + WelcomeText4 + newline + newline);
String text = textField.getText();
is =new ByteArrayInputStream(text.getBytes("UTF-8"));
}
public void actionPerformed(ActionEvent evt) {
String text2 = textField.getText();
textArea.append(text2 + newline);
textField.selectAll();
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
i am new to java, trying to deal with the streams, too :)
Sorry for bad English I am from Russia.
May be this code will help you.
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public MyPrintStream myPrintStream;
public NewJFrame()throws FileNotFoundException{
initComponents();
this.myPrintStream = new MyPrintStream("string");
}
private class MyPrintStream extends PrintStream {
MyPrintStream(String str)throws FileNotFoundException{
super(str);
}
public void println(String s){
textArea1.append(s+'\n');
}
} .. continuation class code
Main method:
public static void main(String args[]){
/* Set the Nimbus look and feel... */
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run(){
try{
NewJFrame myJFrame = new NewJFrame();
myJFrame.setVisible(true);
System.setOut(myJFrame.myPrintStream);
System.out.println("its work");
System.out.println("its work2");
System.out.print("str"); //does not work, need to override
}catch (FileNotFoundException e){System.out.println (e.getMessage());}
}
});

JavaFX 2 and Internationalization

I've just started writing my first JavaFX 2 application after learning the basics and would like to internationalize it.
I notice that in JavaFX 1.x, the scripting language allowed for very simple internationalization of strings. Are there any similar features in JavaFX 2?
Basically: what is the best practice for internationalizing a JavaFX 2 application?
The basic steps (among others) of a java app internationalizing, are Localelizing and resource bundling. In JavaFX, you can use FXMLLoader#setResources() for that purposes. Here a SSCCE demo to demonstrate it. The codes are self-descriptive.
Demo package structure:
bundledemo
|------ BundleDemo.java
|------ MyController.java
|------ MyView.fxml
bundles
|------ MyBundle_en.properties
|------ MyBundle_kg.properties
MyBundle_en.properties
key1=Name Surname
key2=How are you?
MyBundle_kg.properties
key1=Aты Жөнү
key2=Кандайсың?
MyView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.*?>
<BorderPane fx:controller="bundledemo.MyController" xmlns:fx="http://javafx.com/fxml">
<top>
<!-- This label's text will be set by the controller -->
<Label fx:id="lblTextByController"/>
</top>
<center>
<!-- This label's text will be taken from the bundle automatically -->
<Label text="%key2"/>
</center>
</BorderPane>
MyController.java
package bundledemo;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class MyController implements Initializable {
#FXML private Label lblTextByController;
private ResourceBundle bundle;
#Override
public void initialize(URL location, ResourceBundle resources) {
bundle = resources;
lblTextByController.setText(bundle.getString("key1"));
}
}
BundleDemo.java
package bundledemo;
// imports are ignored.
public class BundleDemo extends Application {
private Stage stage;
#Override
public void start(Stage primaryStage) {
stage = primaryStage;
Button btnEN = new Button();
btnEN.setText("English");
btnEN.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
loadView(new Locale("en", "EN"));
}
});
Button btnKG = new Button();
btnKG.setText("Kyrgyz");
btnKG.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
loadView(new Locale("kg", "KG"));
}
});
VBox root = new VBox(20);
root.getChildren().add(HBoxBuilder.create().spacing(10).style("-fx-background-color: gray").padding(new Insets(5)).children(btnEN, btnKG).build());
root.getChildren().add(new StackPane());
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
private void loadView(Locale locale) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setResources(ResourceBundle.getBundle("bundles.MyBundle", locale));
Pane pane = (BorderPane) fxmlLoader.load(this.getClass().getResource("MyView.fxml").openStream());
// replace the content
StackPane content = (StackPane) ((VBox) stage.getScene().getRoot()).getChildren().get(1);
content.getChildren().clear();
content.getChildren().add(pane);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Screenshot:
If your internationalized text needs to be rendered in a font that might be on the user's target system, then you can either:
Embed the font with your application:
How to embed .ttf fonts is JavaFx 2.2?
OR
Use web(Google) fonts in JavaFX.
If the required font is not available, then the internationalized text might be displayed as unintelligible gibberish, even though everything else about the setup is fine.
This works for me:
└───src
├───app
├───bundles // <- here the "bundles"
├───dicts
├───images
├───libs
└───resources
In the bundles package are
LangBundle_en.properties
LangBundle_de.properties
Sample content:
enter_pwd=Enter your password:
To load them I use the following code:
#Override
public void initialize(URL location, ResourceBundle resources) {
ResourceBundle lngBndl = ResourceBundle
.getBundle("bundles.LangBundle", new Locale("en", "EN"));
tvSetupPwd.setText(lngBndl.getString("enter_pwd"));
// ...
}
Look at my example
More I described here or on GitHub
Update:
the solution is in Messages.java
/**
* The class with all messages of this application.
*/
public abstract class Messages {
private static ResourceBundle BUNDLE;
private static final String FIELD_NAME = "lookup";
private static final String BUNDLE_NAME = "messages/messages";
private static final String CONTROLS_BUNDLE_NAME = "com/sun/javafx/scene/control/skin/resources/controls";
public static final String MAIN_APP_TITLE;
public static final String DIALOG_HEADER;
public static final String MAIN_CONTROLLER_CONTENT_TEXT;
public static final String MAIN_CONTROLLER_HELLO_TEXT;
public static final String MAIN_CONTROLLER_GOODBYE_TEXT;
static {
final Locale locale = Locale.getDefault();
final ClassLoader classLoader = ControlResources.class.getClassLoader();
final ResourceBundle controlBundle = getBundle(CONTROLS_BUNDLE_NAME,
locale, classLoader, PropertyLoader.getInstance());
final ResourceBundle overrideBundle = getBundle(CONTROLS_BUNDLE_NAME,
PropertyLoader.getInstance());
final Map override = getUnsafeFieldValue(overrideBundle, FIELD_NAME);
final Map original = getUnsafeFieldValue(controlBundle, FIELD_NAME);
//noinspection ConstantConditions,ConstantConditions,unchecked
original.putAll(override);
BUNDLE = getBundle(BUNDLE_NAME, PropertyLoader.getInstance());
MAIN_APP_TITLE = BUNDLE.getString("MainApp.title");
DIALOG_HEADER = BUNDLE.getString("Dialog.information.header");
MAIN_CONTROLLER_CONTENT_TEXT = BUNDLE.getString("MainController.contentText");
MAIN_CONTROLLER_HELLO_TEXT = BUNDLE.getString("MainController.helloText");
MAIN_CONTROLLER_GOODBYE_TEXT = BUNDLE.getString("MainController.goodbyeText");
}
public static ResourceBundle GetBundle() {
return BUNDLE;
}
}
and in PropertyLoader.java
public class PropertyLoader extends ResourceBundle.Control {
private static final String PROPERTIES_RESOURCE_NAME = "properties";
private static final PropertyLoader INSTANCE = new PropertyLoader();
public static PropertyLoader getInstance() {
return INSTANCE;
}
#Override
public ResourceBundle newBundle(final String baseName, final Locale locale, final String format,
final ClassLoader loader, final boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
final String bundleName = toBundleName(baseName, locale);
final String resourceName = toResourceName(bundleName, PROPERTIES_RESOURCE_NAME);
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
final URL url = loader.getResource(resourceName);
if (url != null) {
final URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
bundle = new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
} finally {
stream.close();
}
}
return bundle;
}
}

Wicket serving images from File System

I am pretty new to Wicket and i have some difficulties with using resource references. I am using wicket 1.5.4 and have following problem: I store images on the file system. I have class ImageElement which holds part of the file path relative to configured rootFilePath (i.e dir1/dir2/img1.png). On the page I add Image as follows:
new Image("id",ImagesResourceReference.get(), pageParameters)
where page parameters includes image path parameter (path="/dir1/dir2/img1.png"). My questions are:
Is it the simplest way of serving images from the file system?
Is it ok to use ResourceReference with static method? or I should construct each time new ResourceReference? I saw that in previous version it was possible to use new ResourceReference(globalId), but it seems not to be the case anymore. If so what is the global resource reference for? So far as I understand resource reference is supposed to be factory for resources so it would be rather strange to create new factory for each resource request.
The last question is, how can i pass the path to the image in a better way so that i do not have to concatenate indexed parameters to build the path once respond method is invoked on ImageResource.
What would be the best scenario to get it working in efficient and simple way, i saw the example in 'Wicket in action', but this is meant for dynamic image generation from db and am not sure if it suites for my case
My implementation of ResourceReference which I mounted in Application under "/images" path, looks as follows:
public class ImagesResourceReference extends ResourceReference {
private static String rootFileDirectory;
private static ImagesResourceReference instance;
private ImagesResourceReference() {
super(ImagesResourceReference.class, "imagesResourcesReference");
}
public static ImagesResourceReference get() {
if(instance == null) {
if(StringUtils.isNotBlank(rootFileDirectory)) {
instance = new ImagesResourceReference();
} else {
throw new IllegalStateException("Parameter configuring root directory " +
"where images are saved is not set");
}
}
return instance;
}
public static void setRootFileDirectory(String rootFileDirectory) {
ImagesResourceReference.rootFileDirectory = rootFileDirectory;
}
private static final long serialVersionUID = 1L;
#Override
public IResource getResource() {
return new ImageResource(rootFileDirectory);
}
private static class ImageResource implements IResource {
private static final long serialVersionUID = 1L;
private final String rootFileDirectory;
public ImageResource(String rootFileDirectory) {
this.rootFileDirectory = rootFileDirectory;
}
#Override
public void respond(Attributes attributes) {
PageParameters parameters = attributes.getParameters();
List<String> indexedParams = getAllIndexedParameters(parameters);
if(!indexedParams.isEmpty() && isValidImagePath(indexedParams)) {
String pathToRequestedImage = getImagePath(indexedParams);
FileResourceStream fileResourceStream = new FileResourceStream(new File(pathToRequestedImage));
ResourceStreamResource resource = new ResourceStreamResource(fileResourceStream);
resource.respond(attributes);
}
}
private boolean isValidImagePath(List<String> indexedParams) {
String fileName = indexedParams.get(indexedParams.size() -1);
return !FilenameUtils.getExtension(fileName).isEmpty();
}
private List<String> getAllIndexedParameters(PageParameters parameters) {
int indexedparamCount = parameters.getIndexedCount();
List<String> indexedParameters = new ArrayList<String>();
for(int i=0; i<indexedparamCount ;i++) {
indexedParameters.add(parameters.get(i).toString());
}
return indexedParameters;
}
private String getImagePath(List<String> indexedParams) {
return rootFileDirectory + File.separator + StringUtils.join(indexedParams, File.separator);
}
}
Any help and advices appreciated! Thanks in advance.
You could use it as a shared resource:
public class WicketApplication extends WebApplication {
#Override
public Class<HomePage> getHomePage() {
return HomePage.class;
}
#Override
public void init() {
super.init();
getSharedResources().add("downloads", new FolderContentResource(new File("C:\\Users\\ronald.tetsuo\\Downloads")));
mountResource("downloads", new SharedResourceReference("downloads"));
}
static class FolderContentResource implements IResource {
private final File rootFolder;
public FolderContentResource(File rootFolder) {
this.rootFolder = rootFolder;
}
public void respond(Attributes attributes) {
PageParameters parameters = attributes.getParameters();
String fileName = parameters.get(0).toString();
File file = new File(rootFolder, fileName);
FileResourceStream fileResourceStream = new FileResourceStream(file);
ResourceStreamResource resource = new ResourceStreamResource(fileResourceStream);
resource.respond(attributes);
}
}
}
You can still use ResourceReferences with global IDs. You just have to use a SharedResourceReference. This is probably better, too.
add(new Image("image", new SharedResourceReference("mySharedResourceRef", parameters));
I would try to avoid building paths from URL parameters. This can easily end up in security leaks.

Resources