How to add header and footer using pdfstamper in itextpdf when servlet is database responsive? - servlets

I have a servlet which is creating a PDF direct from mysql database. Everything works fine, but now I need to add header and footer in every page of that dynamically generated pdf. The header must show 'Page current_page_number of total_number_of_page' and footer must retrieve some data from mysql database and show in a table format. I really stuck in this problem for last couple of weeks.
I am using servlet 2.5 and itextpdf 5.5.4.
Here I am attaching my code:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.Image;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import java.io.DataOutputStream;
import com.itextpdf.text.pdf.PdfContentByte;
/**
* Servlet implementation class for Servlet: formPart11PDF
*
*/
public class formPart11PDF extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
private String dbURL = "jdbc:mysql://localhost:3306/test";
private String dbUser = "root";
private String dbPass = "admin";
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#HttpServlet()
*/
public formPart11PDF() {
super();
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream os = response.getOutputStream();
response.setContentType("application/pdf");
DataOutputStream output = new DataOutputStream(os);
Document doc = new Document();
Font bf12 = new Font(FontFamily.TIMES_ROMAN, 12);
Font f = new Font(FontFamily.TIMES_ROMAN, 10, Font.NORMAL, BaseColor.GRAY);
Connection conn4 = null;
PreparedStatement pst4 = null;
String sql4 = null;
Connection conn0 = null;
PreparedStatement pst0 = null;
String sql0 = null;
try{
PdfWriter writer = PdfWriter.getInstance(doc, output);
doc.addAuthor("betterThanZero");
doc.addCreationDate();
doc.addProducer();
doc.addCreator("MMG");
doc.addTitle("DM-01");
doc.setPageSize(PageSize.A4);
doc.setMargins(65, 50, 70, 100);
doc.open();
PdfContentByte contentByte = writer.getDirectContent();
String p_ides=request.getParameter("p_ides");
String p_diofficer=request.getParameter("p_diofficer");
float[] columnWidths4 = {10f, 30f, 60f};
//create PDF table with the given widths
PdfPTable table4 = new PdfPTable(columnWidths4);
// set table width a percentage of the page width
table4.setWidthPercentage(100f);
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn4 = DriverManager.getConnection(dbURL, dbUser, dbPass);
sql4="select mmg_no,i_des,tg_dir " +
"from dm_011 where i_des=? and di_officer=?";
pst4 = conn4.prepareStatement(sql4);
pst4.setString(1, p_ides);
pst4.setString(2, p_diofficer);
ResultSet rs4 = pst4.executeQuery();
while(rs4.next()){
PdfPCell cell9 = new PdfPCell(new Phrase("1", bf12));
cell9.setRowspan(2);
table4.addCell(cell9);
PdfPCell cell10 = new PdfPCell(new Phrase("a) MMG Demand Control No:\n[to be entered by MMG only]", bf12));
table4.addCell(cell10);
PdfPCell cell11 = new PdfPCell(new Phrase(rs4.getString("mmg_no"), bf12));
table4.addCell(cell11);
PdfPCell cell12 = new PdfPCell(new Phrase("b) Brief description of\nStores/Services:\n[Title of File to be given by\nDemanding Officer]", bf12));
table4.addCell(cell12);
PdfPCell cell13 = new PdfPCell(new Phrase(rs4.getString("i_des"), bf12));
table4.addCell(cell13);
PdfPCell cell14 = new PdfPCell(new Phrase("2", bf12));
table4.addCell(cell14);
PdfPCell cell15 = new PdfPCell(new Phrase("a) Tech Dir / Group:", bf12));
table4.addCell(cell15);
PdfPCell cell16 = new PdfPCell(new Phrase(rs4.getString("tg_dir"), bf12));
table4.addCell(cell16);
}
rs4.close();
pst4.close();
pst4 = null;
conn4.close();
conn4 = null;
doc.add(table4);
doc.close();
int pageCount = writer.getPageNumber()-1;
writer.close();
String output1 = os.toString();
PdfReader reader = new PdfReader(output1);
//reset the output
os = response.getOutputStream();
output = new DataOutputStream(os);
doc = new Document();
writer = PdfWriter.getInstance(doc, output);
doc.open();
PdfStamper stamper = new PdfStamper(reader, os);
for (int i = 1; i <= pageCount; i++)
{
contentByte = stamper.getOverContent(i);
//header
float[] columnWidths9 = {10f, 10f};
PdfPTable table9 = new PdfPTable(columnWidths9);
table9.setHorizontalAlignment(Element.ALIGN_RIGHT);
table9.setWidthPercentage(160 / 5.23f);
PdfPCell cell127 = new PdfPCell(new Phrase(" DM-01 ", f));
cell127.setVerticalAlignment(Element.ALIGN_CENTER);
cell127.setHorizontalAlignment(Element.ALIGN_CENTER);
table9.addCell(cell127);
PdfPCell cell128 = new PdfPCell(new Phrase(String.format("Page "+ i + " of " + pageCount), f));
cell128.setVerticalAlignment(Element.ALIGN_CENTER);
cell128.setHorizontalAlignment(Element.ALIGN_CENTER);
table9.addCell(cell128);
doc.add(table9);
//footer
Connection conn0 = null;
PreparedStatement pst0 = null;
String sql0 = null;
float[] columnWidths0 = {70f, 30f};
PdfPTable table0 = new PdfPTable(columnWidths0);
table0.setWidthPercentage(100f);
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn0 = DriverManager.getConnection(dbURL, dbUser, dbPass);
sql0="select i_des,di_officer " +
"from dm_011 where i_des=? and di_officer=?";
pst0 = conn0.prepareStatement(sql0);
pst0.setString(1, p_ides);
pst0.setString(2, p_diofficer);
ResultSet rs0 = pst0.executeQuery();
while(rs0.next()){
PdfPCell cell48 = new PdfPCell(new Phrase("Demand for " + rs0.getString("i_des"), bf12));
cell48.setRowspan(2);
table0.addCell(cell48);
PdfPCell cell49 = new PdfPCell(new Phrase(Chunk.NEWLINE));
cell49.setPaddingBottom(15);
cell49.setPaddingTop(15);
table0.addCell(cell49);
PdfPCell cell50 = new PdfPCell(new Phrase("Sign of Demanding Officer\n(" + rs0.getString("di_officer") + ")", bf12));
table0.addCell(cell50);
}
rs0.close();
pst0.close();
pst0 = null;
conn0.close();
conn0 = null;
PdfPTable outertable = new PdfPTable(1);
outertable.setWidthPercentage(100f);
PdfPCell cellO1 = new PdfPCell();
cellO1.setMinimumHeight(doc.getPageSize().getHeight() -
(170f + table9.getTotalHeight()));
cellO1.setVerticalAlignment(Element.ALIGN_BOTTOM);
cellO1.setBorderColor(BaseColor.WHITE);
cellO1.addElement(table0);
outertable1.addCell(cellO1);
doc.add(outertable);
}
stamper.close();
doc.close();
}catch(DocumentException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
The above code gives me the below error:
java.io.IOException: org.apache.catalina.connector.CoyoteOutputStream#10e18ba not found as file or resource.
at com.itextpdf.text.io.RandomAccessSourceFactory.createByReadingToMemory(RandomAccessSourceFactory.java:263)
at com.itextpdf.text.io.RandomAccessSourceFactory.createBestSource(RandomAccessSourceFactory.java:173)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:219)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:207)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:197)
at servlet_for_demand.formPart11PDF.doGet(formPart11PDF.java:737)
at servlet_for_demand.formPart11PDF.doPost(formPart11PDF.java:810)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Here I am attaching my database table creation code for developer to make solution easy.
create database test;
use test;
create table dm_011(mmg_no varchar(40),i_des varchar(40),tg_dir varchar(40));
insert into dm_011 values ('1','abcd','abcd1');
insert into dm_011 values ('2','efgh','efgh1');
Please help me, I can't find any solution.

Related

Working with application in Java using maps

I have trouble with my Java application. I'm writing a program that connects to public transport API and perform some operations, which includes showing map of Warsaw with bus stops. I want to add an EventHandler function that allows to tap on a bus stop on the map, which will result in showing a box with some informations about this bus stop. How can I do such a thing?
My application so far:
Main.java:
package gui;
import api.Api;
import com.gluonhq.charm.down.ServiceFactory;
import com.gluonhq.charm.down.Services;
import com.gluonhq.charm.down.plugins.StorageService;
import com.gluonhq.maps.MapPoint;
import com.gluonhq.maps.MapView;
import com.gluonhq.maps.demo.PoiLayer;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.io.File;
import java.util.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Main extends Application{
private ContentType currentContent = ContentType.SCHEDULE;
private HashMap<ContentType, Pane> contentPaneMap;
private HBox buttonBox;
private Stage stage;
private Theme theme;
private final int height = 500;
private final int width = 800;
private final ToggleGroup menuButtonToggle = new ToggleGroup();
private String selectedStopId;
#Override
public void start(Stage primaryStage) {
this.stage = primaryStage;
theme = Theme.DARK;
buttonBox = new HBox();
buttonBox.getChildren().addAll(getMenuButtons());
initContentPanes();
getContentPaneAndResetStage();
primaryStage.show();
}
private void getContentPaneAndResetStage(){
Pane contentPane = contentPaneMap.get(currentContent);
VBox rootPane = new VBox();
rootPane.getChildren().addAll(buttonBox, contentPane);
Scene scene = new Scene(rootPane, width, height);
scene.getStylesheets().add(theme.cssFile);
stage.setScene(scene);
}
private List<ToggleButton> getMenuButtons(){
List<ToggleButton> buttonList = new ArrayList<>();
for(ContentType contentType:ContentType.values()){
ToggleButton button = new ToggleButton(contentType.buttonText);
button.setPrefWidth((double) width/4);
button.setOnAction(e -> {
Main.this.currentContent = contentType;
getContentPaneAndResetStage();
});
buttonList.add(button);
button.setToggleGroup(Main.this.menuButtonToggle);
}
return buttonList;
}
private void initContentPanes(){
contentPaneMap = new HashMap<>();
Api.saveLocalisationToCache();
contentPaneMap.put(ContentType.MAP, getMapPane());
contentPaneMap.put(ContentType.SCHEDULE, getSchedulePane());
contentPaneMap.put(ContentType.ROUTE, getRoutePane());
contentPaneMap.put(ContentType.SETTINGS, getSettingsPane());
}
private Pane getSchedulePane(){
VBox schedulePane = new VBox();
Label stopNameLabel = new Label("Nazwa przystanku: ");
stopNameLabel.setPadding(new Insets(5));
TextField stopName = new TextField();
stopName.setOnAction(e -> {
List<String> stopId = Api.getId(stopName.getText());
selectedStopId = null;
schedulePane.getChildren().remove(1);
schedulePane.getChildren().add(getContentForSchedulePane(stopId, stopName.getText()));
});
schedulePane.getChildren().add(new HBox(stopNameLabel, stopName));
if (selectedStopId == null) schedulePane.getChildren().add(new Pane(new Label("Nie znaleziono przystanku")));
else schedulePane.getChildren().add(new Label(selectedStopId));
return schedulePane;
}
private Pane getContentForSchedulePane(List<String> stopId, String stopName){
if (stopId.size() == 0) return new Pane(new Label("Nie znaleziono przystanku"));
if (stopId.size() == 1) {
String stop1id = stopId.get(0);
Label stopNameLabel = new Label("Przystanek " + stopName.toUpperCase() + " (id " + stop1id + ")");
stopNameLabel.setPadding(new Insets(5));
VBox newContentPane = new VBox(stopNameLabel);
ChoiceBox<String> busStopNr = new ChoiceBox<>(
FXCollections.observableArrayList(List.of(new String[]{"01", "02"})));
busStopNr.setValue("01");
ChoiceBox<String> lineChoice = new ChoiceBox<>(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue())));
Label times = new Label();
lineChoice.setOnAction(
e -> times.setText(Api.getTimes(stop1id, busStopNr.getValue(), lineChoice.getValue()).toString()));
busStopNr.setOnAction(
e -> lineChoice.setItems(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue()))));
newContentPane.getChildren().addAll(
new HBox(new Label("Nr słupka: "), busStopNr),
new HBox(new Label("Nr linii: "), lineChoice),
times);
return newContentPane;
}
GridPane newButtonPane = new GridPane();
int i = 1; int j = 0;
for (String id:stopId) {
Button b = new Button(id);
b.setOnAction(event -> {
selectedStopId = b.getText();
contentPaneMap.get(ContentType.SCHEDULE).getChildren().remove(1);
contentPaneMap.get(ContentType.SCHEDULE).getChildren()
.add(getContentForSchedulePane(Collections.singletonList(b.getText()), stopName));
});
((GridPane) newButtonPane).add(b, i, j);
i = (i+1)%4+1; j = i==1?j+1:j;
}
return newButtonPane;
}
private Pane getRoutePane(){return new VBox(new Circle(20, Color.BLUE));}
private Pane getMapPane(){
MapView mapView = new MapView();
PoiLayer poiLayer = new PoiLayer();
List<Map<String, String>> pointList = Api.getLocalization();
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
poiLayer.addPoint(point, new Circle(3, Color.RED));
}
mapView.setCenter(new MapPoint(52.230926, 21.006701));
mapView.setZoom(13);
mapView.addLayer(poiLayer);
return new StackPane(mapView);
}
public void getInfo(){
}
private Pane getSettingsPane(){
GridPane settingsPane = new GridPane();
ChoiceBox<Theme> themeChoiceBox = new ChoiceBox<>(FXCollections.observableArrayList(Theme.values()));
themeChoiceBox.setOnAction(e -> {
Main.this.theme = themeChoiceBox.getValue();
getContentPaneAndResetStage();
});
Label themeLabel = new Label("Motyw: ");
themeLabel.setPadding(new Insets(5));
settingsPane.add(themeLabel, 1, 1);
settingsPane.add(themeChoiceBox, 2, 1);
settingsPane.setHgap(10);
settingsPane.setVgap(10);
settingsPane.setGridLinesVisible(false);
return settingsPane;
}
#Override
public void init() {
System.setProperty("javafx.platform", "Desktop");
System.setProperty("http.agent", "Gluon Mobile/1.0.1");
StorageService storageService = new StorageService() {
#Override
public Optional<File> getPrivateStorage() {
return Optional.of(new File(System.getProperty("user.home")));
}
#Override
public Optional<File> getPublicStorage(String s) {
return getPrivateStorage();
}
#Override
public boolean isExternalStorageWritable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canWrite();
}
#Override
public boolean isExternalStorageReadable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canRead();
}
};
ServiceFactory<StorageService> storageServiceServiceFactory = new ServiceFactory<>() {
#Override
public Class<StorageService> getServiceType() {
return StorageService.class;
}
#Override
public Optional<StorageService> getInstance() {
return Optional.of(storageService);
}
};
Services.registerServiceFactory(storageServiceServiceFactory);
}
}
api.java:
package api;
import javafx.application.Platform;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Api {
private static final String baseUrl = "https://api.um.warszawa.pl/api/action/";
private static final String apikey = "95904037-5fdc-48d5-bd7f-c9f8d0b28947";
private static final String pathToLocalisationCache = "./.cache/stop-localisation.json";
private static HttpURLConnection getConnection(String urlString){
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
assert url != null;
connection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
//Współrzędne przystanków
public static List<Map<String,String>> getLocalization() {
File cacheFile = new File(pathToLocalisationCache);
String data;
if(!cacheFile.exists()){
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
data = Api.readData(connection);
} else{
data = readLocalisationFromCache();
}
List<Map<String,String>> list = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
Map<String, String> map = new HashMap<>();
for(int i = 0; i < arr1.length();i++){
String value = arr1.getJSONObject(i).getString("value");
String key = arr1.getJSONObject(i).getString("key");
map.put(key, value);
}
list.add(map);
}
return list;
}
public static void saveLocalisationToCache(){
File file = new File(pathToLocalisationCache);
if (file.exists()) return;
try{
boolean fileCreated = true;
if (!file.getParentFile().exists()) fileCreated = file.getParentFile().mkdir();
if (!fileCreated) throw new IOException("Unable to create cache directory");
fileCreated = file.createNewFile();
if (!fileCreated) throw new IOException("Unable to create file");
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = setParameters(getConnection(url));
InputStreamReader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()), StandardCharsets.UTF_8.newDecoder());
OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), StandardCharsets.UTF_8.newEncoder());
in.transferTo(out);
in.close(); out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String readLocalisationFromCache(){
try{
BufferedReader reader = new BufferedReader(new FileReader(pathToLocalisationCache));
StringBuilder dataSB = new StringBuilder();
reader.lines().forEach(dataSB::append);
reader.close();
return dataSB.toString();
} catch (IOException e){e.printStackTrace();}
return null;
}
//id przystanku po nazwie
public static List<String> getId(String n) {
StringBuilder name = new StringBuilder();
try {
String[] testStrings = {n};
for (String s : testStrings) {
String encodedString = URLEncoder.encode(s, StandardCharsets.UTF_8);
name.append(encodedString);
}
} catch(Exception e){e.printStackTrace();}
String url = baseUrl+"dbtimetable_get?id=b27f4c17-5c50-4a5b-89dd-236b282bc499&name="+name+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
// Zwraca liste linii dla konkretnego przystanku i nr slupka
public static List<String> getLines(String idPrzystanku, String nrSlupka) {
String url = baseUrl+"dbtimetable_get?id=88cd555f-6f31-43ca-9de4-66c479ad5942&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
//Zwraca listę czas dla danego przystanku i linii
public static List<String> getTimes(String idPrzystanku, String nrSlupka, String line) {
String url = baseUrl+"dbtimetable_get?id=e923fa0e-d96c-43f9-ae6e-60518c9f3238&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&line="+line+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
List<String> times = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
JSONObject obj2 = arr1.getJSONObject(5);
times.add(obj2.getString("value"));
}
return times;
}
//Odczytuje dane
public static String readData(HttpURLConnection connection) {
InputStream inStream;
try {
inStream = new BufferedInputStream(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
Scanner in = new Scanner(inStream, StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNext()) {
sb.append(in.next());
}
return sb.toString();
}
//Ustala parametry połączenia
public static HttpURLConnection setParameters(HttpURLConnection
connection) {
try {
connection.setRequestMethod("GET");
connection.setDoInput(true);
} catch (ProtocolException e) {
e.printStackTrace();
}
connection.setRequestProperty("Authorization", "Token " + apikey);
try {
if (connection.getResponseCode() != 200) {
System.out.println("Response code: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
Platform.exit(); // ze względu na javafx
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
I have no idea how to do it and I will be very grateful if someone will help me.
Based on my work experience on map libraries with JavaFX, I can share an approach you can take here. You can simply add a Mouse click event handler on the MapView and in that event you can catch the coordinates/Point where the user clicks on the screen. Then you can compare that point clicked by the user with one of the location Map points you want your user to click and see if it matches (by checking a distance between the user click position and the map coordinate of the bus stop). I have applied this approach in a different map library but similar can be applied here with some tweaks and adjustments.
List<Map<String, String>> pointList = Api.getLocalization();
mapView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
Point2D clickedMapCoordinates = mapView.screenToLocal(new Point2D(mouseEvent.getX(), mouseEvent.getY()));
for (Map<String, String> stop: pointList){
MapPoint stopPoint = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
Point2D mapStopPoint = new Point2D(stopPoint.getLongitude(), stopPoint.getLatitude());
// if user clicked on map near the position(lat,lng) of a stop
// then trigger the logic, you can change the distance threshold value according to your need
if(mapStopPoint.distance(clickedMapCoordinates) < 0.0001)
{
// perform your logic here about the stop point point...
}
}
}
});
Another approach which I suppose you can take is put a click event handler on the Circle object for the bus stop point and then check if the user's clicked circle matches the coordinates of a bus stop point.
Circle circle = new Circle(3, Color.RED);
circle.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getSource() instanceof Circle)
{
Circle clickedCircle = (Circle) mouseEvent.getSource();
Point2D clickedPoint = mapView.screenToLocal(clickedCircle.getCenterX(), clickedCircle.getCenterY())
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
if(clickedPoint.getX() == point.getLongitude() && clickedPoint.getY() == point.getLatitude())
{
// this is the clicked map point (bus stop point)
// perform your logic here
}
}
}
}
});
If the second approach doesn't work, try debugging and checking the clicked point and bus stop point coordinates values and adjust them. Hope this helps you in some way.

Are BinaryFormatter Serialization dotnet core and framework compatible?

I have 2 programs, one written in .Net Framework 4.7.x and another app that is dot net core 2.1.
Program 1, written in .Net Framework. takes a Dataset and using BinaryFormatter writes it to a database field as a byte[].
Program 2, written in dot net core, then takes that record and attempts to Deserialize the field using BinaryFormatter. I'm getting an exception "ArgumentException: Type 'System.Byte' is not deserializable."
Program 1
static void Main(string[] args)
{
var connectionString = ConfigurationManager.ConnectionStrings["CDPMetadataModelContext"].ConnectionString;
byte[] binaryFormattedDs;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var da = new SqlDataAdapter("Select * from Code_Job_Status", connection))
{
var ds = new DataSet();
da.Fill(ds);
binaryFormattedDs = SerializeBinaryDataContract(ds);
}
string query = "INSERT INTO dbo.Result_Cache (Result_Binary_Data, Run_DateTime) output inserted.Result_Cache_ID VALUES";
string insertQuery = "(#binaryValue, getdate())";
using (SqlCommand cmd = new SqlCommand(query + insertQuery, connection))
{
cmd.Parameters.AddWithValue("#binaryValue", SqlDbType.VarBinary).Value = binaryFormattedDs;
var newId = (int)cmd.ExecuteScalar();
Console.WriteLine("New Id= "+ newId);
Debug.WriteLine("New Id= " + newId);
}
connection.Close();
}
Console.ReadKey();
var ds2 = DeSerialize<DataSet>(binaryFormattedDs);
Console.WriteLine("Row Count=" + ds2.Tables[0].Rows.Count);
Console.ReadKey();
}
public static T DeSerialize<T>(byte[] bytes)
{
var serializer = new BinaryFormatter();
using (var ms = new MemoryStream())
{
ms.Write(bytes, 0, bytes.Length);
ms.Seek(0, SeekOrigin.Begin);
return (T)serializer.Deserialize(ms);
}
}
public static byte[] SerializeBinaryDataContract(DataSet dataSet)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
byte[] buffer;
using (MemoryStream memoryStream = new MemoryStream())
{
dataSet.RemotingFormat = SerializationFormat.Binary;
binaryFormatter.Serialize((Stream)memoryStream, (object)dataSet);
buffer = new byte[memoryStream.Length];
memoryStream.Seek(0L, SeekOrigin.Begin);
memoryStream.Read(buffer, 0, buffer.Length);
}
return buffer;
}
Program 2
static void Main(string[] args)
{
Console.WriteLine("Result_Cache_ID:");
var reportIds = Console.ReadLine();
if (int.TryParse(reportIds, out var resultCacheId))
{
GetDS(resultCacheId);
}
Console.ReadKey();
}
private static void GetDS(int resultCacheId)
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var da = new SqlDataAdapter("Select * from Result_Cache where Result_Cache_ID="+ resultCacheId, connection))
{
var ds = new DataSet();
da.Fill(ds);
var binaryFormattedDs =(byte[]) ds.Tables[0].Rows[0]["Result_Binary_Data"];
var ds2 = DeSerialize<DataSet>(binaryFormattedDs);
Console.WriteLine("Row Count=" + ds2.Tables[0].Rows.Count);
}
}
}
public static T DeSerialize<T>(byte[] bytes)
{
var serializer = new BinaryFormatter();
using (var ms = new MemoryStream())
{
ms.Write(bytes, 0, bytes.Length);
ms.Seek(0, SeekOrigin.Begin);
return (T)serializer.Deserialize(ms);
}
}
am I doing something wrong?

AES with GUI not working

I am developing a AES-128 bit symmetric key encryptor in JavaFX. Here is my doubt: The below attached class encrypt method is called when a person clicks on encrypt button. But when someone tries to decrypt the file using the given method it doesn't actually decrypt. It gives a file that's still encrypted.
The same thing when I performed for a console based program it worked flawlessly.
GUI class (Excerpt of the project which don't work !)
package application;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryption {
private final File toBeUsed;
private final String password;
public AESEncryption(String passkey, File given){
this.password = passkey;
this.toBeUsed = given;
}
public void encrypt(boolean toBeLocal){
Service<Void> encryption = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>(){
#Override
protected Void call() throws Exception {
if(toBeLocal) this.startEncryption();
this.success();
return null;
}
private void success() {
Platform.runLater(new Runnable() {
#Override
public void run() {
EncryptionSuccessController controller = (EncryptionSuccessController)new OfflineWindow("/fxml/encryption_success.fxml", "Success").getLoader().getController();
controller.setPath(toBeUsed.getAbsolutePath()+".enc");
}
});
}
private void startEncryption() throws Exception{
SecureRandom randomizer = new SecureRandom();
byte[] salt = new byte[16];
randomizer.nextBytes(salt);
byte key[] = (password+salt).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
SecretKeySpec pass = new SecretKeySpec(key,"AES");
Cipher encrypt = Cipher.getInstance("AES");
encrypt.init(Cipher.ENCRYPT_MODE, pass);
FileOutputStream fos = new FileOutputStream(toBeUsed.getAbsolutePath() +".enc");
try(FileInputStream fis =new FileInputStream(toBeUsed.getAbsolutePath())){
try(CipherOutputStream cout=new CipherOutputStream(fos, encrypt)){
copy(fis,cout);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void copy(InputStream is,OutputStream os) throws Exception{
byte buf[] = new byte[4096];
int read = 0;
while((read = is.read(buf)) != -1) os.write(buf,0,read);
}
};
};
};
encryption.start();
}
public void decrypt(boolean isLocallyEncrypted){
Service<Void> decryption = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>(){
#Override
protected Void call() throws Exception {
if(isLocallyEncrypted) this.startDecryption();
this.message();
return null;
}
private void message() {
Platform.runLater(new Runnable(){
#Override
public void run() {
DecryptionCompleteController controller = (DecryptionCompleteController)new OfflineWindow("/fxml/decryption_over.fxml", "Completed").getLoader().getController();
controller.setPath(toBeUsed.getAbsolutePath());
}
});
}
private void startDecryption() throws Exception{
SecureRandom randomizer = new SecureRandom();
byte[] salt = new byte[16];
randomizer.nextBytes(salt);
byte key[] = (password+salt).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
SecretKeySpec pass = new SecretKeySpec(key,"AES");
Cipher decrypt = Cipher.getInstance("AES");
decrypt.init(Cipher.DECRYPT_MODE, pass);
FileInputStream fis = new FileInputStream(toBeUsed.getAbsolutePath());
try(CipherInputStream cin=new CipherInputStream(fis, decrypt)){
try(FileOutputStream fos =new FileOutputStream(toBeUsed.getAbsolutePath().substring(0,toBeUsed.getAbsolutePath().lastIndexOf(".")))){
copy(cin,fos);
}
}
}
private void copy(InputStream is,OutputStream os) throws Exception{
byte buf[] = new byte[4096];
int read = 0;
while((read = is.read(buf)) != -1) os.write(buf,0,read);
}
};
};
};
decryption.start();
}
}
Console based code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private String algo;
private String path;
private String password;
public AES(String algo,String path, String password) {
this.algo = algo; //setting algo
this.path = path;//setting file path
this.password = password;
}
public void encrypt() throws Exception{
SecureRandom padding = new SecureRandom();
byte[] salt = new byte[16];
padding.nextBytes(salt);
//generating key
byte k[] = (password+salt).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
k = sha.digest(k);
k = Arrays.copyOf(k, 16);
for(int i=0;i<k.length;i++) System.out.print(k[i]);
SecretKeySpec key = new SecretKeySpec(k,algo);
//creating and initialising cipher and cipher streams
Cipher encrypt = Cipher.getInstance(algo);
encrypt.init(Cipher.ENCRYPT_MODE, key);
//opening streams
FileOutputStream fos =new FileOutputStream(path+".enc");
try(FileInputStream fis =new FileInputStream(path)){
try(CipherOutputStream cout=new CipherOutputStream(fos, encrypt)){
copy(fis,cout);
}
}
}
public void decrypt() throws Exception{
SecureRandom padding = new SecureRandom();
byte[] salt = new byte[16];
padding.nextBytes(salt);
//generating same key
byte k[] = (password+salt).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
k = sha.digest(k);
k = Arrays.copyOf(k, 16);
for(int i=0;i<k.length;i++) System.out.print(k[i]);
SecretKeySpec key = new SecretKeySpec(k,algo);
//creating and initialising cipher and cipher streams
Cipher decrypt = Cipher.getInstance(algo);
decrypt.init(Cipher.DECRYPT_MODE, key);
//opening streams
FileInputStream fis = new FileInputStream(path);
try(CipherInputStream cin=new CipherInputStream(fis, decrypt)){
try(FileOutputStream fos =new FileOutputStream(path.substring(0,path.lastIndexOf(".")))){
copy(cin,fos);
}
}
}
private void copy(InputStream is,OutputStream os) throws Exception{
byte buf[] = new byte[4096]; //4K buffer set
int read = 0;
while((read = is.read(buf)) != -1) //reading
os.write(buf,0,read); //writing
}
}
As always expecting a best answer from Stack Overflow's intelligent community.
It looks like the salt value in your GUI application is different between encrypt and decrypt. I'm not sure why it would be the same in your console application, but to get the same key using the method you're using, the salt should also be the same.
Your salt is random for both encryption and decryption; this will never work as the key is different each time (which you should have noted).
You cannot just concatenate a byte array to a string. Implicitly a toString() method is called, which just shows some information about the reference.
public class AES_GUI {
private String algo;
private String path;
private String password;
public AES_GUI(String algo, String path, String password) {
this.algo = algo; // setting algo
this.path = path;// setting file path
this.password = password;
}
public void encrypt() throws Exception {
SecureRandom padding = new SecureRandom();
byte[] salt = new byte[16];
padding.nextBytes(salt);
// generating key
byte k[] = password.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
sha.update(salt);
k = sha.digest(k);
k = Arrays.copyOf(k, 16);
for (int i = 0; i < k.length; i++)
System.out.print(k[i]);
System.out.println();
SecretKeySpec key = new SecretKeySpec(k, algo);
// creating and initialising cipher and cipher streams
Cipher encrypt = Cipher.getInstance(algo);
encrypt.init(Cipher.ENCRYPT_MODE, key);
// opening streams
FileOutputStream fos = new FileOutputStream(path + ".enc");
fos.write(salt);
try (FileInputStream fis = new FileInputStream(path)) {
try (CipherOutputStream cout = new CipherOutputStream(fos, encrypt)) {
copy(fis, cout);
}
}
}
public void decrypt() throws Exception {
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(path + ".enc"), 16);
byte[] salt = new byte[16];
int read = fis.read(salt);
if (read != 16) {
throw new IllegalStateException();
}
// generating same key
byte k[] = password.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
sha.update(salt);
k = sha.digest(k);
k = Arrays.copyOf(k, 16);
for (int i = 0; i < k.length; i++)
System.out.print(k[i]);
System.out.println();
SecretKeySpec key = new SecretKeySpec(k, algo);
// creating and initialising cipher and cipher streams
Cipher decrypt = Cipher.getInstance(algo);
decrypt.init(Cipher.DECRYPT_MODE, key);
// opening streams
try (CipherInputStream cin = new CipherInputStream(fis, decrypt)) {
try (FileOutputStream fos = new FileOutputStream(path + ".dec")) {
copy(cin, fos);
}
}
}
private void copy(InputStream is, OutputStream os) throws Exception {
byte buf[] = new byte[4096]; // 4K buffer set
int read = 0;
while ((read = is.read(buf)) != -1)
// reading
os.write(buf, 0, read); // writing
}
}
Note that this code is not secure. You should try and use PBKDF2 for key derivation from a password and use a different mode of operation than ECB (which is the default for the SUN provider of Oracle. Also note that I slightly altered the code for testing purposes.

Add background watermark logo to PDF file

I have rendered my aspx page to pdf successfully using ITextSharp.
Now i want to add watermark logo in background off PDF file please help me out i have been stuck into this.
Following is my code for export to pdf
private void ShowPdf(string s)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + s);
Response.ContentType = "application/pdf";
Response.WriteFile(s);
Response.Flush();
Response.Clear();
}
public void PrepareControlForPDF()
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
divApplicantDetails.RenderControl(myWriter);
myWriter.Flush();
// myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
//CreatePDFDocument(strmRdr);
//strmRdr.Dispose();
///mem.Dispose();
CreatePDFDocument(pageContent);
//writer.Write(pageContent);
}
public void CreatePDFDocument(string strHtml)
{
string filename = ""+System.DateTime.Now.Day+"AppLetter.pdf";
// if (System.IO.File.Exists(Server.MapPath("../Pdf") + "/" + filename))
// {
// System.IO.File.Delete(Server.MapPath("../Pdf") + "/" + filename);
// }
string strFileName = Server.MapPath("../Pdf") + "/" + filename;
Document document = new Document();
try
{
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
MemoryStream ms = new MemoryStream();
ms.Write(System.Text.Encoding.ASCII.GetBytes(strHtml), 0, System.Text.Encoding.ASCII.GetBytes(strHtml).Length);
//ms.Position = 0;
StreamReader sr = new StreamReader(new MemoryStream(new System.Text.ASCIIEncoding().GetBytes(strHtml)));
sr.BaseStream.Position = 0;
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
}
finally
{
document.Close();
}
}
I think you can achieve by creating a new class and implementing the IPdfPageEvent interface... refer here

Create Jtextfield based on array size

I'm new to java and we were ask to make a program that will create multiple Jtextfields based on the size of my array, i tried this code but nothing displays in the JOption window
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class try3 {
public static void main(String[] args) throws IOException{
String maindish = "Main.txt";
String mainprice = "mainprice.txt";
FileReader menu1 = new FileReader(maindish);BufferedReader Menu1 = new BufferedReader(menu1);
FileReader price1 = new FileReader(mainprice);BufferedReader Price1 = new BufferedReader(price1);
String menu = null;
ArrayList MENU = new ArrayList();
for (int a = 0; (menu = Menu1.readLine()) != null; a++ )
MENU.add(menu);
Object[] arr = new Object[MENU.size()];
MENU.toArray(arr);
int control = arr.length;
JLabel[] label = new JLabel[arr.length];
JTextField[] text = new JTextField[arr.length];
JPanel panel = new JPanel(new BorderLayout());
for (int a = 0; a >= control; a++){
label[a] = new JLabel(arr[a].toString());
text[a] = new JTextField("Quantity");
panel.add(label[a],BorderLayout.WEST);
panel.add(text[a],BorderLayout.CENTER);}
JOptionPane.showConfirmDialog(null, panel, "Login", JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
}
}

Resources