file_id
stringlengths
4
10
content
stringlengths
91
42.8k
repo
stringlengths
7
108
path
stringlengths
7
251
token_length
int64
34
8.19k
original_comment
stringlengths
11
11.5k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
34
42.8k
212331_9
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad<SUF>*/ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_10
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet<SUF>*/ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_11
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet<SUF>*/ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_12
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt<SUF>*/ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_13
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt<SUF>*/ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_14
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt<SUF>*/ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_15
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt<SUF>*/ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_16
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt<SUF>*/ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_17
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt<SUF>*/ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_18
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze functie maakt een nieuw input object aan * @return Java2DInput */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt<SUF>*/ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212331_19
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */ @Override protected Sound CreateSound() { return new Java2DSound(); } }
JurgenVanpeteghem/Space-Invaders
Space_Invaders/src/Java2D/Java2DFactory.java
2,410
/** * Deze functie maakt een nieuw sound object aan. * @return Java2DSound */
block_comment
nl
package Java2D; import be.uantwerpen.fti.ei.space.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; public class Java2DFactory extends A_fact { public int screenWidth; public int screenHeight; public double gameWidth; public double gameHeight; public double scaleX; public double scaleY; private final JFrame frame; private final JPanel panel; private final JLabel statusbar; private BufferedImage g2dimage; private Graphics2D g2d; private BufferedImage backgroundImg; private BufferedImage gameOverImg; private BufferedImage youWinImg; private double size; /** * Deze functie maakt een nieuw JFrame en JPanel aan en voegt een statusbar toe. * @throws IOException */ public Java2DFactory() throws IOException{ readconfig(); frame = new JFrame(); statusbar = new JLabel("0"); panel = new JPanel(true) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } }; frame.setFocusable(true); frame.add(panel); frame.add(statusbar,BorderLayout.NORTH); frame.setTitle("Space Invadors"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLocationRelativeTo(null); frame.setVisible(true); } public Graphics2D getG2d() { return g2d; } public JFrame getFrame() { return frame; } public double getSize() { return size; } /** * Deze functie leest een config bestand in met scherm breedte en hoogte. * @throws IOException */ private void readconfig() throws IOException { FileInputStream fileInputStream = new FileInputStream("Space_Invaders/src/config.properties"); Properties prop = new Properties(); prop.load(fileInputStream); this.screenHeight = Integer.parseInt(prop.getProperty("ScreenHeight")); this.screenWidth = Integer.parseInt(prop.getProperty("ScreenWidth")); } /** * Deze functie maakt een schalingsfactor voor x en voor y aan. Deze schaal drukt de verhouding van game afmetingen en de schermafmetingen uit. * @param gamewidth de breedte van het game veld * @param gameheight de hoogte van het game veld */ public void scaleScreen(double gamewidth, double gameheight){ gameWidth = gamewidth; gameHeight = gameheight; scaleX = screenWidth / gamewidth; scaleY = screenHeight / gameheight; } /** * Deze functie drukt een "game over afbeelding" af over heel het scherm. */ @Override protected void gameOver() { try{ gameOverImg = resizeImage(gameOverImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(gameOverImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * Deze functie drukt een "you win afbeelding" af over heel het scherm. */ @Override protected void youWin() { try{ youWinImg = resizeImage(youWinImg,frame.getWidth(), frame.getHeight()); } catch (Exception e){ System.out.println(Arrays.toString(e.getStackTrace())); } g2d.drawImage(youWinImg, 0, 0, null); statusbar.setText("press space key to continue"); } /** * deze functie hertekent het scherm. */ @Override public void render() { panel.repaint(); } /** * Deze funcite plaats een achtergrond op het speelveld. * @param g Graphics */ private void doDrawing(Graphics g) { Graphics2D graph2d = (Graphics2D) g; Toolkit.getDefaultToolkit().sync(); graph2d.drawImage(g2dimage, 0, 0, null); // copy buffered image graph2d.dispose(); if (g2d != null) g2d.drawImage(backgroundImg,0, 0, null); } /** * Met deze functie kan de grootte van een afbeelding worden aangepast. * @param originalImage de aan te passen afbeelding * @param targetWidth de gewenste breedte * @param targetHeight de gewenste hoogte * @return geeft de aangepaste afbeelding terug */ public BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){ Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT); BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); outputImage.getGraphics().drawImage(resultingImage, 0, 0, null); return outputImage; } /** * Deze functie laad de afbeeldingen voor de achtergrond, game over en you win in. * @throws IOException */ private void loadImages() throws IOException { backgroundImg = null; gameOverImg = null; youWinImg = null; backgroundImg = ImageIO.read(new File("Space_Invaders/src/recources/background.jpg")); gameOverImg = ImageIO.read(new File("Space_Invaders/src/recources/Game over.jpg")); youWinImg = ImageIO.read(new File("Space_Invaders/src/recources/you_win.png")); } /** * Deze functie zet de game dimensies op een bepaalde waarde en zet het veld op een bepaalde locatie op het scherm. * De achtergrond wordt over heel het veld getekend. * @param GameWidth game breedte * @param GameHeight game hoogte * @throws IOException */ @Override public void setGameDimensions(int GameWidth, int GameHeight) throws IOException { size = Math.min(screenWidth /GameWidth, screenHeight /GameHeight); System.out.println("size: "+size); frame.setLocation(50,50); frame.setSize(screenWidth, screenHeight); loadImages(); try { backgroundImg = resizeImage(backgroundImg, frame.getWidth(), frame.getHeight()); } catch(Exception e) { System.out.println(Arrays.toString(e.getStackTrace())); } g2dimage = new BufferedImage(frame.getWidth(), frame.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE); g2d = g2dimage.createGraphics(); g2d.drawImage(backgroundImg,0, 0, null); } /** * Deze functie zet de score en het aantal resterende levens in de statusbar. * @param score de huidige score * @param lives het resterende aantal levens */ @Override protected void ShowStatus(int score, int lives) { statusbar.setText("Score " + score + " lives " + lives); statusbar.setForeground(Color.DARK_GRAY); } /** * Deze funcite maakt een nieuw Java2Dplayership aan * @return Java2DPlayerShip * @throws IOException */ @Override protected Playership CreatePlayerschip() throws IOException { return new Java2DPlayership(this); } /** * Deze funcite maakt een nieuw Java2DEnemyShip aan * @return Java2DEnemyShip * @throws IOException */ @Override protected Enemyship CreateEnemyship() throws IOException { return new Java2DEnemyship(this); } /** * Deze functie maakt een nieuwe player bullet aan * @return Java2DBullet * @throws IOException */ @Override protected Bullet CreateBullet() throws IOException { return new Java2DBullet(this); } /** * Deze functie maakt een nieuwe enemy bullet aan * @return Java2DEnemyBullet * @throws IOException */ @Override protected Java2DEnemyBullet CreateEnemyBullet() throws IOException { return new Java2DEnemyBullet(this); } /** * Deze functie maakt een nieuwe positieve bonus aan * @return Java2DPBonus * @throws IOException */ @Override protected Java2DPBonus CreatePBonus() throws IOException { return new Java2DPBonus(this); } /** * Deze functie maakt een nieuwe negatieve bonus aan * @return Java2DNBonus * @throws IOException */ @Override protected Java2DNBonus CreateNBonus() throws IOException { return new Java2DNBonus(this); } /** * Deze functie maakt een nieuw input object aan * @return Java2DInput */ @Override protected Input CreateInput() { return new Java2DInput(this); } /** * Deze functie maakt<SUF>*/ @Override protected Sound CreateSound() { return new Java2DSound(); } }
212335_0
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
NiekSulter/Afvinkopdrachten
Afvinkopdracht_7/src/seqVis.java
1,801
/** * Class om de GUI te maken en figuren te tekenen. */
block_comment
nl
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de<SUF>*/ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
212335_1
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
NiekSulter/Afvinkopdrachten
Afvinkopdracht_7/src/seqVis.java
1,801
/** * Methode om de elementen aan te maken. */
block_comment
nl
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de<SUF>*/ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
212335_3
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
NiekSulter/Afvinkopdrachten
Afvinkopdracht_7/src/seqVis.java
1,801
//Knoppen en actionlisteners
line_comment
nl
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en<SUF> b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
212335_4
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
NiekSulter/Afvinkopdrachten
Afvinkopdracht_7/src/seqVis.java
1,801
//Toevoegen van elementen aan de panels
line_comment
nl
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van<SUF> p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
212335_5
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
NiekSulter/Afvinkopdrachten
Afvinkopdracht_7/src/seqVis.java
1,801
/** * Actionlisiner om de knoppen van functionaliteit te voorzien. */
block_comment
nl
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de<SUF>*/ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
212335_6
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
NiekSulter/Afvinkopdrachten
Afvinkopdracht_7/src/seqVis.java
1,801
/** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */
block_comment
nl
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de<SUF>*/ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
212335_7
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
NiekSulter/Afvinkopdrachten
Afvinkopdracht_7/src/seqVis.java
1,801
/** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */
block_comment
nl
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het<SUF>*/ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
212335_8
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
NiekSulter/Afvinkopdrachten
Afvinkopdracht_7/src/seqVis.java
1,801
/** * Functie om de kleuren aan een lijst toe te voegen om ze te verwerken. * Vervolgens worden de lijnen in de visualisatie getekend. */
block_comment
nl
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Class om de GUI te maken en figuren te tekenen. */ public class seqVis extends JFrame implements ActionListener { private JPanel p1, p2; private JLabel l1, l2, l3; private JButton b1, b2; private JTextField tf1, tf2; private JTextArea ta1; private ArrayList<Color> color; String total = ""; String header; readFile f1; public static void main(String[] args) { seqVis frame = new seqVis(); frame.setSize(1100, 400); frame.GUI(); frame.setVisible(true); frame.setTitle("SeqVis"); } /** * Methode om de elementen aan te maken. */ private void GUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); //Panels aanmaken p1 = new JPanel(); p1.setPreferredSize(new Dimension(1100, 250)); p2 = new JPanel(); p2.setPreferredSize(new Dimension(1000, 50)); //Labels aanmaken l1 = new JLabel("File:"); l2 = new JLabel("Sequence:"); l3 = new JLabel("Visualisatie:"); //Textfiels en area's tf1 = new JTextField(70); tf1.setEditable(false); ta1 = new JTextArea(10, 90); ta1.setPreferredSize(new Dimension(1100, 150)); //Knoppen en actionlisteners b1 = new JButton("search"); b1.addActionListener(this); b2 = new JButton("analyse"); b2.addActionListener(this); p2.setBackground(Color.WHITE); //Toevoegen van elementen aan de panels p1.add(l1); p1.add(tf1); p1.add(b1); p1.add(b2); p1.add(l2); p1.add(ta1); p1.add(l3); window.add(p1); window.add(p2); } /** * Actionlisiner om de knoppen van functionaliteit te voorzien. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == b2) { try { parseFile(f1.getFile()); makeObject(); } catch (NoValidSeq | IOException noValidSeq) { noValidSeq.printStackTrace(); } } else if (e.getSource() == b1) { final JFileChooser fw = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Fasta files (.fasta, .fa, .txt)", "fasta", "fa", "txt"); fw.setFileFilter(filter); int retval = fw.showOpenDialog(seqVis.this); if (retval == JFileChooser.APPROVE_OPTION) { f1 = new readFile(fw.getSelectedFile()); tf1.setText(f1.getFileName()); } } } /** * Methode om de opgegven file te parsen en een string te maken van de sequentie. * * @param file bestand dat ingelezen is in de readFile class * @throws IOException standaard input exception */ public void parseFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String rij = null; while ((rij = reader.readLine()) != null) { if (rij.startsWith(">")) { header = rij; ta1.append(rij + "\n"); } else { total += rij; ta1.append(rij + "\n"); } } } /** * Methode om het sequentie aan te maken * * @throws NoValidSeq custom exception als de sequentie onbekende letters bevat */ public void makeObject() throws NoValidSeq { if (total.matches("^[ACTG]+$")) { DNA object = new DNA(total, header); selectColor(object); } else if (total.matches("^[ACUG]+$")) { RNA object = new RNA(total, header); selectColor(object); } else if (total.matches("^[DERKHSTNQCUGPAVILMFYWX]+$")) { protein object = new protein(total, header); selectColor(object); } else { throw new NoValidSeq("Dit is geen geldige sequentie!"); } } /** * Functie om de<SUF>*/ public void selectColor(sequentie object) { char[] polar = {'S', 'T', 'C', 'Y', 'N', 'Q'}; char[] nonpolar = {'G', 'A', 'V', 'L', 'I', 'M', 'F', 'W', 'P'}; char[] neutral = {'D', 'E', 'R', 'K', 'H'}; char[] letters = total.toCharArray(); Graphics paper = p2.getGraphics(); int xpos = 0; for (char i : letters) { if (object instanceof DNA) { if (i == 'A' || i == 'T') { paper.setColor(DNA.Kleuren.AT.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (i == 'G' || i == 'C') { paper.setColor(DNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof RNA) { if (i == 'U' || i == 'A') { paper.setColor(RNA.Kleuren.AU.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(RNA.Kleuren.GC.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } else if (object instanceof protein) { if (Arrays.asList(polar).contains(i)) { paper.setColor(protein.Kleuren.polair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else if (Arrays.asList(nonpolar).contains(i)) { paper.setColor(protein.Kleuren.apolair.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } else { paper.setColor(protein.Kleuren.neutaal.getColor()); paper.drawLine(xpos, 1, xpos + 1, 50); } } xpos++; } } }
212346_1
/** * * @author Tom Naessens * [email protected] * 1ste Bachelor Informatica * Universiteit Gent * */ package elektrobank.Models.Simulator; import elektrobank.Controllers.Handlers.MouseHandler; import elektrobank.Controllers.Handlers.SimulateMouseHandler; import elektrobank.Controllers.TimerController; import elektrobank.Models.EdgeCircuitModel; import elektrobank.utils.PointNode; import java.awt.Point; import java.awt.geom.Line2D; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; import joldespice.circuit.simulator.CircuitSimulator; import joldespice.circuit.simulator.NumericalException; import joldespice.circuit.simulator.SimulatorFactory; import joldespice.components.Component; import joldespice.components.nonlinear.Switch; import joldespice.graph.EdgeContainer; import joldespice.graph.EdgeList; public class SimulatorModel extends EdgeCircuitModel { MouseHandler simulateHandler; SpinnerNumberModel sSHModel; SpinnerNumberModel sSTModel; CircuitSimulator circSim; Timer timer; static final double MAXTHICKNESS = 5; // Want we willen niet dat onze lijnen TE dik getekend worden! double maxCurrent; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale stroom bij te houden double maxVoltage; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale voltage bij te houden public SimulatorModel(SpinnerNumberModel sSHModel, SpinnerNumberModel sSTModel) { simulateHandler = new SimulateMouseHandler(this); this.sSHModel = sSHModel; this.sSTModel = sSTModel; timer = new Timer((Integer) sSHModel.getValue(), new TimerController(this)); circSim = SimulatorFactory.makeSimulator(circ); } public void initSim() { maxCurrent = 0; maxVoltage = 0; circSim = SimulatorFactory.makeSimulator(circ); circSim.init(); } public void resetSim() { maxCurrent = 0; maxVoltage = 0; circSim.reset(); timer.stop(); fireStateChanged(); } public void doStep() { try { circSim.setTimestep((Double) sSTModel.getValue()); circSim.proceed(); fireStateChanged(); } catch (NumericalException ex) { Logger.getLogger("jOldeSpice").log(Level.SEVERE, "Matrix is singular", ex); JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout opgetreden", JOptionPane.ERROR_MESSAGE); timer.stop(); } } public void changeSwitch(Point pt) { EdgeContainer tempSwitch = getNearestSwitch(pt); if (tempSwitch != null) { ((Switch) tempSwitch.getE()).setState(!((Switch) tempSwitch.getE()).getState()); } fireStateChanged(); } public void changeTimer() { if (timer.isRunning()) { timer.stop(); } else { timer.start(); } fireStateChanged(); } // Geeft de dichtstbijzijnde Edge terug, als er geen is gevonden geeft hij null terug public EdgeContainer<Component, PointNode> getNearestSwitch(Point pt) { EdgeContainer<Component, PointNode> nearestEdge = null; double shortest = Double.MAX_VALUE; double distanceToEdge; EdgeList<Component, PointNode> edges = getCirc().getEdgeList(); for (EdgeContainer<Component, PointNode> tempEdge : edges) { PointNode headNode = tempEdge.getHead(); PointNode tailNode = tempEdge.getTail(); distanceToEdge = new Line2D.Double(headNode.getLocation(), tailNode.getLocation()).ptSegDist(pt); if (tempEdge.getE().getClass().getSimpleName().equals("Switch") && distanceToEdge < shortest && distanceToEdge < 50) { shortest = distanceToEdge; nearestEdge = tempEdge; } } return nearestEdge; } public void setMaxCurrent(double current) { maxCurrent = current; } public double getMaxCurrent() { return maxCurrent; } public void setMaxVoltage(double voltage) { maxVoltage = voltage; } public double getMaxVoltage() { return maxVoltage; } public double getMaxThickness() { return MAXTHICKNESS; } public Timer getTimer() { return timer; } public MouseHandler getSimulateHandler() { return simulateHandler; } }
TomNaessens/UGent-stuff
Prog2--Project--Elektrobank/src/elektrobank/Models/Simulator/SimulatorModel.java
1,167
// Want we willen niet dat onze lijnen TE dik getekend worden!
line_comment
nl
/** * * @author Tom Naessens * [email protected] * 1ste Bachelor Informatica * Universiteit Gent * */ package elektrobank.Models.Simulator; import elektrobank.Controllers.Handlers.MouseHandler; import elektrobank.Controllers.Handlers.SimulateMouseHandler; import elektrobank.Controllers.TimerController; import elektrobank.Models.EdgeCircuitModel; import elektrobank.utils.PointNode; import java.awt.Point; import java.awt.geom.Line2D; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; import joldespice.circuit.simulator.CircuitSimulator; import joldespice.circuit.simulator.NumericalException; import joldespice.circuit.simulator.SimulatorFactory; import joldespice.components.Component; import joldespice.components.nonlinear.Switch; import joldespice.graph.EdgeContainer; import joldespice.graph.EdgeList; public class SimulatorModel extends EdgeCircuitModel { MouseHandler simulateHandler; SpinnerNumberModel sSHModel; SpinnerNumberModel sSTModel; CircuitSimulator circSim; Timer timer; static final double MAXTHICKNESS = 5; // Want we<SUF> double maxCurrent; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale stroom bij te houden double maxVoltage; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale voltage bij te houden public SimulatorModel(SpinnerNumberModel sSHModel, SpinnerNumberModel sSTModel) { simulateHandler = new SimulateMouseHandler(this); this.sSHModel = sSHModel; this.sSTModel = sSTModel; timer = new Timer((Integer) sSHModel.getValue(), new TimerController(this)); circSim = SimulatorFactory.makeSimulator(circ); } public void initSim() { maxCurrent = 0; maxVoltage = 0; circSim = SimulatorFactory.makeSimulator(circ); circSim.init(); } public void resetSim() { maxCurrent = 0; maxVoltage = 0; circSim.reset(); timer.stop(); fireStateChanged(); } public void doStep() { try { circSim.setTimestep((Double) sSTModel.getValue()); circSim.proceed(); fireStateChanged(); } catch (NumericalException ex) { Logger.getLogger("jOldeSpice").log(Level.SEVERE, "Matrix is singular", ex); JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout opgetreden", JOptionPane.ERROR_MESSAGE); timer.stop(); } } public void changeSwitch(Point pt) { EdgeContainer tempSwitch = getNearestSwitch(pt); if (tempSwitch != null) { ((Switch) tempSwitch.getE()).setState(!((Switch) tempSwitch.getE()).getState()); } fireStateChanged(); } public void changeTimer() { if (timer.isRunning()) { timer.stop(); } else { timer.start(); } fireStateChanged(); } // Geeft de dichtstbijzijnde Edge terug, als er geen is gevonden geeft hij null terug public EdgeContainer<Component, PointNode> getNearestSwitch(Point pt) { EdgeContainer<Component, PointNode> nearestEdge = null; double shortest = Double.MAX_VALUE; double distanceToEdge; EdgeList<Component, PointNode> edges = getCirc().getEdgeList(); for (EdgeContainer<Component, PointNode> tempEdge : edges) { PointNode headNode = tempEdge.getHead(); PointNode tailNode = tempEdge.getTail(); distanceToEdge = new Line2D.Double(headNode.getLocation(), tailNode.getLocation()).ptSegDist(pt); if (tempEdge.getE().getClass().getSimpleName().equals("Switch") && distanceToEdge < shortest && distanceToEdge < 50) { shortest = distanceToEdge; nearestEdge = tempEdge; } } return nearestEdge; } public void setMaxCurrent(double current) { maxCurrent = current; } public double getMaxCurrent() { return maxCurrent; } public void setMaxVoltage(double voltage) { maxVoltage = voltage; } public double getMaxVoltage() { return maxVoltage; } public double getMaxThickness() { return MAXTHICKNESS; } public Timer getTimer() { return timer; } public MouseHandler getSimulateHandler() { return simulateHandler; } }
212346_2
/** * * @author Tom Naessens * [email protected] * 1ste Bachelor Informatica * Universiteit Gent * */ package elektrobank.Models.Simulator; import elektrobank.Controllers.Handlers.MouseHandler; import elektrobank.Controllers.Handlers.SimulateMouseHandler; import elektrobank.Controllers.TimerController; import elektrobank.Models.EdgeCircuitModel; import elektrobank.utils.PointNode; import java.awt.Point; import java.awt.geom.Line2D; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; import joldespice.circuit.simulator.CircuitSimulator; import joldespice.circuit.simulator.NumericalException; import joldespice.circuit.simulator.SimulatorFactory; import joldespice.components.Component; import joldespice.components.nonlinear.Switch; import joldespice.graph.EdgeContainer; import joldespice.graph.EdgeList; public class SimulatorModel extends EdgeCircuitModel { MouseHandler simulateHandler; SpinnerNumberModel sSHModel; SpinnerNumberModel sSTModel; CircuitSimulator circSim; Timer timer; static final double MAXTHICKNESS = 5; // Want we willen niet dat onze lijnen TE dik getekend worden! double maxCurrent; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale stroom bij te houden double maxVoltage; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale voltage bij te houden public SimulatorModel(SpinnerNumberModel sSHModel, SpinnerNumberModel sSTModel) { simulateHandler = new SimulateMouseHandler(this); this.sSHModel = sSHModel; this.sSTModel = sSTModel; timer = new Timer((Integer) sSHModel.getValue(), new TimerController(this)); circSim = SimulatorFactory.makeSimulator(circ); } public void initSim() { maxCurrent = 0; maxVoltage = 0; circSim = SimulatorFactory.makeSimulator(circ); circSim.init(); } public void resetSim() { maxCurrent = 0; maxVoltage = 0; circSim.reset(); timer.stop(); fireStateChanged(); } public void doStep() { try { circSim.setTimestep((Double) sSTModel.getValue()); circSim.proceed(); fireStateChanged(); } catch (NumericalException ex) { Logger.getLogger("jOldeSpice").log(Level.SEVERE, "Matrix is singular", ex); JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout opgetreden", JOptionPane.ERROR_MESSAGE); timer.stop(); } } public void changeSwitch(Point pt) { EdgeContainer tempSwitch = getNearestSwitch(pt); if (tempSwitch != null) { ((Switch) tempSwitch.getE()).setState(!((Switch) tempSwitch.getE()).getState()); } fireStateChanged(); } public void changeTimer() { if (timer.isRunning()) { timer.stop(); } else { timer.start(); } fireStateChanged(); } // Geeft de dichtstbijzijnde Edge terug, als er geen is gevonden geeft hij null terug public EdgeContainer<Component, PointNode> getNearestSwitch(Point pt) { EdgeContainer<Component, PointNode> nearestEdge = null; double shortest = Double.MAX_VALUE; double distanceToEdge; EdgeList<Component, PointNode> edges = getCirc().getEdgeList(); for (EdgeContainer<Component, PointNode> tempEdge : edges) { PointNode headNode = tempEdge.getHead(); PointNode tailNode = tempEdge.getTail(); distanceToEdge = new Line2D.Double(headNode.getLocation(), tailNode.getLocation()).ptSegDist(pt); if (tempEdge.getE().getClass().getSimpleName().equals("Switch") && distanceToEdge < shortest && distanceToEdge < 50) { shortest = distanceToEdge; nearestEdge = tempEdge; } } return nearestEdge; } public void setMaxCurrent(double current) { maxCurrent = current; } public double getMaxCurrent() { return maxCurrent; } public void setMaxVoltage(double voltage) { maxVoltage = voltage; } public double getMaxVoltage() { return maxVoltage; } public double getMaxThickness() { return MAXTHICKNESS; } public Timer getTimer() { return timer; } public MouseHandler getSimulateHandler() { return simulateHandler; } }
TomNaessens/UGent-stuff
Prog2--Project--Elektrobank/src/elektrobank/Models/Simulator/SimulatorModel.java
1,167
// Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale stroom bij te houden
line_comment
nl
/** * * @author Tom Naessens * [email protected] * 1ste Bachelor Informatica * Universiteit Gent * */ package elektrobank.Models.Simulator; import elektrobank.Controllers.Handlers.MouseHandler; import elektrobank.Controllers.Handlers.SimulateMouseHandler; import elektrobank.Controllers.TimerController; import elektrobank.Models.EdgeCircuitModel; import elektrobank.utils.PointNode; import java.awt.Point; import java.awt.geom.Line2D; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; import joldespice.circuit.simulator.CircuitSimulator; import joldespice.circuit.simulator.NumericalException; import joldespice.circuit.simulator.SimulatorFactory; import joldespice.components.Component; import joldespice.components.nonlinear.Switch; import joldespice.graph.EdgeContainer; import joldespice.graph.EdgeList; public class SimulatorModel extends EdgeCircuitModel { MouseHandler simulateHandler; SpinnerNumberModel sSHModel; SpinnerNumberModel sSTModel; CircuitSimulator circSim; Timer timer; static final double MAXTHICKNESS = 5; // Want we willen niet dat onze lijnen TE dik getekend worden! double maxCurrent; // Zorgt ervoor<SUF> double maxVoltage; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale voltage bij te houden public SimulatorModel(SpinnerNumberModel sSHModel, SpinnerNumberModel sSTModel) { simulateHandler = new SimulateMouseHandler(this); this.sSHModel = sSHModel; this.sSTModel = sSTModel; timer = new Timer((Integer) sSHModel.getValue(), new TimerController(this)); circSim = SimulatorFactory.makeSimulator(circ); } public void initSim() { maxCurrent = 0; maxVoltage = 0; circSim = SimulatorFactory.makeSimulator(circ); circSim.init(); } public void resetSim() { maxCurrent = 0; maxVoltage = 0; circSim.reset(); timer.stop(); fireStateChanged(); } public void doStep() { try { circSim.setTimestep((Double) sSTModel.getValue()); circSim.proceed(); fireStateChanged(); } catch (NumericalException ex) { Logger.getLogger("jOldeSpice").log(Level.SEVERE, "Matrix is singular", ex); JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout opgetreden", JOptionPane.ERROR_MESSAGE); timer.stop(); } } public void changeSwitch(Point pt) { EdgeContainer tempSwitch = getNearestSwitch(pt); if (tempSwitch != null) { ((Switch) tempSwitch.getE()).setState(!((Switch) tempSwitch.getE()).getState()); } fireStateChanged(); } public void changeTimer() { if (timer.isRunning()) { timer.stop(); } else { timer.start(); } fireStateChanged(); } // Geeft de dichtstbijzijnde Edge terug, als er geen is gevonden geeft hij null terug public EdgeContainer<Component, PointNode> getNearestSwitch(Point pt) { EdgeContainer<Component, PointNode> nearestEdge = null; double shortest = Double.MAX_VALUE; double distanceToEdge; EdgeList<Component, PointNode> edges = getCirc().getEdgeList(); for (EdgeContainer<Component, PointNode> tempEdge : edges) { PointNode headNode = tempEdge.getHead(); PointNode tailNode = tempEdge.getTail(); distanceToEdge = new Line2D.Double(headNode.getLocation(), tailNode.getLocation()).ptSegDist(pt); if (tempEdge.getE().getClass().getSimpleName().equals("Switch") && distanceToEdge < shortest && distanceToEdge < 50) { shortest = distanceToEdge; nearestEdge = tempEdge; } } return nearestEdge; } public void setMaxCurrent(double current) { maxCurrent = current; } public double getMaxCurrent() { return maxCurrent; } public void setMaxVoltage(double voltage) { maxVoltage = voltage; } public double getMaxVoltage() { return maxVoltage; } public double getMaxThickness() { return MAXTHICKNESS; } public Timer getTimer() { return timer; } public MouseHandler getSimulateHandler() { return simulateHandler; } }
212346_3
/** * * @author Tom Naessens * [email protected] * 1ste Bachelor Informatica * Universiteit Gent * */ package elektrobank.Models.Simulator; import elektrobank.Controllers.Handlers.MouseHandler; import elektrobank.Controllers.Handlers.SimulateMouseHandler; import elektrobank.Controllers.TimerController; import elektrobank.Models.EdgeCircuitModel; import elektrobank.utils.PointNode; import java.awt.Point; import java.awt.geom.Line2D; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; import joldespice.circuit.simulator.CircuitSimulator; import joldespice.circuit.simulator.NumericalException; import joldespice.circuit.simulator.SimulatorFactory; import joldespice.components.Component; import joldespice.components.nonlinear.Switch; import joldespice.graph.EdgeContainer; import joldespice.graph.EdgeList; public class SimulatorModel extends EdgeCircuitModel { MouseHandler simulateHandler; SpinnerNumberModel sSHModel; SpinnerNumberModel sSTModel; CircuitSimulator circSim; Timer timer; static final double MAXTHICKNESS = 5; // Want we willen niet dat onze lijnen TE dik getekend worden! double maxCurrent; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale stroom bij te houden double maxVoltage; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale voltage bij te houden public SimulatorModel(SpinnerNumberModel sSHModel, SpinnerNumberModel sSTModel) { simulateHandler = new SimulateMouseHandler(this); this.sSHModel = sSHModel; this.sSTModel = sSTModel; timer = new Timer((Integer) sSHModel.getValue(), new TimerController(this)); circSim = SimulatorFactory.makeSimulator(circ); } public void initSim() { maxCurrent = 0; maxVoltage = 0; circSim = SimulatorFactory.makeSimulator(circ); circSim.init(); } public void resetSim() { maxCurrent = 0; maxVoltage = 0; circSim.reset(); timer.stop(); fireStateChanged(); } public void doStep() { try { circSim.setTimestep((Double) sSTModel.getValue()); circSim.proceed(); fireStateChanged(); } catch (NumericalException ex) { Logger.getLogger("jOldeSpice").log(Level.SEVERE, "Matrix is singular", ex); JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout opgetreden", JOptionPane.ERROR_MESSAGE); timer.stop(); } } public void changeSwitch(Point pt) { EdgeContainer tempSwitch = getNearestSwitch(pt); if (tempSwitch != null) { ((Switch) tempSwitch.getE()).setState(!((Switch) tempSwitch.getE()).getState()); } fireStateChanged(); } public void changeTimer() { if (timer.isRunning()) { timer.stop(); } else { timer.start(); } fireStateChanged(); } // Geeft de dichtstbijzijnde Edge terug, als er geen is gevonden geeft hij null terug public EdgeContainer<Component, PointNode> getNearestSwitch(Point pt) { EdgeContainer<Component, PointNode> nearestEdge = null; double shortest = Double.MAX_VALUE; double distanceToEdge; EdgeList<Component, PointNode> edges = getCirc().getEdgeList(); for (EdgeContainer<Component, PointNode> tempEdge : edges) { PointNode headNode = tempEdge.getHead(); PointNode tailNode = tempEdge.getTail(); distanceToEdge = new Line2D.Double(headNode.getLocation(), tailNode.getLocation()).ptSegDist(pt); if (tempEdge.getE().getClass().getSimpleName().equals("Switch") && distanceToEdge < shortest && distanceToEdge < 50) { shortest = distanceToEdge; nearestEdge = tempEdge; } } return nearestEdge; } public void setMaxCurrent(double current) { maxCurrent = current; } public double getMaxCurrent() { return maxCurrent; } public void setMaxVoltage(double voltage) { maxVoltage = voltage; } public double getMaxVoltage() { return maxVoltage; } public double getMaxThickness() { return MAXTHICKNESS; } public Timer getTimer() { return timer; } public MouseHandler getSimulateHandler() { return simulateHandler; } }
TomNaessens/UGent-stuff
Prog2--Project--Elektrobank/src/elektrobank/Models/Simulator/SimulatorModel.java
1,167
// Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale voltage bij te houden
line_comment
nl
/** * * @author Tom Naessens * [email protected] * 1ste Bachelor Informatica * Universiteit Gent * */ package elektrobank.Models.Simulator; import elektrobank.Controllers.Handlers.MouseHandler; import elektrobank.Controllers.Handlers.SimulateMouseHandler; import elektrobank.Controllers.TimerController; import elektrobank.Models.EdgeCircuitModel; import elektrobank.utils.PointNode; import java.awt.Point; import java.awt.geom.Line2D; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; import joldespice.circuit.simulator.CircuitSimulator; import joldespice.circuit.simulator.NumericalException; import joldespice.circuit.simulator.SimulatorFactory; import joldespice.components.Component; import joldespice.components.nonlinear.Switch; import joldespice.graph.EdgeContainer; import joldespice.graph.EdgeList; public class SimulatorModel extends EdgeCircuitModel { MouseHandler simulateHandler; SpinnerNumberModel sSHModel; SpinnerNumberModel sSTModel; CircuitSimulator circSim; Timer timer; static final double MAXTHICKNESS = 5; // Want we willen niet dat onze lijnen TE dik getekend worden! double maxCurrent; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale stroom bij te houden double maxVoltage; // Zorgt ervoor<SUF> public SimulatorModel(SpinnerNumberModel sSHModel, SpinnerNumberModel sSTModel) { simulateHandler = new SimulateMouseHandler(this); this.sSHModel = sSHModel; this.sSTModel = sSTModel; timer = new Timer((Integer) sSHModel.getValue(), new TimerController(this)); circSim = SimulatorFactory.makeSimulator(circ); } public void initSim() { maxCurrent = 0; maxVoltage = 0; circSim = SimulatorFactory.makeSimulator(circ); circSim.init(); } public void resetSim() { maxCurrent = 0; maxVoltage = 0; circSim.reset(); timer.stop(); fireStateChanged(); } public void doStep() { try { circSim.setTimestep((Double) sSTModel.getValue()); circSim.proceed(); fireStateChanged(); } catch (NumericalException ex) { Logger.getLogger("jOldeSpice").log(Level.SEVERE, "Matrix is singular", ex); JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout opgetreden", JOptionPane.ERROR_MESSAGE); timer.stop(); } } public void changeSwitch(Point pt) { EdgeContainer tempSwitch = getNearestSwitch(pt); if (tempSwitch != null) { ((Switch) tempSwitch.getE()).setState(!((Switch) tempSwitch.getE()).getState()); } fireStateChanged(); } public void changeTimer() { if (timer.isRunning()) { timer.stop(); } else { timer.start(); } fireStateChanged(); } // Geeft de dichtstbijzijnde Edge terug, als er geen is gevonden geeft hij null terug public EdgeContainer<Component, PointNode> getNearestSwitch(Point pt) { EdgeContainer<Component, PointNode> nearestEdge = null; double shortest = Double.MAX_VALUE; double distanceToEdge; EdgeList<Component, PointNode> edges = getCirc().getEdgeList(); for (EdgeContainer<Component, PointNode> tempEdge : edges) { PointNode headNode = tempEdge.getHead(); PointNode tailNode = tempEdge.getTail(); distanceToEdge = new Line2D.Double(headNode.getLocation(), tailNode.getLocation()).ptSegDist(pt); if (tempEdge.getE().getClass().getSimpleName().equals("Switch") && distanceToEdge < shortest && distanceToEdge < 50) { shortest = distanceToEdge; nearestEdge = tempEdge; } } return nearestEdge; } public void setMaxCurrent(double current) { maxCurrent = current; } public double getMaxCurrent() { return maxCurrent; } public void setMaxVoltage(double voltage) { maxVoltage = voltage; } public double getMaxVoltage() { return maxVoltage; } public double getMaxThickness() { return MAXTHICKNESS; } public Timer getTimer() { return timer; } public MouseHandler getSimulateHandler() { return simulateHandler; } }
212346_4
/** * * @author Tom Naessens * [email protected] * 1ste Bachelor Informatica * Universiteit Gent * */ package elektrobank.Models.Simulator; import elektrobank.Controllers.Handlers.MouseHandler; import elektrobank.Controllers.Handlers.SimulateMouseHandler; import elektrobank.Controllers.TimerController; import elektrobank.Models.EdgeCircuitModel; import elektrobank.utils.PointNode; import java.awt.Point; import java.awt.geom.Line2D; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; import joldespice.circuit.simulator.CircuitSimulator; import joldespice.circuit.simulator.NumericalException; import joldespice.circuit.simulator.SimulatorFactory; import joldespice.components.Component; import joldespice.components.nonlinear.Switch; import joldespice.graph.EdgeContainer; import joldespice.graph.EdgeList; public class SimulatorModel extends EdgeCircuitModel { MouseHandler simulateHandler; SpinnerNumberModel sSHModel; SpinnerNumberModel sSTModel; CircuitSimulator circSim; Timer timer; static final double MAXTHICKNESS = 5; // Want we willen niet dat onze lijnen TE dik getekend worden! double maxCurrent; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale stroom bij te houden double maxVoltage; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale voltage bij te houden public SimulatorModel(SpinnerNumberModel sSHModel, SpinnerNumberModel sSTModel) { simulateHandler = new SimulateMouseHandler(this); this.sSHModel = sSHModel; this.sSTModel = sSTModel; timer = new Timer((Integer) sSHModel.getValue(), new TimerController(this)); circSim = SimulatorFactory.makeSimulator(circ); } public void initSim() { maxCurrent = 0; maxVoltage = 0; circSim = SimulatorFactory.makeSimulator(circ); circSim.init(); } public void resetSim() { maxCurrent = 0; maxVoltage = 0; circSim.reset(); timer.stop(); fireStateChanged(); } public void doStep() { try { circSim.setTimestep((Double) sSTModel.getValue()); circSim.proceed(); fireStateChanged(); } catch (NumericalException ex) { Logger.getLogger("jOldeSpice").log(Level.SEVERE, "Matrix is singular", ex); JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout opgetreden", JOptionPane.ERROR_MESSAGE); timer.stop(); } } public void changeSwitch(Point pt) { EdgeContainer tempSwitch = getNearestSwitch(pt); if (tempSwitch != null) { ((Switch) tempSwitch.getE()).setState(!((Switch) tempSwitch.getE()).getState()); } fireStateChanged(); } public void changeTimer() { if (timer.isRunning()) { timer.stop(); } else { timer.start(); } fireStateChanged(); } // Geeft de dichtstbijzijnde Edge terug, als er geen is gevonden geeft hij null terug public EdgeContainer<Component, PointNode> getNearestSwitch(Point pt) { EdgeContainer<Component, PointNode> nearestEdge = null; double shortest = Double.MAX_VALUE; double distanceToEdge; EdgeList<Component, PointNode> edges = getCirc().getEdgeList(); for (EdgeContainer<Component, PointNode> tempEdge : edges) { PointNode headNode = tempEdge.getHead(); PointNode tailNode = tempEdge.getTail(); distanceToEdge = new Line2D.Double(headNode.getLocation(), tailNode.getLocation()).ptSegDist(pt); if (tempEdge.getE().getClass().getSimpleName().equals("Switch") && distanceToEdge < shortest && distanceToEdge < 50) { shortest = distanceToEdge; nearestEdge = tempEdge; } } return nearestEdge; } public void setMaxCurrent(double current) { maxCurrent = current; } public double getMaxCurrent() { return maxCurrent; } public void setMaxVoltage(double voltage) { maxVoltage = voltage; } public double getMaxVoltage() { return maxVoltage; } public double getMaxThickness() { return MAXTHICKNESS; } public Timer getTimer() { return timer; } public MouseHandler getSimulateHandler() { return simulateHandler; } }
TomNaessens/UGent-stuff
Prog2--Project--Elektrobank/src/elektrobank/Models/Simulator/SimulatorModel.java
1,167
// Geeft de dichtstbijzijnde Edge terug, als er geen is gevonden geeft hij null terug
line_comment
nl
/** * * @author Tom Naessens * [email protected] * 1ste Bachelor Informatica * Universiteit Gent * */ package elektrobank.Models.Simulator; import elektrobank.Controllers.Handlers.MouseHandler; import elektrobank.Controllers.Handlers.SimulateMouseHandler; import elektrobank.Controllers.TimerController; import elektrobank.Models.EdgeCircuitModel; import elektrobank.utils.PointNode; import java.awt.Point; import java.awt.geom.Line2D; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SpinnerNumberModel; import javax.swing.Timer; import joldespice.circuit.simulator.CircuitSimulator; import joldespice.circuit.simulator.NumericalException; import joldespice.circuit.simulator.SimulatorFactory; import joldespice.components.Component; import joldespice.components.nonlinear.Switch; import joldespice.graph.EdgeContainer; import joldespice.graph.EdgeList; public class SimulatorModel extends EdgeCircuitModel { MouseHandler simulateHandler; SpinnerNumberModel sSHModel; SpinnerNumberModel sSTModel; CircuitSimulator circSim; Timer timer; static final double MAXTHICKNESS = 5; // Want we willen niet dat onze lijnen TE dik getekend worden! double maxCurrent; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale stroom bij te houden double maxVoltage; // Zorgt ervoor dat we de damping zien op bepaalde momenten door de maximale voltage bij te houden public SimulatorModel(SpinnerNumberModel sSHModel, SpinnerNumberModel sSTModel) { simulateHandler = new SimulateMouseHandler(this); this.sSHModel = sSHModel; this.sSTModel = sSTModel; timer = new Timer((Integer) sSHModel.getValue(), new TimerController(this)); circSim = SimulatorFactory.makeSimulator(circ); } public void initSim() { maxCurrent = 0; maxVoltage = 0; circSim = SimulatorFactory.makeSimulator(circ); circSim.init(); } public void resetSim() { maxCurrent = 0; maxVoltage = 0; circSim.reset(); timer.stop(); fireStateChanged(); } public void doStep() { try { circSim.setTimestep((Double) sSTModel.getValue()); circSim.proceed(); fireStateChanged(); } catch (NumericalException ex) { Logger.getLogger("jOldeSpice").log(Level.SEVERE, "Matrix is singular", ex); JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout opgetreden", JOptionPane.ERROR_MESSAGE); timer.stop(); } } public void changeSwitch(Point pt) { EdgeContainer tempSwitch = getNearestSwitch(pt); if (tempSwitch != null) { ((Switch) tempSwitch.getE()).setState(!((Switch) tempSwitch.getE()).getState()); } fireStateChanged(); } public void changeTimer() { if (timer.isRunning()) { timer.stop(); } else { timer.start(); } fireStateChanged(); } // Geeft de<SUF> public EdgeContainer<Component, PointNode> getNearestSwitch(Point pt) { EdgeContainer<Component, PointNode> nearestEdge = null; double shortest = Double.MAX_VALUE; double distanceToEdge; EdgeList<Component, PointNode> edges = getCirc().getEdgeList(); for (EdgeContainer<Component, PointNode> tempEdge : edges) { PointNode headNode = tempEdge.getHead(); PointNode tailNode = tempEdge.getTail(); distanceToEdge = new Line2D.Double(headNode.getLocation(), tailNode.getLocation()).ptSegDist(pt); if (tempEdge.getE().getClass().getSimpleName().equals("Switch") && distanceToEdge < shortest && distanceToEdge < 50) { shortest = distanceToEdge; nearestEdge = tempEdge; } } return nearestEdge; } public void setMaxCurrent(double current) { maxCurrent = current; } public double getMaxCurrent() { return maxCurrent; } public void setMaxVoltage(double voltage) { maxVoltage = voltage; } public double getMaxVoltage() { return maxVoltage; } public double getMaxThickness() { return MAXTHICKNESS; } public Timer getTimer() { return timer; } public MouseHandler getSimulateHandler() { return simulateHandler; } }
212371_0
package nl.topicus.eduarte.krdparticipatie.web.components.panels.filter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jasperreports.engine.JasperPrint; import nl.topicus.cobra.dao.DataAccessRegistry; import nl.topicus.cobra.dataproviders.CollectionDataProvider; import nl.topicus.cobra.modelsv2.ModelFactory; import nl.topicus.cobra.util.ComponentUtil; import nl.topicus.cobra.util.TimeUtil; import nl.topicus.cobra.web.components.datapanel.ColumnModel; import nl.topicus.cobra.web.components.datapanel.CustomDataPanel; import nl.topicus.cobra.web.components.dataview.ExportableDataView; import nl.topicus.cobra.web.components.link.CustomDataPanelAfdrukkenLink; import nl.topicus.eduarte.dao.participatie.helpers.AfspraakDataAccessHelper; import nl.topicus.eduarte.dao.participatie.helpers.BudgetDataAccessHelper; import nl.topicus.eduarte.entities.inschrijving.Verbintenis; import nl.topicus.eduarte.entities.onderwijsproduct.Onderwijsproduct; import nl.topicus.eduarte.entities.participatie.Afspraak; import nl.topicus.eduarte.entities.participatie.enums.AfspraakTypeCategory; import nl.topicus.eduarte.entities.participatie.enums.UitnodigingStatus; import nl.topicus.eduarte.krdparticipatie.web.components.tables.ActiviteitTotaalTable; import nl.topicus.eduarte.krdparticipatie.web.pages.deelnemer.rapportage.ActiviteitTotaal; import nl.topicus.eduarte.participatie.zoekfilters.AfspraakTypeZoekFilter; import nl.topicus.eduarte.participatie.zoekfilters.AfspraakZoekFilter; import nl.topicus.eduarte.participatie.zoekfilters.DeelnemerActiviteitTotalenZoekFilter; import nl.topicus.eduarte.web.components.panels.EduArteDataPanel; import org.apache.wicket.Component; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; /** * @author vanderkamp */ public class DeelnemerActiviteitTotalenPanel extends Panel { private static final long serialVersionUID = 1L; private CustomDataPanelAfdrukkenLink< ? > printLink; public DeelnemerActiviteitTotalenPanel(String id, Verbintenis verbintenis, DeelnemerActiviteitTotalenZoekFilter filter) { super(id); CollectionDataProvider<ActiviteitTotaal> provider = new CollectionDataProvider<ActiviteitTotaal>(new ActiviteitTotaalModel(verbintenis, filter)); CustomDataPanel<ActiviteitTotaal> panel = new EduArteDataPanel<ActiviteitTotaal>("datapanel", provider, new ActiviteitTotaalTable<ActiviteitTotaal>("Totalen per onderwijsproduct van " + verbintenis.getDeelnemer().getPersoon().getVolledigeNaam(), filter, "Onderwijsproduct", true)) { private static final long serialVersionUID = 1L; @Override protected String getCSVTitle() { return getContentDescription().getTitle(); } @Override protected Component createAfdrukkenLink(@SuppressWarnings("hiding") String id, ColumnModel<ActiviteitTotaal> columns, ExportableDataView<ActiviteitTotaal> dataz) { printLink = (CustomDataPanelAfdrukkenLink< ? >) super.createAfdrukkenLink(id, columns, dataz); return printLink; } }; add(panel); } private class ActiviteitTotaalModel extends LoadableDetachableModel<List<ActiviteitTotaal>> { private static final long serialVersionUID = 1L; private DeelnemerActiviteitTotalenZoekFilter filter; private IModel<Verbintenis> inschrijvingModel; private ActiviteitTotaalModel(Verbintenis verbintenis, DeelnemerActiviteitTotalenZoekFilter filter) { this.filter = filter; this.inschrijvingModel = ModelFactory.getModel(verbintenis); } @Override protected List<ActiviteitTotaal> load() { Verbintenis verbintenis = inschrijvingModel.getObject(); filter.setEindDatum(TimeUtil.getInstance().maakEindeVanDagVanDatum( filter.getEindDatum())); AfspraakZoekFilter afspraakZoekFilter = new AfspraakZoekFilter(); afspraakZoekFilter.setDeelnemer(verbintenis.getDeelnemer()); afspraakZoekFilter.setBeginDatumTijd(filter.getBeginDatum()); afspraakZoekFilter.setEindDatumTijd(filter.getEindDatum()); afspraakZoekFilter.setContract(filter.getContract()); EnumSet<UitnodigingStatus> uitnStatussen = EnumSet.of(UitnodigingStatus.DIRECTE_PLAATSING, UitnodigingStatus.GEACCEPTEERD, UitnodigingStatus.INGETEKEND); afspraakZoekFilter.setUitnodigingStatussen(uitnStatussen); AfspraakTypeZoekFilter afspraakTypeZoekFilter = new AfspraakTypeZoekFilter(); EnumSet<AfspraakTypeCategory> cats = EnumSet.noneOf(AfspraakTypeCategory.class); for (AfspraakTypeCategory category : filter.getAfspraakTypeCategories()) { cats.add(category); } afspraakTypeZoekFilter.setCategories(cats); afspraakZoekFilter.setAfspraakTypeZoekFilter(afspraakTypeZoekFilter); AfspraakDataAccessHelper helper = DataAccessRegistry.getHelper(AfspraakDataAccessHelper.class); List<Afspraak> afsprakenList = new ArrayList<Afspraak>(); if (!filter.getAfspraakTypeCategories().isEmpty()) afsprakenList = helper.list(afspraakZoekFilter); List<ActiviteitTotaal> totalenList = new ArrayList<ActiviteitTotaal>(); Map<Onderwijsproduct, List<Afspraak>> afsprakenMap = new HashMap<Onderwijsproduct, List<Afspraak>>(); List<Afspraak> afsprakenZonderActiviteit = new ArrayList<Afspraak>(); for (Afspraak afspraak : afsprakenList) { if (afspraak.getOnderwijsproduct() != null) { if (!afsprakenMap.containsKey(afspraak.getOnderwijsproduct())) { afsprakenMap.put(afspraak.getOnderwijsproduct(), new ArrayList<Afspraak>()); } afsprakenMap.get(afspraak.getOnderwijsproduct()).add(afspraak); } else { afsprakenZonderActiviteit.add(afspraak); } } if (filter.isActiviteitenTonen() == null || filter.isActiviteitenTonen()) { for (Onderwijsproduct odwpr : afsprakenMap.keySet()) { BudgetDataAccessHelper budgetHelper = DataAccessRegistry.getHelper(BudgetDataAccessHelper.class); BigDecimal budget = new BigDecimal(budgetHelper.getBudget(odwpr, verbintenis.getDeelnemer())); totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), odwpr .getCode(), afsprakenMap.get(odwpr), budget)); } if (!afsprakenZonderActiviteit.isEmpty()) totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), "Geen activiteit", afsprakenZonderActiviteit, BigDecimal.ZERO)); } totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), "Totaal", afsprakenList, BigDecimal.ZERO)); return totalenList; } @Override protected void onDetach() { super.onDetach(); ComponentUtil.detachQuietly(filter); ComponentUtil.detachQuietly(inschrijvingModel); } } public JasperPrint getJasperPrint() { try { return printLink.getJasperPrint(null); } catch (InterruptedException e) { // ignore, kan alleen als het in de achtergrond opgestart wordt. return null; } } }
topicusonderwijs/tribe-krd-opensource
eduarte/module-krd-participatie/src/main/java/nl/topicus/eduarte/krdparticipatie/web/components/panels/filter/DeelnemerActiviteitTotalenPanel.java
2,163
/** * @author vanderkamp */
block_comment
nl
package nl.topicus.eduarte.krdparticipatie.web.components.panels.filter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jasperreports.engine.JasperPrint; import nl.topicus.cobra.dao.DataAccessRegistry; import nl.topicus.cobra.dataproviders.CollectionDataProvider; import nl.topicus.cobra.modelsv2.ModelFactory; import nl.topicus.cobra.util.ComponentUtil; import nl.topicus.cobra.util.TimeUtil; import nl.topicus.cobra.web.components.datapanel.ColumnModel; import nl.topicus.cobra.web.components.datapanel.CustomDataPanel; import nl.topicus.cobra.web.components.dataview.ExportableDataView; import nl.topicus.cobra.web.components.link.CustomDataPanelAfdrukkenLink; import nl.topicus.eduarte.dao.participatie.helpers.AfspraakDataAccessHelper; import nl.topicus.eduarte.dao.participatie.helpers.BudgetDataAccessHelper; import nl.topicus.eduarte.entities.inschrijving.Verbintenis; import nl.topicus.eduarte.entities.onderwijsproduct.Onderwijsproduct; import nl.topicus.eduarte.entities.participatie.Afspraak; import nl.topicus.eduarte.entities.participatie.enums.AfspraakTypeCategory; import nl.topicus.eduarte.entities.participatie.enums.UitnodigingStatus; import nl.topicus.eduarte.krdparticipatie.web.components.tables.ActiviteitTotaalTable; import nl.topicus.eduarte.krdparticipatie.web.pages.deelnemer.rapportage.ActiviteitTotaal; import nl.topicus.eduarte.participatie.zoekfilters.AfspraakTypeZoekFilter; import nl.topicus.eduarte.participatie.zoekfilters.AfspraakZoekFilter; import nl.topicus.eduarte.participatie.zoekfilters.DeelnemerActiviteitTotalenZoekFilter; import nl.topicus.eduarte.web.components.panels.EduArteDataPanel; import org.apache.wicket.Component; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; /** * @author vanderkamp <SUF>*/ public class DeelnemerActiviteitTotalenPanel extends Panel { private static final long serialVersionUID = 1L; private CustomDataPanelAfdrukkenLink< ? > printLink; public DeelnemerActiviteitTotalenPanel(String id, Verbintenis verbintenis, DeelnemerActiviteitTotalenZoekFilter filter) { super(id); CollectionDataProvider<ActiviteitTotaal> provider = new CollectionDataProvider<ActiviteitTotaal>(new ActiviteitTotaalModel(verbintenis, filter)); CustomDataPanel<ActiviteitTotaal> panel = new EduArteDataPanel<ActiviteitTotaal>("datapanel", provider, new ActiviteitTotaalTable<ActiviteitTotaal>("Totalen per onderwijsproduct van " + verbintenis.getDeelnemer().getPersoon().getVolledigeNaam(), filter, "Onderwijsproduct", true)) { private static final long serialVersionUID = 1L; @Override protected String getCSVTitle() { return getContentDescription().getTitle(); } @Override protected Component createAfdrukkenLink(@SuppressWarnings("hiding") String id, ColumnModel<ActiviteitTotaal> columns, ExportableDataView<ActiviteitTotaal> dataz) { printLink = (CustomDataPanelAfdrukkenLink< ? >) super.createAfdrukkenLink(id, columns, dataz); return printLink; } }; add(panel); } private class ActiviteitTotaalModel extends LoadableDetachableModel<List<ActiviteitTotaal>> { private static final long serialVersionUID = 1L; private DeelnemerActiviteitTotalenZoekFilter filter; private IModel<Verbintenis> inschrijvingModel; private ActiviteitTotaalModel(Verbintenis verbintenis, DeelnemerActiviteitTotalenZoekFilter filter) { this.filter = filter; this.inschrijvingModel = ModelFactory.getModel(verbintenis); } @Override protected List<ActiviteitTotaal> load() { Verbintenis verbintenis = inschrijvingModel.getObject(); filter.setEindDatum(TimeUtil.getInstance().maakEindeVanDagVanDatum( filter.getEindDatum())); AfspraakZoekFilter afspraakZoekFilter = new AfspraakZoekFilter(); afspraakZoekFilter.setDeelnemer(verbintenis.getDeelnemer()); afspraakZoekFilter.setBeginDatumTijd(filter.getBeginDatum()); afspraakZoekFilter.setEindDatumTijd(filter.getEindDatum()); afspraakZoekFilter.setContract(filter.getContract()); EnumSet<UitnodigingStatus> uitnStatussen = EnumSet.of(UitnodigingStatus.DIRECTE_PLAATSING, UitnodigingStatus.GEACCEPTEERD, UitnodigingStatus.INGETEKEND); afspraakZoekFilter.setUitnodigingStatussen(uitnStatussen); AfspraakTypeZoekFilter afspraakTypeZoekFilter = new AfspraakTypeZoekFilter(); EnumSet<AfspraakTypeCategory> cats = EnumSet.noneOf(AfspraakTypeCategory.class); for (AfspraakTypeCategory category : filter.getAfspraakTypeCategories()) { cats.add(category); } afspraakTypeZoekFilter.setCategories(cats); afspraakZoekFilter.setAfspraakTypeZoekFilter(afspraakTypeZoekFilter); AfspraakDataAccessHelper helper = DataAccessRegistry.getHelper(AfspraakDataAccessHelper.class); List<Afspraak> afsprakenList = new ArrayList<Afspraak>(); if (!filter.getAfspraakTypeCategories().isEmpty()) afsprakenList = helper.list(afspraakZoekFilter); List<ActiviteitTotaal> totalenList = new ArrayList<ActiviteitTotaal>(); Map<Onderwijsproduct, List<Afspraak>> afsprakenMap = new HashMap<Onderwijsproduct, List<Afspraak>>(); List<Afspraak> afsprakenZonderActiviteit = new ArrayList<Afspraak>(); for (Afspraak afspraak : afsprakenList) { if (afspraak.getOnderwijsproduct() != null) { if (!afsprakenMap.containsKey(afspraak.getOnderwijsproduct())) { afsprakenMap.put(afspraak.getOnderwijsproduct(), new ArrayList<Afspraak>()); } afsprakenMap.get(afspraak.getOnderwijsproduct()).add(afspraak); } else { afsprakenZonderActiviteit.add(afspraak); } } if (filter.isActiviteitenTonen() == null || filter.isActiviteitenTonen()) { for (Onderwijsproduct odwpr : afsprakenMap.keySet()) { BudgetDataAccessHelper budgetHelper = DataAccessRegistry.getHelper(BudgetDataAccessHelper.class); BigDecimal budget = new BigDecimal(budgetHelper.getBudget(odwpr, verbintenis.getDeelnemer())); totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), odwpr .getCode(), afsprakenMap.get(odwpr), budget)); } if (!afsprakenZonderActiviteit.isEmpty()) totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), "Geen activiteit", afsprakenZonderActiviteit, BigDecimal.ZERO)); } totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), "Totaal", afsprakenList, BigDecimal.ZERO)); return totalenList; } @Override protected void onDetach() { super.onDetach(); ComponentUtil.detachQuietly(filter); ComponentUtil.detachQuietly(inschrijvingModel); } } public JasperPrint getJasperPrint() { try { return printLink.getJasperPrint(null); } catch (InterruptedException e) { // ignore, kan alleen als het in de achtergrond opgestart wordt. return null; } } }
212371_1
package nl.topicus.eduarte.krdparticipatie.web.components.panels.filter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jasperreports.engine.JasperPrint; import nl.topicus.cobra.dao.DataAccessRegistry; import nl.topicus.cobra.dataproviders.CollectionDataProvider; import nl.topicus.cobra.modelsv2.ModelFactory; import nl.topicus.cobra.util.ComponentUtil; import nl.topicus.cobra.util.TimeUtil; import nl.topicus.cobra.web.components.datapanel.ColumnModel; import nl.topicus.cobra.web.components.datapanel.CustomDataPanel; import nl.topicus.cobra.web.components.dataview.ExportableDataView; import nl.topicus.cobra.web.components.link.CustomDataPanelAfdrukkenLink; import nl.topicus.eduarte.dao.participatie.helpers.AfspraakDataAccessHelper; import nl.topicus.eduarte.dao.participatie.helpers.BudgetDataAccessHelper; import nl.topicus.eduarte.entities.inschrijving.Verbintenis; import nl.topicus.eduarte.entities.onderwijsproduct.Onderwijsproduct; import nl.topicus.eduarte.entities.participatie.Afspraak; import nl.topicus.eduarte.entities.participatie.enums.AfspraakTypeCategory; import nl.topicus.eduarte.entities.participatie.enums.UitnodigingStatus; import nl.topicus.eduarte.krdparticipatie.web.components.tables.ActiviteitTotaalTable; import nl.topicus.eduarte.krdparticipatie.web.pages.deelnemer.rapportage.ActiviteitTotaal; import nl.topicus.eduarte.participatie.zoekfilters.AfspraakTypeZoekFilter; import nl.topicus.eduarte.participatie.zoekfilters.AfspraakZoekFilter; import nl.topicus.eduarte.participatie.zoekfilters.DeelnemerActiviteitTotalenZoekFilter; import nl.topicus.eduarte.web.components.panels.EduArteDataPanel; import org.apache.wicket.Component; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; /** * @author vanderkamp */ public class DeelnemerActiviteitTotalenPanel extends Panel { private static final long serialVersionUID = 1L; private CustomDataPanelAfdrukkenLink< ? > printLink; public DeelnemerActiviteitTotalenPanel(String id, Verbintenis verbintenis, DeelnemerActiviteitTotalenZoekFilter filter) { super(id); CollectionDataProvider<ActiviteitTotaal> provider = new CollectionDataProvider<ActiviteitTotaal>(new ActiviteitTotaalModel(verbintenis, filter)); CustomDataPanel<ActiviteitTotaal> panel = new EduArteDataPanel<ActiviteitTotaal>("datapanel", provider, new ActiviteitTotaalTable<ActiviteitTotaal>("Totalen per onderwijsproduct van " + verbintenis.getDeelnemer().getPersoon().getVolledigeNaam(), filter, "Onderwijsproduct", true)) { private static final long serialVersionUID = 1L; @Override protected String getCSVTitle() { return getContentDescription().getTitle(); } @Override protected Component createAfdrukkenLink(@SuppressWarnings("hiding") String id, ColumnModel<ActiviteitTotaal> columns, ExportableDataView<ActiviteitTotaal> dataz) { printLink = (CustomDataPanelAfdrukkenLink< ? >) super.createAfdrukkenLink(id, columns, dataz); return printLink; } }; add(panel); } private class ActiviteitTotaalModel extends LoadableDetachableModel<List<ActiviteitTotaal>> { private static final long serialVersionUID = 1L; private DeelnemerActiviteitTotalenZoekFilter filter; private IModel<Verbintenis> inschrijvingModel; private ActiviteitTotaalModel(Verbintenis verbintenis, DeelnemerActiviteitTotalenZoekFilter filter) { this.filter = filter; this.inschrijvingModel = ModelFactory.getModel(verbintenis); } @Override protected List<ActiviteitTotaal> load() { Verbintenis verbintenis = inschrijvingModel.getObject(); filter.setEindDatum(TimeUtil.getInstance().maakEindeVanDagVanDatum( filter.getEindDatum())); AfspraakZoekFilter afspraakZoekFilter = new AfspraakZoekFilter(); afspraakZoekFilter.setDeelnemer(verbintenis.getDeelnemer()); afspraakZoekFilter.setBeginDatumTijd(filter.getBeginDatum()); afspraakZoekFilter.setEindDatumTijd(filter.getEindDatum()); afspraakZoekFilter.setContract(filter.getContract()); EnumSet<UitnodigingStatus> uitnStatussen = EnumSet.of(UitnodigingStatus.DIRECTE_PLAATSING, UitnodigingStatus.GEACCEPTEERD, UitnodigingStatus.INGETEKEND); afspraakZoekFilter.setUitnodigingStatussen(uitnStatussen); AfspraakTypeZoekFilter afspraakTypeZoekFilter = new AfspraakTypeZoekFilter(); EnumSet<AfspraakTypeCategory> cats = EnumSet.noneOf(AfspraakTypeCategory.class); for (AfspraakTypeCategory category : filter.getAfspraakTypeCategories()) { cats.add(category); } afspraakTypeZoekFilter.setCategories(cats); afspraakZoekFilter.setAfspraakTypeZoekFilter(afspraakTypeZoekFilter); AfspraakDataAccessHelper helper = DataAccessRegistry.getHelper(AfspraakDataAccessHelper.class); List<Afspraak> afsprakenList = new ArrayList<Afspraak>(); if (!filter.getAfspraakTypeCategories().isEmpty()) afsprakenList = helper.list(afspraakZoekFilter); List<ActiviteitTotaal> totalenList = new ArrayList<ActiviteitTotaal>(); Map<Onderwijsproduct, List<Afspraak>> afsprakenMap = new HashMap<Onderwijsproduct, List<Afspraak>>(); List<Afspraak> afsprakenZonderActiviteit = new ArrayList<Afspraak>(); for (Afspraak afspraak : afsprakenList) { if (afspraak.getOnderwijsproduct() != null) { if (!afsprakenMap.containsKey(afspraak.getOnderwijsproduct())) { afsprakenMap.put(afspraak.getOnderwijsproduct(), new ArrayList<Afspraak>()); } afsprakenMap.get(afspraak.getOnderwijsproduct()).add(afspraak); } else { afsprakenZonderActiviteit.add(afspraak); } } if (filter.isActiviteitenTonen() == null || filter.isActiviteitenTonen()) { for (Onderwijsproduct odwpr : afsprakenMap.keySet()) { BudgetDataAccessHelper budgetHelper = DataAccessRegistry.getHelper(BudgetDataAccessHelper.class); BigDecimal budget = new BigDecimal(budgetHelper.getBudget(odwpr, verbintenis.getDeelnemer())); totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), odwpr .getCode(), afsprakenMap.get(odwpr), budget)); } if (!afsprakenZonderActiviteit.isEmpty()) totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), "Geen activiteit", afsprakenZonderActiviteit, BigDecimal.ZERO)); } totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), "Totaal", afsprakenList, BigDecimal.ZERO)); return totalenList; } @Override protected void onDetach() { super.onDetach(); ComponentUtil.detachQuietly(filter); ComponentUtil.detachQuietly(inschrijvingModel); } } public JasperPrint getJasperPrint() { try { return printLink.getJasperPrint(null); } catch (InterruptedException e) { // ignore, kan alleen als het in de achtergrond opgestart wordt. return null; } } }
topicusonderwijs/tribe-krd-opensource
eduarte/module-krd-participatie/src/main/java/nl/topicus/eduarte/krdparticipatie/web/components/panels/filter/DeelnemerActiviteitTotalenPanel.java
2,163
// ignore, kan alleen als het in de achtergrond opgestart wordt.
line_comment
nl
package nl.topicus.eduarte.krdparticipatie.web.components.panels.filter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jasperreports.engine.JasperPrint; import nl.topicus.cobra.dao.DataAccessRegistry; import nl.topicus.cobra.dataproviders.CollectionDataProvider; import nl.topicus.cobra.modelsv2.ModelFactory; import nl.topicus.cobra.util.ComponentUtil; import nl.topicus.cobra.util.TimeUtil; import nl.topicus.cobra.web.components.datapanel.ColumnModel; import nl.topicus.cobra.web.components.datapanel.CustomDataPanel; import nl.topicus.cobra.web.components.dataview.ExportableDataView; import nl.topicus.cobra.web.components.link.CustomDataPanelAfdrukkenLink; import nl.topicus.eduarte.dao.participatie.helpers.AfspraakDataAccessHelper; import nl.topicus.eduarte.dao.participatie.helpers.BudgetDataAccessHelper; import nl.topicus.eduarte.entities.inschrijving.Verbintenis; import nl.topicus.eduarte.entities.onderwijsproduct.Onderwijsproduct; import nl.topicus.eduarte.entities.participatie.Afspraak; import nl.topicus.eduarte.entities.participatie.enums.AfspraakTypeCategory; import nl.topicus.eduarte.entities.participatie.enums.UitnodigingStatus; import nl.topicus.eduarte.krdparticipatie.web.components.tables.ActiviteitTotaalTable; import nl.topicus.eduarte.krdparticipatie.web.pages.deelnemer.rapportage.ActiviteitTotaal; import nl.topicus.eduarte.participatie.zoekfilters.AfspraakTypeZoekFilter; import nl.topicus.eduarte.participatie.zoekfilters.AfspraakZoekFilter; import nl.topicus.eduarte.participatie.zoekfilters.DeelnemerActiviteitTotalenZoekFilter; import nl.topicus.eduarte.web.components.panels.EduArteDataPanel; import org.apache.wicket.Component; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; /** * @author vanderkamp */ public class DeelnemerActiviteitTotalenPanel extends Panel { private static final long serialVersionUID = 1L; private CustomDataPanelAfdrukkenLink< ? > printLink; public DeelnemerActiviteitTotalenPanel(String id, Verbintenis verbintenis, DeelnemerActiviteitTotalenZoekFilter filter) { super(id); CollectionDataProvider<ActiviteitTotaal> provider = new CollectionDataProvider<ActiviteitTotaal>(new ActiviteitTotaalModel(verbintenis, filter)); CustomDataPanel<ActiviteitTotaal> panel = new EduArteDataPanel<ActiviteitTotaal>("datapanel", provider, new ActiviteitTotaalTable<ActiviteitTotaal>("Totalen per onderwijsproduct van " + verbintenis.getDeelnemer().getPersoon().getVolledigeNaam(), filter, "Onderwijsproduct", true)) { private static final long serialVersionUID = 1L; @Override protected String getCSVTitle() { return getContentDescription().getTitle(); } @Override protected Component createAfdrukkenLink(@SuppressWarnings("hiding") String id, ColumnModel<ActiviteitTotaal> columns, ExportableDataView<ActiviteitTotaal> dataz) { printLink = (CustomDataPanelAfdrukkenLink< ? >) super.createAfdrukkenLink(id, columns, dataz); return printLink; } }; add(panel); } private class ActiviteitTotaalModel extends LoadableDetachableModel<List<ActiviteitTotaal>> { private static final long serialVersionUID = 1L; private DeelnemerActiviteitTotalenZoekFilter filter; private IModel<Verbintenis> inschrijvingModel; private ActiviteitTotaalModel(Verbintenis verbintenis, DeelnemerActiviteitTotalenZoekFilter filter) { this.filter = filter; this.inschrijvingModel = ModelFactory.getModel(verbintenis); } @Override protected List<ActiviteitTotaal> load() { Verbintenis verbintenis = inschrijvingModel.getObject(); filter.setEindDatum(TimeUtil.getInstance().maakEindeVanDagVanDatum( filter.getEindDatum())); AfspraakZoekFilter afspraakZoekFilter = new AfspraakZoekFilter(); afspraakZoekFilter.setDeelnemer(verbintenis.getDeelnemer()); afspraakZoekFilter.setBeginDatumTijd(filter.getBeginDatum()); afspraakZoekFilter.setEindDatumTijd(filter.getEindDatum()); afspraakZoekFilter.setContract(filter.getContract()); EnumSet<UitnodigingStatus> uitnStatussen = EnumSet.of(UitnodigingStatus.DIRECTE_PLAATSING, UitnodigingStatus.GEACCEPTEERD, UitnodigingStatus.INGETEKEND); afspraakZoekFilter.setUitnodigingStatussen(uitnStatussen); AfspraakTypeZoekFilter afspraakTypeZoekFilter = new AfspraakTypeZoekFilter(); EnumSet<AfspraakTypeCategory> cats = EnumSet.noneOf(AfspraakTypeCategory.class); for (AfspraakTypeCategory category : filter.getAfspraakTypeCategories()) { cats.add(category); } afspraakTypeZoekFilter.setCategories(cats); afspraakZoekFilter.setAfspraakTypeZoekFilter(afspraakTypeZoekFilter); AfspraakDataAccessHelper helper = DataAccessRegistry.getHelper(AfspraakDataAccessHelper.class); List<Afspraak> afsprakenList = new ArrayList<Afspraak>(); if (!filter.getAfspraakTypeCategories().isEmpty()) afsprakenList = helper.list(afspraakZoekFilter); List<ActiviteitTotaal> totalenList = new ArrayList<ActiviteitTotaal>(); Map<Onderwijsproduct, List<Afspraak>> afsprakenMap = new HashMap<Onderwijsproduct, List<Afspraak>>(); List<Afspraak> afsprakenZonderActiviteit = new ArrayList<Afspraak>(); for (Afspraak afspraak : afsprakenList) { if (afspraak.getOnderwijsproduct() != null) { if (!afsprakenMap.containsKey(afspraak.getOnderwijsproduct())) { afsprakenMap.put(afspraak.getOnderwijsproduct(), new ArrayList<Afspraak>()); } afsprakenMap.get(afspraak.getOnderwijsproduct()).add(afspraak); } else { afsprakenZonderActiviteit.add(afspraak); } } if (filter.isActiviteitenTonen() == null || filter.isActiviteitenTonen()) { for (Onderwijsproduct odwpr : afsprakenMap.keySet()) { BudgetDataAccessHelper budgetHelper = DataAccessRegistry.getHelper(BudgetDataAccessHelper.class); BigDecimal budget = new BigDecimal(budgetHelper.getBudget(odwpr, verbintenis.getDeelnemer())); totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), odwpr .getCode(), afsprakenMap.get(odwpr), budget)); } if (!afsprakenZonderActiviteit.isEmpty()) totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), "Geen activiteit", afsprakenZonderActiviteit, BigDecimal.ZERO)); } totalenList.add(new ActiviteitTotaal(verbintenis.getDeelnemer(), "Totaal", afsprakenList, BigDecimal.ZERO)); return totalenList; } @Override protected void onDetach() { super.onDetach(); ComponentUtil.detachQuietly(filter); ComponentUtil.detachQuietly(inschrijvingModel); } } public JasperPrint getJasperPrint() { try { return printLink.getJasperPrint(null); } catch (InterruptedException e) { // ignore, kan<SUF> return null; } } }
212393_0
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.jpa.personen.db; import java.math.BigDecimal; import javax.persistence.*; @Entity @Table(name = "email") public class Email extends BaseEntity { private static final long serialVersionUID = 1L; @Id @TableGenerator(name = "table_gen_email", table = "serial", pkColumnName = "id", valueColumnName = "val", pkColumnValue = "email", allocationSize = 1) @GeneratedValue(strategy = GenerationType.TABLE, generator = "table_gen_email") @Column(name = "c_email", unique = true, nullable = false, precision = 131089) private Long cEmail; @Column(precision = 131089) private BigDecimal actief; @Column(name = "geldig") private int geldigheid = 0; @Column() private String email; @Column() private String onderwerp; @Column() private String van; @Column() private String bcc; @Column(name = "antwoord_naar") private String antwoordNaar; @Column(name = "inhoud") private String inhoud; @Column(name = "content_type", length = 1) private String contentType; public Email() { } public Long getCEmail() { return cEmail; } public void setCEmail(Long cEmail) { this.cEmail = cEmail; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getOnderwerp() { return onderwerp; } public void setOnderwerp(String onderwerp) { this.onderwerp = onderwerp; } public String getVan() { return van; } public void setVan(String van) { this.van = van; } public String getAntwoordNaar() { return antwoordNaar; } public void setAntwoordNaar(String antwoordNaar) { this.antwoordNaar = antwoordNaar; } public String getInhoud() { return inhoud; } public void setInhoud(String inhoud) { this.inhoud = inhoud; } public BigDecimal getActief() { return actief; } public void setActief(BigDecimal actief) { this.actief = actief; } public int getGeldigheid() { return geldigheid; } public void setGeldigheid(int geldigheid) { this.geldigheid = geldigheid; } public String getBcc() { return bcc; } public void setBcc(String bcc) { this.bcc = bcc; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } }
vrijBRP/vrijBRP-Balie
gba-jpa/src/main/java/nl/procura/gba/jpa/personen/db/Email.java
977
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */
block_comment
nl
/* * Copyright 2021 -<SUF>*/ package nl.procura.gba.jpa.personen.db; import java.math.BigDecimal; import javax.persistence.*; @Entity @Table(name = "email") public class Email extends BaseEntity { private static final long serialVersionUID = 1L; @Id @TableGenerator(name = "table_gen_email", table = "serial", pkColumnName = "id", valueColumnName = "val", pkColumnValue = "email", allocationSize = 1) @GeneratedValue(strategy = GenerationType.TABLE, generator = "table_gen_email") @Column(name = "c_email", unique = true, nullable = false, precision = 131089) private Long cEmail; @Column(precision = 131089) private BigDecimal actief; @Column(name = "geldig") private int geldigheid = 0; @Column() private String email; @Column() private String onderwerp; @Column() private String van; @Column() private String bcc; @Column(name = "antwoord_naar") private String antwoordNaar; @Column(name = "inhoud") private String inhoud; @Column(name = "content_type", length = 1) private String contentType; public Email() { } public Long getCEmail() { return cEmail; } public void setCEmail(Long cEmail) { this.cEmail = cEmail; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getOnderwerp() { return onderwerp; } public void setOnderwerp(String onderwerp) { this.onderwerp = onderwerp; } public String getVan() { return van; } public void setVan(String van) { this.van = van; } public String getAntwoordNaar() { return antwoordNaar; } public void setAntwoordNaar(String antwoordNaar) { this.antwoordNaar = antwoordNaar; } public String getInhoud() { return inhoud; } public void setInhoud(String inhoud) { this.inhoud = inhoud; } public BigDecimal getActief() { return actief; } public void setActief(BigDecimal actief) { this.actief = actief; } public int getGeldigheid() { return geldigheid; } public void setGeldigheid(int geldigheid) { this.geldigheid = geldigheid; } public String getBcc() { return bcc; } public void setBcc(String bcc) { this.bcc = bcc; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } }
212403_1
/* * SPDX-FileCopyrightText: 2022 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.zac.mailtemplates.model; import static net.atos.zac.util.FlywayIntegrator.SCHEMA; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.SequenceGenerator; import jakarta.persistence.Table; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; @Entity @Table(schema = SCHEMA, name = "mail_template") @SequenceGenerator(schema = SCHEMA, name = "sq_mail_template", sequenceName = "sq_mail_template", allocationSize = 1) public class MailTemplate { /** * Naam van property: {@link MailTemplate#mail} */ public static final String MAIL = "mail"; /** * Naam van property: {@link MailTemplate#defaultMailtemplate} */ public static final String DEFAULT_MAILTEMPLATE = "defaultMailtemplate"; @Id @GeneratedValue(generator = "sq_mail_template", strategy = GenerationType.SEQUENCE) @Column(name = "id_mail_template") private Long id; @NotBlank @Column(name = "mail_template_naam", nullable = false) private String mailTemplateNaam; @NotBlank @Column(name = "onderwerp", nullable = false) private String onderwerp; @NotBlank @Column(name = "body", nullable = false) private String body; @NotNull @Column(name = "mail_template_enum", nullable = false) @Enumerated(EnumType.STRING) private Mail mail; @NotNull @Column(name = "default_mailtemplate", nullable = false) private Boolean defaultMailtemplate; public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getMailTemplateNaam() { return mailTemplateNaam; } public void setMailTemplateNaam(final String mailTemplateNaam) { this.mailTemplateNaam = mailTemplateNaam; } public String getOnderwerp() { return onderwerp; } public void setOnderwerp(final String onderwerp) { this.onderwerp = onderwerp; } public String getBody() { return body; } public void setBody(final String body) { this.body = body; } public Mail getMail() { return mail; } public void setMail(final Mail mail) { this.mail = mail; } public Boolean isDefaultMailtemplate() { return defaultMailtemplate; } public void setDefaultMailtemplate(final Boolean defaultMailtemplate) { this.defaultMailtemplate = defaultMailtemplate; } }
infonl/dimpact-zaakafhandelcomponent
src/main/java/net/atos/zac/mailtemplates/model/MailTemplate.java
734
/** * Naam van property: {@link MailTemplate#mail} */
block_comment
nl
/* * SPDX-FileCopyrightText: 2022 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.zac.mailtemplates.model; import static net.atos.zac.util.FlywayIntegrator.SCHEMA; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.SequenceGenerator; import jakarta.persistence.Table; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; @Entity @Table(schema = SCHEMA, name = "mail_template") @SequenceGenerator(schema = SCHEMA, name = "sq_mail_template", sequenceName = "sq_mail_template", allocationSize = 1) public class MailTemplate { /** * Naam van property:<SUF>*/ public static final String MAIL = "mail"; /** * Naam van property: {@link MailTemplate#defaultMailtemplate} */ public static final String DEFAULT_MAILTEMPLATE = "defaultMailtemplate"; @Id @GeneratedValue(generator = "sq_mail_template", strategy = GenerationType.SEQUENCE) @Column(name = "id_mail_template") private Long id; @NotBlank @Column(name = "mail_template_naam", nullable = false) private String mailTemplateNaam; @NotBlank @Column(name = "onderwerp", nullable = false) private String onderwerp; @NotBlank @Column(name = "body", nullable = false) private String body; @NotNull @Column(name = "mail_template_enum", nullable = false) @Enumerated(EnumType.STRING) private Mail mail; @NotNull @Column(name = "default_mailtemplate", nullable = false) private Boolean defaultMailtemplate; public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getMailTemplateNaam() { return mailTemplateNaam; } public void setMailTemplateNaam(final String mailTemplateNaam) { this.mailTemplateNaam = mailTemplateNaam; } public String getOnderwerp() { return onderwerp; } public void setOnderwerp(final String onderwerp) { this.onderwerp = onderwerp; } public String getBody() { return body; } public void setBody(final String body) { this.body = body; } public Mail getMail() { return mail; } public void setMail(final Mail mail) { this.mail = mail; } public Boolean isDefaultMailtemplate() { return defaultMailtemplate; } public void setDefaultMailtemplate(final Boolean defaultMailtemplate) { this.defaultMailtemplate = defaultMailtemplate; } }
212410_0
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.modules.zaken.aantekening.page2; import java.io.Serializable; import java.lang.annotation.ElementType; import nl.procura.gba.web.components.fields.GbaNativeSelect; import nl.procura.gba.web.components.fields.GbaTextField; import nl.procura.gba.web.services.zaken.algemeen.aantekening.PlAantekeningIndicatie; import nl.procura.gba.web.services.zaken.algemeen.aantekening.PlAantekeningStatus; import nl.procura.vaadin.annotation.field.Field; import nl.procura.vaadin.annotation.field.Field.FieldType; import nl.procura.vaadin.annotation.field.FormFieldFactoryBean; import nl.procura.vaadin.annotation.field.Immediate; import nl.procura.vaadin.annotation.field.Select; import nl.procura.vaadin.annotation.field.TextArea; import nl.procura.vaadin.component.field.ProNativeSelect; import lombok.Data; @Data @FormFieldFactoryBean(accessType = ElementType.FIELD) public class Page2AantekeningBean implements Serializable { public static final String DATUM = "datum"; public static final String GEBRUIKER = "gebruiker"; public static final String INDICATIE = "indicatie"; public static final String INDICATIE_LABEL = "indicatieLabel"; public static final String ONDERWERP = "onderwerp"; public static final String ONDERWERP_LABEL = "onderwerpLabel"; public static final String INHOUD = "inhoud"; public static final String INHOUD_LABEL = "inhoudLabel"; public static final String STATUS = "status"; @Field(type = FieldType.LABEL, caption = "Datum / tijd") private String datum = ""; @Field(type = FieldType.LABEL, caption = "Gebruiker") private String gebruiker = ""; @Field(customTypeClass = GbaNativeSelect.class, caption = "Indicatie", width = "500px", required = true) @Immediate private PlAantekeningIndicatie indicatie = null; @Field(type = FieldType.LABEL, caption = "Indicatie", width = "500px") @TextArea(maxLength = 250) private String indicatieLabel = ""; @Field(customTypeClass = GbaTextField.class, caption = "Onderwerp", width = "500px") private String onderwerp = ""; @Field(type = FieldType.LABEL, caption = "Onderwerp", width = "500px") private String onderwerpLabel = ""; @Field(type = FieldType.TEXT_AREA, caption = "Inhoud", width = "700px") @TextArea(rows = 25) private String inhoud = ""; @Field(type = FieldType.TEXT_AREA, caption = "Inhoud", width = "700px", readOnly = true) @TextArea(rows = 25) private String inhoudLabel = ""; @Field(customTypeClass = ProNativeSelect.class, caption = "Status") @Select(containerDataSource = StatusContainer.class, nullSelectionAllowed = false) private PlAantekeningStatus status; }
vrijBRP/vrijBRP-Balie
gba-web/src/main/java/nl/procura/gba/web/modules/zaken/aantekening/page2/Page2AantekeningBean.java
1,085
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */
block_comment
nl
/* * Copyright 2021 -<SUF>*/ package nl.procura.gba.web.modules.zaken.aantekening.page2; import java.io.Serializable; import java.lang.annotation.ElementType; import nl.procura.gba.web.components.fields.GbaNativeSelect; import nl.procura.gba.web.components.fields.GbaTextField; import nl.procura.gba.web.services.zaken.algemeen.aantekening.PlAantekeningIndicatie; import nl.procura.gba.web.services.zaken.algemeen.aantekening.PlAantekeningStatus; import nl.procura.vaadin.annotation.field.Field; import nl.procura.vaadin.annotation.field.Field.FieldType; import nl.procura.vaadin.annotation.field.FormFieldFactoryBean; import nl.procura.vaadin.annotation.field.Immediate; import nl.procura.vaadin.annotation.field.Select; import nl.procura.vaadin.annotation.field.TextArea; import nl.procura.vaadin.component.field.ProNativeSelect; import lombok.Data; @Data @FormFieldFactoryBean(accessType = ElementType.FIELD) public class Page2AantekeningBean implements Serializable { public static final String DATUM = "datum"; public static final String GEBRUIKER = "gebruiker"; public static final String INDICATIE = "indicatie"; public static final String INDICATIE_LABEL = "indicatieLabel"; public static final String ONDERWERP = "onderwerp"; public static final String ONDERWERP_LABEL = "onderwerpLabel"; public static final String INHOUD = "inhoud"; public static final String INHOUD_LABEL = "inhoudLabel"; public static final String STATUS = "status"; @Field(type = FieldType.LABEL, caption = "Datum / tijd") private String datum = ""; @Field(type = FieldType.LABEL, caption = "Gebruiker") private String gebruiker = ""; @Field(customTypeClass = GbaNativeSelect.class, caption = "Indicatie", width = "500px", required = true) @Immediate private PlAantekeningIndicatie indicatie = null; @Field(type = FieldType.LABEL, caption = "Indicatie", width = "500px") @TextArea(maxLength = 250) private String indicatieLabel = ""; @Field(customTypeClass = GbaTextField.class, caption = "Onderwerp", width = "500px") private String onderwerp = ""; @Field(type = FieldType.LABEL, caption = "Onderwerp", width = "500px") private String onderwerpLabel = ""; @Field(type = FieldType.TEXT_AREA, caption = "Inhoud", width = "700px") @TextArea(rows = 25) private String inhoud = ""; @Field(type = FieldType.TEXT_AREA, caption = "Inhoud", width = "700px", readOnly = true) @TextArea(rows = 25) private String inhoudLabel = ""; @Field(customTypeClass = ProNativeSelect.class, caption = "Status") @Select(containerDataSource = StatusContainer.class, nullSelectionAllowed = false) private PlAantekeningStatus status; }
212419_0
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
CharlotteErpels1993/TI3_GC05_Project
Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/ProfielDetail.java
1,878
//Geeft een detail van de aangeklikte monitor
line_comment
nl
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een<SUF> public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
212419_1
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
CharlotteErpels1993/TI3_GC05_Project
Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/ProfielDetail.java
1,878
/*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/
block_comment
nl
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat");<SUF>*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
212419_2
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
CharlotteErpels1993/TI3_GC05_Project
Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/ProfielDetail.java
1,878
//Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken
line_comment
nl
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de<SUF> final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
212419_3
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
CharlotteErpels1993/TI3_GC05_Project
Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/ProfielDetail.java
1,878
//Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel
line_comment
nl
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op<SUF> //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
212419_4
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
CharlotteErpels1993/TI3_GC05_Project
Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/ProfielDetail.java
1,878
//Zoneen geef een gepaste boodschap
line_comment
nl
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef<SUF> isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
212419_5
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
CharlotteErpels1993/TI3_GC05_Project
Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/ProfielDetail.java
1,878
//Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres
line_comment
nl
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het<SUF> Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
212419_7
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
CharlotteErpels1993/TI3_GC05_Project
Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/ProfielDetail.java
1,878
/*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/
block_comment
nl
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); <SUF>*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
212419_8
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
CharlotteErpels1993/TI3_GC05_Project
Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/ProfielDetail.java
1,878
/*public static Intent getOpenFacebookIntent(Context context, String voornaam, String achternaam) { try { context.getPackageManager().getPackageInfo("com.facebook.katana", 0); achternaam.replaceAll("\\s+",""); //return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + voornaam +"."+achternaam)); return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } catch (Exception e) { return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + voornaam+"."+achternaam)); } }*/
block_comment
nl
package com.hogent.ti3g05.ti3_g05_joetzapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hogent.ti3g05.ti3_g05_joetzapp.Services.ConnectionDetector; import com.parse.ParseUser; //Geeft een detail van de aangeklikte monitor public class ProfielDetail extends Activity { String naam; String voornaam; String email; String gsm; Boolean isInternetPresent = false; ConnectionDetector cd; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha); try { setContentView(R.layout.profiel_detail); }catch (OutOfMemoryError e) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } catch (InflateException ex) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } Intent i = getIntent(); naam = i.getStringExtra("naam"); voornaam = i.getStringExtra("voornaam"); email = i.getStringExtra("email"); gsm = i.getStringExtra("gsm"); /*straat = i.getStringExtra("straat"); //huisnr = i.getStringExtra("huisnr"); gemeente = i.getStringExtra("gemeente"); // periodes = i.getStringExtra("periodes"); rijksregisterNr = i.getStringExtra("rijksregNr"); lidNr = i.getStringExtra("lidNr");*/ setTitle(naam + " " + voornaam); cd = new ConnectionDetector(getApplicationContext()); TextView txtNaam = (TextView) findViewById(R.id.achternaamP); TextView txtVoornaam = (TextView) findViewById(R.id.voornaamP); TextView txtEmail = (TextView) findViewById(R.id.emailP); TextView txtGsm = (TextView)findViewById(R.id.gsmP); if(ParseUser.getCurrentUser().getEmail().equals(email)) { //Indien de gebruiker zijn eigen profiel selecteert kan hij deze bewerken final Button btnProfielEdit = (Button) findViewById(R.id.btnProfielEdit); btnProfielEdit.setVisibility(View.VISIBLE); btnProfielEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnProfielEdit.startAnimation(animAlpha); //Als op de knop geklikt wordt kijk of er internet is, zoja stuur de gebruiker door naar het bewerken van zijn profiel //Zoneen geef een gepaste boodschap isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Intent inte = new Intent(getApplicationContext(), ProfielEdit.class); inte.putExtra("naam", naam); inte.putExtra("voornaam", voornaam); inte.putExtra("gsm", gsm); inte.putExtra("email", email); startActivity(inte); } else { Toast.makeText(getApplicationContext(), getString(R.string.error_no_internet), Toast.LENGTH_SHORT).show(); } } }); } txtNaam.setText(naam); txtVoornaam.setText(voornaam); txtEmail.setText(email); txtGsm.setText(gsm); final Button mail = (Button) findViewById(R.id.mail); mail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mail.startAnimation(animAlpha); //Bij het klikken op de knop wordt de mail applicatie geopend en kan de gebruiker een mail sturen naar het email adres Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{ email }); i.putExtra(Intent.EXTRA_SUBJECT, "onderwerp"); startActivity(i); } }); /*ImageView naarProf = (ImageView)findViewById(R.id.naarprofiel); naarProf.setVisibility(View.GONE); naarProf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent fb = getOpenFacebookIntent(getApplicationContext(), voornaam, naam); startActivity(fb); } });*/ /*//txtmaxDeeln.setText(maxDeeln.toString()); //txtLidNr.setText(lidNr); txtStraat.setText(straat); txtGemeente.setText(gemeente); txtRijksregNr.setText(rijksregisterNr);*/ } /*public static Intent<SUF>*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.back_2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.backMenu2) { Intent intent1 = new Intent(this, navBarMainScreen.class); intent1.putExtra("naarfrag", "profiel"); intent1.putExtra("herladen", "nee"); intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent1); overridePendingTransition(R.anim.left_in, R.anim.right_out); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent setIntent = new Intent(ProfielDetail.this, navBarMainScreen.class); setIntent.putExtra("naarfrag","profiel"); setIntent.putExtra("herladen","nee"); setIntent.addCategory(Intent.CATEGORY_HOME); setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(setIntent); } }
212432_0
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.modules.beheer.email.page2; import java.io.Serializable; import java.lang.annotation.ElementType; import nl.procura.gba.web.components.fields.GbaInternetAddressField; import nl.procura.gba.web.components.fields.GbaNativeSelect; import nl.procura.gba.web.services.beheer.email.EmailType; import nl.procura.gba.web.services.beheer.email.EmailTypeContent; import nl.procura.vaadin.annotation.field.*; import nl.procura.vaadin.annotation.field.Field.FieldType; import nl.procura.vaadin.component.container.NLBooleanContainer; import nl.procura.vaadin.component.field.PosNumberField; import lombok.Data; @Data @FormFieldFactoryBean(accessType = ElementType.FIELD) public class Page2EmailBean implements Serializable { public static final String TYPE = "type"; public static final String TYPE_CONTENT = "typeContent"; public static final String ACTIVEREN = "activeren"; public static final String ONDERWERP = "onderwerp"; public static final String BCC = "bcc"; public static final String VAN = "van"; public static final String ANTWOORD_NAAR = "antwoordNaar"; public static final String VARIABELEN = "variabelen"; public static final String GELDIG = "geldig"; @Field(customTypeClass = GbaNativeSelect.class, caption = "Geactiveerd", required = true) @Select(nullSelectionAllowed = false, containerDataSource = NLBooleanContainer.class, itemCaptionPropertyId = NLBooleanContainer.JA_NEE) @Immediate private Boolean activeren = null; @Field(customTypeClass = GbaNativeSelect.class, caption = "Type", required = true, width = "400px") @Select(containerDataSource = EmailTypeContainer.class) @Immediate private EmailType type = null; @Field(customTypeClass = GbaNativeSelect.class, caption = "Soort inhoud", required = true) @Select(containerDataSource = EmailTypeContentContainer.class, nullSelectionAllowed = false) @Immediate private EmailTypeContent typeContent = null; @Field(type = FieldType.TEXT_FIELD, caption = "Onderwerp", required = true, width = "400px") @TextField(nullRepresentation = "", maxLength = 255) private String onderwerp = ""; @Field(type = FieldType.TEXT_FIELD, caption = "Variabelen", width = "600px", readOnly = true) private String variabelen = ""; @Field(customTypeClass = GbaInternetAddressField.class, caption = "Van", required = true, width = "400px") @TextField(nullRepresentation = "", maxLength = 255) private String van = ""; @Field(customTypeClass = GbaInternetAddressField.class, caption = "BCC", width = "400px") @TextField(nullRepresentation = "", maxLength = 255) private String bcc = ""; @Field(customTypeClass = GbaInternetAddressField.class, caption = "Antwoord-naar", required = true, width = "400px") @TextField(nullRepresentation = "", maxLength = 255) private String antwoordNaar = ""; @Field(customTypeClass = PosNumberField.class, caption = "Geldigheid van de link", width = "40px", required = true) @TextField(maxLength = 2) private String geldig = ""; }
vrijBRP/vrijBRP-Balie
gba-web/src/main/java/nl/procura/gba/web/modules/beheer/email/page2/Page2EmailBean.java
1,150
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */
block_comment
nl
/* * Copyright 2021 -<SUF>*/ package nl.procura.gba.web.modules.beheer.email.page2; import java.io.Serializable; import java.lang.annotation.ElementType; import nl.procura.gba.web.components.fields.GbaInternetAddressField; import nl.procura.gba.web.components.fields.GbaNativeSelect; import nl.procura.gba.web.services.beheer.email.EmailType; import nl.procura.gba.web.services.beheer.email.EmailTypeContent; import nl.procura.vaadin.annotation.field.*; import nl.procura.vaadin.annotation.field.Field.FieldType; import nl.procura.vaadin.component.container.NLBooleanContainer; import nl.procura.vaadin.component.field.PosNumberField; import lombok.Data; @Data @FormFieldFactoryBean(accessType = ElementType.FIELD) public class Page2EmailBean implements Serializable { public static final String TYPE = "type"; public static final String TYPE_CONTENT = "typeContent"; public static final String ACTIVEREN = "activeren"; public static final String ONDERWERP = "onderwerp"; public static final String BCC = "bcc"; public static final String VAN = "van"; public static final String ANTWOORD_NAAR = "antwoordNaar"; public static final String VARIABELEN = "variabelen"; public static final String GELDIG = "geldig"; @Field(customTypeClass = GbaNativeSelect.class, caption = "Geactiveerd", required = true) @Select(nullSelectionAllowed = false, containerDataSource = NLBooleanContainer.class, itemCaptionPropertyId = NLBooleanContainer.JA_NEE) @Immediate private Boolean activeren = null; @Field(customTypeClass = GbaNativeSelect.class, caption = "Type", required = true, width = "400px") @Select(containerDataSource = EmailTypeContainer.class) @Immediate private EmailType type = null; @Field(customTypeClass = GbaNativeSelect.class, caption = "Soort inhoud", required = true) @Select(containerDataSource = EmailTypeContentContainer.class, nullSelectionAllowed = false) @Immediate private EmailTypeContent typeContent = null; @Field(type = FieldType.TEXT_FIELD, caption = "Onderwerp", required = true, width = "400px") @TextField(nullRepresentation = "", maxLength = 255) private String onderwerp = ""; @Field(type = FieldType.TEXT_FIELD, caption = "Variabelen", width = "600px", readOnly = true) private String variabelen = ""; @Field(customTypeClass = GbaInternetAddressField.class, caption = "Van", required = true, width = "400px") @TextField(nullRepresentation = "", maxLength = 255) private String van = ""; @Field(customTypeClass = GbaInternetAddressField.class, caption = "BCC", width = "400px") @TextField(nullRepresentation = "", maxLength = 255) private String bcc = ""; @Field(customTypeClass = GbaInternetAddressField.class, caption = "Antwoord-naar", required = true, width = "400px") @TextField(nullRepresentation = "", maxLength = 255) private String antwoordNaar = ""; @Field(customTypeClass = PosNumberField.class, caption = "Geldigheid van de link", width = "40px", required = true) @TextField(maxLength = 2) private String geldig = ""; }
212446_0
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.components.layouts.form.document.email.page1; import java.io.Serializable; import java.lang.annotation.ElementType; import nl.procura.gba.web.components.fields.GbaTextField; import nl.procura.gba.web.services.beheer.email.EmailTemplate; import nl.procura.vaadin.annotation.field.Field; import nl.procura.vaadin.annotation.field.FormFieldFactoryBean; import nl.procura.vaadin.annotation.field.Select; import nl.procura.vaadin.component.field.ProNativeSelect; import lombok.Data; @Data @FormFieldFactoryBean(accessType = ElementType.FIELD) public class Page1EmailPreviewsBean implements Serializable { public static final String SJABLOON = "sjabloon"; public static final String ONDERWERP = "onderwerp"; @Field(customTypeClass = ProNativeSelect.class, caption = "E-mail sjabloon", width = "300px") @Select(itemCaptionPropertyId = EmailTemplateContainer.OMSCHRIJVING) private EmailTemplate sjabloon = null; @Field(customTypeClass = GbaTextField.class, caption = "Onderwerp", required = true, width = "300px") private String onderwerp = ""; }
vrijBRP/vrijBRP-Balie
gba-web/src/main/java/nl/procura/gba/web/components/layouts/form/document/email/page1/Page1EmailPreviewsBean.java
567
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */
block_comment
nl
/* * Copyright 2021 -<SUF>*/ package nl.procura.gba.web.components.layouts.form.document.email.page1; import java.io.Serializable; import java.lang.annotation.ElementType; import nl.procura.gba.web.components.fields.GbaTextField; import nl.procura.gba.web.services.beheer.email.EmailTemplate; import nl.procura.vaadin.annotation.field.Field; import nl.procura.vaadin.annotation.field.FormFieldFactoryBean; import nl.procura.vaadin.annotation.field.Select; import nl.procura.vaadin.component.field.ProNativeSelect; import lombok.Data; @Data @FormFieldFactoryBean(accessType = ElementType.FIELD) public class Page1EmailPreviewsBean implements Serializable { public static final String SJABLOON = "sjabloon"; public static final String ONDERWERP = "onderwerp"; @Field(customTypeClass = ProNativeSelect.class, caption = "E-mail sjabloon", width = "300px") @Select(itemCaptionPropertyId = EmailTemplateContainer.OMSCHRIJVING) private EmailTemplate sjabloon = null; @Field(customTypeClass = GbaTextField.class, caption = "Onderwerp", required = true, width = "300px") private String onderwerp = ""; }
212453_0
package io.dropwizard.services; import io.dropwizard.models.Customer; import io.dropwizard.models.Project; import io.dropwizard.persistence.DAO.CustomerDAO; import io.dropwizard.persistence.DAO.ProjectDAO; import io.dropwizard.persistence.DAO.SubjectDAO; import java.util.List; public class ProjectService { private SubjectDAO subjectDao; private CustomerDAO customerDao; private ProjectDAO dao; public ProjectService(ProjectDAO dao, CustomerDAO customerDao, SubjectDAO subjectDao) { this.subjectDao = subjectDao; this.dao = dao; this.customerDao = customerDao; } public List<Project> getProjects(String customerName) { Customer customer = customerDao.getCustomerByName(customerName); return this.dao.getProjectByID(customer.getCustomerId()); } public void addProject(String klantNaam, String projectNaam, String onderwerpNaam) { System.out.println("projectService addProject()"); Project project; Customer customer = customerDao.getCustomerByName(klantNaam); dao.addProject(projectNaam, customer.getCustomerId()); project = dao.getProjectByCIdAndPName(projectNaam, customer.getCustomerId()); subjectDao.addSubject(onderwerpNaam, project.getProjectID()); } // public void addProject(int klant_ID, String projectnaam, String onderwerpnaam) { // // Project project; // dao.addProject(projectnaam, klant_ID); // // project = dao.getProjectByCIdAndPName(projectnaam, klant_ID); // subjectDao.addSubject(onderwerpnaam, project.getProjectID()); // } }
ianbeemsterboerr/ipsen3-api
src/main/java/io/dropwizard/services/ProjectService.java
413
// public void addProject(int klant_ID, String projectnaam, String onderwerpnaam) {
line_comment
nl
package io.dropwizard.services; import io.dropwizard.models.Customer; import io.dropwizard.models.Project; import io.dropwizard.persistence.DAO.CustomerDAO; import io.dropwizard.persistence.DAO.ProjectDAO; import io.dropwizard.persistence.DAO.SubjectDAO; import java.util.List; public class ProjectService { private SubjectDAO subjectDao; private CustomerDAO customerDao; private ProjectDAO dao; public ProjectService(ProjectDAO dao, CustomerDAO customerDao, SubjectDAO subjectDao) { this.subjectDao = subjectDao; this.dao = dao; this.customerDao = customerDao; } public List<Project> getProjects(String customerName) { Customer customer = customerDao.getCustomerByName(customerName); return this.dao.getProjectByID(customer.getCustomerId()); } public void addProject(String klantNaam, String projectNaam, String onderwerpNaam) { System.out.println("projectService addProject()"); Project project; Customer customer = customerDao.getCustomerByName(klantNaam); dao.addProject(projectNaam, customer.getCustomerId()); project = dao.getProjectByCIdAndPName(projectNaam, customer.getCustomerId()); subjectDao.addSubject(onderwerpNaam, project.getProjectID()); } // public void<SUF> // // Project project; // dao.addProject(projectnaam, klant_ID); // // project = dao.getProjectByCIdAndPName(projectnaam, klant_ID); // subjectDao.addSubject(onderwerpnaam, project.getProjectID()); // } }
212461_0
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.services.zaken.algemeen.controle; import static ch.lambdaj.Lambda.join; import static nl.procura.standard.Globalfunctions.trim; import java.util.ArrayList; import java.util.List; public class StandaardControle implements Controle { private String onderwerp; private String id = ""; private String omschrijving; private boolean gewijzigd = false; private List<String> opmerkingen = new ArrayList<>(); public StandaardControle(String onderwerp, String omschrijving) { this.onderwerp = onderwerp; this.omschrijving = omschrijving; } @Override public void addOpmerking(String opmerking) { opmerkingen.add(opmerking); } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getOmschrijving() { return omschrijving; } public void setOmschrijving(String omschrijving) { this.omschrijving = omschrijving; } @Override public String getOnderwerp() { return onderwerp; } public void setOnderwerp(String onderwerp) { this.onderwerp = onderwerp; } @Override public List<String> getOpmerkingen() { return opmerkingen; } public void setOpmerkingen(List<String> opmerkingen) { this.opmerkingen = opmerkingen; } @Override public String getOpmerkingenString() { return trim(join(getOpmerkingen())).trim(); } @Override public boolean isGewijzigd() { return gewijzigd; } @Override public void setGewijzigd(boolean gewijzigd) { this.gewijzigd = gewijzigd; } }
vrijBRP/vrijBRP-Balie
gba-services/src/main/java/nl/procura/gba/web/services/zaken/algemeen/controle/StandaardControle.java
763
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */
block_comment
nl
/* * Copyright 2021 -<SUF>*/ package nl.procura.gba.web.services.zaken.algemeen.controle; import static ch.lambdaj.Lambda.join; import static nl.procura.standard.Globalfunctions.trim; import java.util.ArrayList; import java.util.List; public class StandaardControle implements Controle { private String onderwerp; private String id = ""; private String omschrijving; private boolean gewijzigd = false; private List<String> opmerkingen = new ArrayList<>(); public StandaardControle(String onderwerp, String omschrijving) { this.onderwerp = onderwerp; this.omschrijving = omschrijving; } @Override public void addOpmerking(String opmerking) { opmerkingen.add(opmerking); } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getOmschrijving() { return omschrijving; } public void setOmschrijving(String omschrijving) { this.omschrijving = omschrijving; } @Override public String getOnderwerp() { return onderwerp; } public void setOnderwerp(String onderwerp) { this.onderwerp = onderwerp; } @Override public List<String> getOpmerkingen() { return opmerkingen; } public void setOpmerkingen(List<String> opmerkingen) { this.opmerkingen = opmerkingen; } @Override public String getOpmerkingenString() { return trim(join(getOpmerkingen())).trim(); } @Override public boolean isGewijzigd() { return gewijzigd; } @Override public void setGewijzigd(boolean gewijzigd) { this.gewijzigd = gewijzigd; } }
212576_0
package nl.topicus.eduarte.web.components.choice; import java.util.List; import nl.topicus.cobra.dao.DataAccessRegistry; import nl.topicus.eduarte.dao.helpers.CodeNaamActiefLandelijkOfInstellingEntiteitDataAccessHelper; import nl.topicus.eduarte.entities.onderwijsproduct.SoortPraktijklokaal; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; /** * @author vandekamp */ public class SoortPraktijklokaalCombobox extends DropDownChoice<SoortPraktijklokaal> { private static final long serialVersionUID = 1L; private static final class ListModel extends LoadableDetachableModel<List<SoortPraktijklokaal>> { private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") @Override protected List<SoortPraktijklokaal> load() { return DataAccessRegistry.getHelper( CodeNaamActiefLandelijkOfInstellingEntiteitDataAccessHelper.class).list( SoortPraktijklokaal.class); } } public SoortPraktijklokaalCombobox(String id) { super(id, new ListModel(), new ChoiceRenderer<SoortPraktijklokaal>("naam", "id")); } public SoortPraktijklokaalCombobox(String id, IModel<SoortPraktijklokaal> model) { super(id, model, new ListModel(), new ChoiceRenderer<SoortPraktijklokaal>("naam", "id")); } }
topicusonderwijs/tribe-krd-opensource
eduarte/core/src/main/java/nl/topicus/eduarte/web/components/choice/SoortPraktijklokaalCombobox.java
471
/** * @author vandekamp */
block_comment
nl
package nl.topicus.eduarte.web.components.choice; import java.util.List; import nl.topicus.cobra.dao.DataAccessRegistry; import nl.topicus.eduarte.dao.helpers.CodeNaamActiefLandelijkOfInstellingEntiteitDataAccessHelper; import nl.topicus.eduarte.entities.onderwijsproduct.SoortPraktijklokaal; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; /** * @author vandekamp <SUF>*/ public class SoortPraktijklokaalCombobox extends DropDownChoice<SoortPraktijklokaal> { private static final long serialVersionUID = 1L; private static final class ListModel extends LoadableDetachableModel<List<SoortPraktijklokaal>> { private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") @Override protected List<SoortPraktijklokaal> load() { return DataAccessRegistry.getHelper( CodeNaamActiefLandelijkOfInstellingEntiteitDataAccessHelper.class).list( SoortPraktijklokaal.class); } } public SoortPraktijklokaalCombobox(String id) { super(id, new ListModel(), new ChoiceRenderer<SoortPraktijklokaal>("naam", "id")); } public SoortPraktijklokaalCombobox(String id, IModel<SoortPraktijklokaal> model) { super(id, model, new ListModel(), new ChoiceRenderer<SoortPraktijklokaal>("naam", "id")); } }
212672_5
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2024, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */ package net.sourceforge.plantuml.bpm; import net.sourceforge.plantuml.klimt.UTranslate; import net.sourceforge.plantuml.klimt.color.HColors; import net.sourceforge.plantuml.klimt.drawing.UGraphic; import net.sourceforge.plantuml.klimt.font.StringBounder; import net.sourceforge.plantuml.klimt.geom.XDimension2D; import net.sourceforge.plantuml.klimt.geom.XPoint2D; import net.sourceforge.plantuml.klimt.shape.UDrawable; import net.sourceforge.plantuml.klimt.shape.ULine; import net.sourceforge.plantuml.style.ISkinParam; public class GridArray implements UDrawable { private final int lines; private final int cols; private final Placeable data[][]; private final ISkinParam skinParam; // private final List<GridEdge> edges = new ArrayList<>(); public GridArray(ISkinParam skinParam, int lines, int cols) { this.skinParam = skinParam; this.lines = lines; this.cols = cols; this.data = new Placeable[lines][cols]; } @Override public String toString() { return "" + lines + "x" + cols; } public void setData(int l, int c, Placeable element) { data[l][c] = element; } public Placeable getData(int l, int c) { return data[l][c]; } public final int getRows() { return cols; } public final int getLines() { return lines; } private double getHeightOfLine(StringBounder stringBounder, int line) { double height = 0; for (int i = 0; i < cols; i++) { final Placeable cell = data[line][i]; if (cell == null) { continue; } height = Math.max(height, cell.getDimension(stringBounder, skinParam).getHeight()); } return height; } private double getWidthOfCol(StringBounder stringBounder, int col) { double width = 0; for (int i = 0; i < lines; i++) { final Placeable cell = data[i][col]; if (cell == null) { continue; } width = Math.max(width, cell.getDimension(stringBounder, skinParam).getWidth()); } return width; } private final double margin = 30; public void drawU(UGraphic ug) { // printMe(); final StringBounder stringBounder = ug.getStringBounder(); // for (GridEdge edge : edges) { // // System.err.println("Drawing " + edge); // final int from[] = getCoord(edge.getFrom()); // final int to[] = getCoord(edge.getTo()); // final XPoint2D pt1 = getCenterOf(stringBounder, from[0], from[1]); // final XPoint2D pt2 = getCenterOf(stringBounder, to[0], to[1]); // drawArrow(ug, pt1, pt2); // } double dy = 0; drawInternalGrid(ug); for (int l = 0; l < lines; l++) { double dx = 0; final double heightOfLine = getHeightOfLine(stringBounder, l); for (int r = 0; r < cols; r++) { final double widthOfCol = getWidthOfCol(stringBounder, r); final Placeable cell = data[l][r]; if (cell != null) { final XDimension2D dim = cell.getDimension(stringBounder, skinParam); cell.toTextBlock(skinParam) .drawU(ug.apply(new UTranslate(dx + (widthOfCol + margin - dim.getWidth()) / 2, dy + (heightOfLine + margin - dim.getHeight()) / 2))); } dx += widthOfCol + margin; } dy += heightOfLine + margin; } } private void drawInternalGrid(UGraphic ug) { double heightMax = 0; for (int l = 0; l < lines; l++) { heightMax += getHeightOfLine(ug.getStringBounder(), l) + margin; } double widthMax = 0; for (int c = 0; c < cols; c++) { widthMax += getWidthOfCol(ug.getStringBounder(), c) + margin; } ug = ug.apply(HColors.BLACK); double y = 0; for (int l = 0; l < lines; l++) { ug.apply(UTranslate.dy(y)).draw(ULine.hline(widthMax)); y += getHeightOfLine(ug.getStringBounder(), l) + margin; } double x = 0; for (int c = 0; c < cols; c++) { ug.apply(UTranslate.dx(x)).draw(ULine.vline(heightMax)); x += getWidthOfCol(ug.getStringBounder(), c) + margin; } } private void drawArrow(UGraphic ug, XPoint2D pt1, XPoint2D pt2) { ug = ug.apply(HColors.BLUE); final ULine line = new ULine(pt2.getX() - pt1.getX(), pt2.getY() - pt1.getY()); ug.apply(UTranslate.point(pt1)).draw(line); } private XPoint2D getCenterOf(StringBounder stringBounder, int c, int l) { double x = getWidthOfCol(stringBounder, c) / 2 + margin / 2; for (int i = 0; i < c; i++) { final double widthOfCol = getWidthOfCol(stringBounder, i); x += widthOfCol + margin; } double y = getHeightOfLine(stringBounder, l) / 2 + margin / 2; for (int i = 0; i < l; i++) { final double heightOfLine = getHeightOfLine(stringBounder, i); y += heightOfLine + margin; } return new XPoint2D(x, y); } private int[] getCoord(Cell someCell) { for (int l = 0; l < lines; l++) { for (int c = 0; c < cols; c++) { final Placeable cell = data[l][c]; if (cell == someCell.getData()) { return new int[] { c, l }; } } } throw new IllegalArgumentException(); } private void printMe() { for (int l = 0; l < lines; l++) { for (int c = 0; c < cols; c++) { final Placeable cell = data[l][c]; System.err.print(cell); System.err.print(" ; "); } System.err.println(); } } // void addEdgesInternal(List<GridEdge> edges) { // this.edges.addAll(edges); // } }
plantuml/plantuml
src/net/sourceforge/plantuml/bpm/GridArray.java
2,131
// final int to[] = getCoord(edge.getTo());
line_comment
nl
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2024, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques * * */ package net.sourceforge.plantuml.bpm; import net.sourceforge.plantuml.klimt.UTranslate; import net.sourceforge.plantuml.klimt.color.HColors; import net.sourceforge.plantuml.klimt.drawing.UGraphic; import net.sourceforge.plantuml.klimt.font.StringBounder; import net.sourceforge.plantuml.klimt.geom.XDimension2D; import net.sourceforge.plantuml.klimt.geom.XPoint2D; import net.sourceforge.plantuml.klimt.shape.UDrawable; import net.sourceforge.plantuml.klimt.shape.ULine; import net.sourceforge.plantuml.style.ISkinParam; public class GridArray implements UDrawable { private final int lines; private final int cols; private final Placeable data[][]; private final ISkinParam skinParam; // private final List<GridEdge> edges = new ArrayList<>(); public GridArray(ISkinParam skinParam, int lines, int cols) { this.skinParam = skinParam; this.lines = lines; this.cols = cols; this.data = new Placeable[lines][cols]; } @Override public String toString() { return "" + lines + "x" + cols; } public void setData(int l, int c, Placeable element) { data[l][c] = element; } public Placeable getData(int l, int c) { return data[l][c]; } public final int getRows() { return cols; } public final int getLines() { return lines; } private double getHeightOfLine(StringBounder stringBounder, int line) { double height = 0; for (int i = 0; i < cols; i++) { final Placeable cell = data[line][i]; if (cell == null) { continue; } height = Math.max(height, cell.getDimension(stringBounder, skinParam).getHeight()); } return height; } private double getWidthOfCol(StringBounder stringBounder, int col) { double width = 0; for (int i = 0; i < lines; i++) { final Placeable cell = data[i][col]; if (cell == null) { continue; } width = Math.max(width, cell.getDimension(stringBounder, skinParam).getWidth()); } return width; } private final double margin = 30; public void drawU(UGraphic ug) { // printMe(); final StringBounder stringBounder = ug.getStringBounder(); // for (GridEdge edge : edges) { // // System.err.println("Drawing " + edge); // final int from[] = getCoord(edge.getFrom()); // final int<SUF> // final XPoint2D pt1 = getCenterOf(stringBounder, from[0], from[1]); // final XPoint2D pt2 = getCenterOf(stringBounder, to[0], to[1]); // drawArrow(ug, pt1, pt2); // } double dy = 0; drawInternalGrid(ug); for (int l = 0; l < lines; l++) { double dx = 0; final double heightOfLine = getHeightOfLine(stringBounder, l); for (int r = 0; r < cols; r++) { final double widthOfCol = getWidthOfCol(stringBounder, r); final Placeable cell = data[l][r]; if (cell != null) { final XDimension2D dim = cell.getDimension(stringBounder, skinParam); cell.toTextBlock(skinParam) .drawU(ug.apply(new UTranslate(dx + (widthOfCol + margin - dim.getWidth()) / 2, dy + (heightOfLine + margin - dim.getHeight()) / 2))); } dx += widthOfCol + margin; } dy += heightOfLine + margin; } } private void drawInternalGrid(UGraphic ug) { double heightMax = 0; for (int l = 0; l < lines; l++) { heightMax += getHeightOfLine(ug.getStringBounder(), l) + margin; } double widthMax = 0; for (int c = 0; c < cols; c++) { widthMax += getWidthOfCol(ug.getStringBounder(), c) + margin; } ug = ug.apply(HColors.BLACK); double y = 0; for (int l = 0; l < lines; l++) { ug.apply(UTranslate.dy(y)).draw(ULine.hline(widthMax)); y += getHeightOfLine(ug.getStringBounder(), l) + margin; } double x = 0; for (int c = 0; c < cols; c++) { ug.apply(UTranslate.dx(x)).draw(ULine.vline(heightMax)); x += getWidthOfCol(ug.getStringBounder(), c) + margin; } } private void drawArrow(UGraphic ug, XPoint2D pt1, XPoint2D pt2) { ug = ug.apply(HColors.BLUE); final ULine line = new ULine(pt2.getX() - pt1.getX(), pt2.getY() - pt1.getY()); ug.apply(UTranslate.point(pt1)).draw(line); } private XPoint2D getCenterOf(StringBounder stringBounder, int c, int l) { double x = getWidthOfCol(stringBounder, c) / 2 + margin / 2; for (int i = 0; i < c; i++) { final double widthOfCol = getWidthOfCol(stringBounder, i); x += widthOfCol + margin; } double y = getHeightOfLine(stringBounder, l) / 2 + margin / 2; for (int i = 0; i < l; i++) { final double heightOfLine = getHeightOfLine(stringBounder, i); y += heightOfLine + margin; } return new XPoint2D(x, y); } private int[] getCoord(Cell someCell) { for (int l = 0; l < lines; l++) { for (int c = 0; c < cols; c++) { final Placeable cell = data[l][c]; if (cell == someCell.getData()) { return new int[] { c, l }; } } } throw new IllegalArgumentException(); } private void printMe() { for (int l = 0; l < lines; l++) { for (int c = 0; c < cols; c++) { final Placeable cell = data[l][c]; System.err.print(cell); System.err.print(" ; "); } System.err.println(); } } // void addEdgesInternal(List<GridEdge> edges) { // this.edges.addAll(edges); // } }
212717_0
package servlets; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import database.ConnectDBReservering; import domeinklassen.Reservering; public class ReserveringBevestigenServlet extends HttpServlet{ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Connection con = (Connection)req.getSession().getAttribute("verbinding"); String knop = req.getParameter("knop"); //Haalt de reserveringen op via ingevoerde ID if (knop.equals("zoek")){ String viaID = req.getParameter("zoekviaID"); if(!viaID.equals("")){ try{ ConnectDBReservering reserveringconn = new ConnectDBReservering(con); int autoid = Integer.parseInt(req.getParameter("zoekviaID")); ArrayList<Reservering> reserveringen = reserveringconn.zoekReserveringenVanAuto(autoid); if(reserveringen.size() > 0){ req.setAttribute("reserveringen", reserveringen); } else{ req.setAttribute("error", "Er zijn geen reserveringen voor deze auto!"); } } catch(Exception ex){ req.setAttribute("error","Voer een geldig ID in!"); } } else{ req.setAttribute("error", "Voer een auto ID in!"); } } //haalt de gekozen reservering op uit de database en bevestig de reservering else if(knop.equals("bevestigen")){ String reservering = req.getParameter("gekozenreservering"); if(reservering != null){ int reserveringid = Integer.parseInt(reservering); ConnectDBReservering reserveringconn = new ConnectDBReservering(con); Reservering r = reserveringconn.zoekReservering(reserveringid); r.setGeweest(true); reserveringconn.updateReservering(r); req.setAttribute("msg", "De reservering is succesvol bevestigd"); } else{ req.setAttribute("error", "Er is geen reservering geselecteerd!"); } } req.getRequestDispatcher("reserveringbevestigen.jsp").forward(req, resp); } }
Jfeurich/Themaopdracht2
Themaopdracht/src/servlets/ReserveringBevestigenServlet.java
640
//Haalt de reserveringen op via ingevoerde ID
line_comment
nl
package servlets; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import database.ConnectDBReservering; import domeinklassen.Reservering; public class ReserveringBevestigenServlet extends HttpServlet{ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Connection con = (Connection)req.getSession().getAttribute("verbinding"); String knop = req.getParameter("knop"); //Haalt de<SUF> if (knop.equals("zoek")){ String viaID = req.getParameter("zoekviaID"); if(!viaID.equals("")){ try{ ConnectDBReservering reserveringconn = new ConnectDBReservering(con); int autoid = Integer.parseInt(req.getParameter("zoekviaID")); ArrayList<Reservering> reserveringen = reserveringconn.zoekReserveringenVanAuto(autoid); if(reserveringen.size() > 0){ req.setAttribute("reserveringen", reserveringen); } else{ req.setAttribute("error", "Er zijn geen reserveringen voor deze auto!"); } } catch(Exception ex){ req.setAttribute("error","Voer een geldig ID in!"); } } else{ req.setAttribute("error", "Voer een auto ID in!"); } } //haalt de gekozen reservering op uit de database en bevestig de reservering else if(knop.equals("bevestigen")){ String reservering = req.getParameter("gekozenreservering"); if(reservering != null){ int reserveringid = Integer.parseInt(reservering); ConnectDBReservering reserveringconn = new ConnectDBReservering(con); Reservering r = reserveringconn.zoekReservering(reserveringid); r.setGeweest(true); reserveringconn.updateReservering(r); req.setAttribute("msg", "De reservering is succesvol bevestigd"); } else{ req.setAttribute("error", "Er is geen reservering geselecteerd!"); } } req.getRequestDispatcher("reserveringbevestigen.jsp").forward(req, resp); } }
212717_1
package servlets; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import database.ConnectDBReservering; import domeinklassen.Reservering; public class ReserveringBevestigenServlet extends HttpServlet{ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Connection con = (Connection)req.getSession().getAttribute("verbinding"); String knop = req.getParameter("knop"); //Haalt de reserveringen op via ingevoerde ID if (knop.equals("zoek")){ String viaID = req.getParameter("zoekviaID"); if(!viaID.equals("")){ try{ ConnectDBReservering reserveringconn = new ConnectDBReservering(con); int autoid = Integer.parseInt(req.getParameter("zoekviaID")); ArrayList<Reservering> reserveringen = reserveringconn.zoekReserveringenVanAuto(autoid); if(reserveringen.size() > 0){ req.setAttribute("reserveringen", reserveringen); } else{ req.setAttribute("error", "Er zijn geen reserveringen voor deze auto!"); } } catch(Exception ex){ req.setAttribute("error","Voer een geldig ID in!"); } } else{ req.setAttribute("error", "Voer een auto ID in!"); } } //haalt de gekozen reservering op uit de database en bevestig de reservering else if(knop.equals("bevestigen")){ String reservering = req.getParameter("gekozenreservering"); if(reservering != null){ int reserveringid = Integer.parseInt(reservering); ConnectDBReservering reserveringconn = new ConnectDBReservering(con); Reservering r = reserveringconn.zoekReservering(reserveringid); r.setGeweest(true); reserveringconn.updateReservering(r); req.setAttribute("msg", "De reservering is succesvol bevestigd"); } else{ req.setAttribute("error", "Er is geen reservering geselecteerd!"); } } req.getRequestDispatcher("reserveringbevestigen.jsp").forward(req, resp); } }
Jfeurich/Themaopdracht2
Themaopdracht/src/servlets/ReserveringBevestigenServlet.java
640
//haalt de gekozen reservering op uit de database en bevestig de reservering
line_comment
nl
package servlets; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import database.ConnectDBReservering; import domeinklassen.Reservering; public class ReserveringBevestigenServlet extends HttpServlet{ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Connection con = (Connection)req.getSession().getAttribute("verbinding"); String knop = req.getParameter("knop"); //Haalt de reserveringen op via ingevoerde ID if (knop.equals("zoek")){ String viaID = req.getParameter("zoekviaID"); if(!viaID.equals("")){ try{ ConnectDBReservering reserveringconn = new ConnectDBReservering(con); int autoid = Integer.parseInt(req.getParameter("zoekviaID")); ArrayList<Reservering> reserveringen = reserveringconn.zoekReserveringenVanAuto(autoid); if(reserveringen.size() > 0){ req.setAttribute("reserveringen", reserveringen); } else{ req.setAttribute("error", "Er zijn geen reserveringen voor deze auto!"); } } catch(Exception ex){ req.setAttribute("error","Voer een geldig ID in!"); } } else{ req.setAttribute("error", "Voer een auto ID in!"); } } //haalt de<SUF> else if(knop.equals("bevestigen")){ String reservering = req.getParameter("gekozenreservering"); if(reservering != null){ int reserveringid = Integer.parseInt(reservering); ConnectDBReservering reserveringconn = new ConnectDBReservering(con); Reservering r = reserveringconn.zoekReservering(reserveringid); r.setGeweest(true); reserveringconn.updateReservering(r); req.setAttribute("msg", "De reservering is succesvol bevestigd"); } else{ req.setAttribute("error", "Er is geen reservering geselecteerd!"); } } req.getRequestDispatcher("reserveringbevestigen.jsp").forward(req, resp); } }
212720_0
package nl.topicus.eduarte.web.components.panels.bottomrow; import nl.topicus.cobra.web.components.panels.bottomrow.AbstractBottomRowButton; import nl.topicus.cobra.web.components.panels.bottomrow.BottomRowPanel; import nl.topicus.cobra.web.components.panels.bottomrow.ButtonAlignment; import nl.topicus.cobra.web.components.shortcut.CobraKeyAction; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.link.Link; /** * Standaard voltooien. Let op: Dit is geen SecureComponent. * * @author loite */ public abstract class VoltooienButton extends AbstractBottomRowButton { private static final long serialVersionUID = 1L; public VoltooienButton(BottomRowPanel bottomRow) { this(bottomRow, "Voltooien"); } public VoltooienButton(BottomRowPanel bottomRow, String label) { super(bottomRow, label, CobraKeyAction.LINKKNOP1, ButtonAlignment.RIGHT); } @Override protected WebMarkupContainer getLink(String linkId) { return new Link<Void>(linkId) { private static final long serialVersionUID = 1L; @Override public void onClick() { VoltooienButton.this.onClick(); } }; } /** * Methode die aangeroepen wordt bij het klikken op de link na het bevestigen van de * actie. */ protected abstract void onClick(); }
topicusonderwijs/tribe-krd-opensource
eduarte/core/src/main/java/nl/topicus/eduarte/web/components/panels/bottomrow/VoltooienButton.java
396
/** * Standaard voltooien. Let op: Dit is geen SecureComponent. * * @author loite */
block_comment
nl
package nl.topicus.eduarte.web.components.panels.bottomrow; import nl.topicus.cobra.web.components.panels.bottomrow.AbstractBottomRowButton; import nl.topicus.cobra.web.components.panels.bottomrow.BottomRowPanel; import nl.topicus.cobra.web.components.panels.bottomrow.ButtonAlignment; import nl.topicus.cobra.web.components.shortcut.CobraKeyAction; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.link.Link; /** * Standaard voltooien. Let<SUF>*/ public abstract class VoltooienButton extends AbstractBottomRowButton { private static final long serialVersionUID = 1L; public VoltooienButton(BottomRowPanel bottomRow) { this(bottomRow, "Voltooien"); } public VoltooienButton(BottomRowPanel bottomRow, String label) { super(bottomRow, label, CobraKeyAction.LINKKNOP1, ButtonAlignment.RIGHT); } @Override protected WebMarkupContainer getLink(String linkId) { return new Link<Void>(linkId) { private static final long serialVersionUID = 1L; @Override public void onClick() { VoltooienButton.this.onClick(); } }; } /** * Methode die aangeroepen wordt bij het klikken op de link na het bevestigen van de * actie. */ protected abstract void onClick(); }
212720_1
package nl.topicus.eduarte.web.components.panels.bottomrow; import nl.topicus.cobra.web.components.panels.bottomrow.AbstractBottomRowButton; import nl.topicus.cobra.web.components.panels.bottomrow.BottomRowPanel; import nl.topicus.cobra.web.components.panels.bottomrow.ButtonAlignment; import nl.topicus.cobra.web.components.shortcut.CobraKeyAction; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.link.Link; /** * Standaard voltooien. Let op: Dit is geen SecureComponent. * * @author loite */ public abstract class VoltooienButton extends AbstractBottomRowButton { private static final long serialVersionUID = 1L; public VoltooienButton(BottomRowPanel bottomRow) { this(bottomRow, "Voltooien"); } public VoltooienButton(BottomRowPanel bottomRow, String label) { super(bottomRow, label, CobraKeyAction.LINKKNOP1, ButtonAlignment.RIGHT); } @Override protected WebMarkupContainer getLink(String linkId) { return new Link<Void>(linkId) { private static final long serialVersionUID = 1L; @Override public void onClick() { VoltooienButton.this.onClick(); } }; } /** * Methode die aangeroepen wordt bij het klikken op de link na het bevestigen van de * actie. */ protected abstract void onClick(); }
topicusonderwijs/tribe-krd-opensource
eduarte/core/src/main/java/nl/topicus/eduarte/web/components/panels/bottomrow/VoltooienButton.java
396
/** * Methode die aangeroepen wordt bij het klikken op de link na het bevestigen van de * actie. */
block_comment
nl
package nl.topicus.eduarte.web.components.panels.bottomrow; import nl.topicus.cobra.web.components.panels.bottomrow.AbstractBottomRowButton; import nl.topicus.cobra.web.components.panels.bottomrow.BottomRowPanel; import nl.topicus.cobra.web.components.panels.bottomrow.ButtonAlignment; import nl.topicus.cobra.web.components.shortcut.CobraKeyAction; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.link.Link; /** * Standaard voltooien. Let op: Dit is geen SecureComponent. * * @author loite */ public abstract class VoltooienButton extends AbstractBottomRowButton { private static final long serialVersionUID = 1L; public VoltooienButton(BottomRowPanel bottomRow) { this(bottomRow, "Voltooien"); } public VoltooienButton(BottomRowPanel bottomRow, String label) { super(bottomRow, label, CobraKeyAction.LINKKNOP1, ButtonAlignment.RIGHT); } @Override protected WebMarkupContainer getLink(String linkId) { return new Link<Void>(linkId) { private static final long serialVersionUID = 1L; @Override public void onClick() { VoltooienButton.this.onClick(); } }; } /** * Methode die aangeroepen<SUF>*/ protected abstract void onClick(); }
212741_7
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Initial Developer of the Original Code is 'Media Competence' * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.connectors.UISconnector.input.products.process; import java.util.*; import org.mmbase.bridge.*; import org.mmbase.util.logging.*; import nl.leocms.connectors.UISconnector.input.products.model.*; import nl.leocms.connectors.UISconnector.input.products.process.Result; import nl.leocms.connectors.UISconnector.shared.properties.model.*; import nl.leocms.connectors.UISconnector.shared.properties.process.PropertyUtil; public class Updater { private static final Logger log = Logging.getLoggerInstance(Updater.class); public static ArrayList update(Cloud cloud, ArrayList arliProducts){ ArrayList arliResult = new ArrayList(); for(Iterator it = arliProducts.iterator(); it.hasNext(); ){ Product product = (Product) it.next(); Result result = new Result(); result.setProduct(product); arliResult.add(result); String sExternID = product.getExternID(); if (sExternID == null){ result.setException(new Exception("ExternID can't be null")); result.setStatus(Result.EXCEPTION); result.setEvenementNode(null); } try{ NodeManager objectNodeManager; /* UIS uses the same object for different types of forms. Something like the following switch could be used to fill the corresponding objects in NatMM. Now the distinction is made on the basis on evenement_type, see below. switch(product.getProductType()){ case Product.PRODUCT_TYPE_EVENT:{ objectNodeManager = cloud.getNodeManager("evenement"); break; } case Product.PRODUCT_TYPE_ITEM:{ objectNodeManager = cloud.getNodeManager("items"); break; } case Product.PRODUCT_TYPE_SUBSCRIPTION:{ objectNodeManager = cloud.getNodeManager("formulier"); break; } default:{ throw new Exception("Unsupported product type"); } } */ objectNodeManager = cloud.getNodeManager("evenement"); Node nodeObject = getObjectNode(objectNodeManager, sExternID); if(nodeObject == null){ //There is no such node in db nodeObject = objectNodeManager.createNode(); result.setStatus(result.ADDED); nodeObject.setStringValue("soort", "parent"); nodeObject.setStringValue("externid", sExternID); nodeObject.setStringValue("begindatum", "" + product.getEmbargoDate().getTime() / 1000); nodeObject.setStringValue("einddatum", "" + product.getExpireDate().getTime() / 1000); nodeObject.setStringValue("isspare", "false"); nodeObject.setStringValue("isoninternet", "true"); nodeObject.setStringValue("iscanceled", "false"); nodeObject.setStringValue("groepsexcursie", "0"); nodeObject.setStringValue("aanmelden_vooraf", "1"); nodeObject.setStringValue("adres_verplicht", "1"); nodeObject.setStringValue("reageer", "0"); nodeObject.setStringValue("min_aantal_deelnemers", "0"); nodeObject.setStringValue("max_aantal_deelnemers", "9999"); // prevent creation of NULL values (NULL and "" are represented the same way) nodeObject.setStringValue("dagomschrijving", ""); nodeObject.setStringValue("status", "-1"); nodeObject.setStringValue("use_verloopdatum", "-1"); nodeObject.setStringValue("achteraf_bevestigen", "-1"); // these values are not used in the agenda.jsp of natmm and the editors nodeObject.setStringValue("begininschrijving", "" + product.getEmbargoDate().getTime() / 1000); nodeObject.setStringValue("eindinschrijving", "" + product.getExpireDate().getTime() / 1000); // workaround use expiredate from UIS as begin and end date of event nodeObject.setStringValue("begindatum", "" + product.getExpireDate().getTime() / 1000); nodeObject.setStringValue("einddatum", "" + product.getExpireDate().getTime() / 1000); // for events of type parent the begindatum == embargo and verloopdatum == enddatum // see nl.leocms.builders.ContenEvenement class nodeObject.setStringValue("embargo", "" + product.getExpireDate().getTime() / 1000); nodeObject.setStringValue("verloopdatum", "" + product.getExpireDate().getTime() / 1000); } else{ //The node is already present result.setStatus(result.UPDATED); } nodeObject.setStringValue("titel", product.getDescription()); nodeObject.commit(); result.setEvenementNode(nodeObject); //Sets price try{ setPrice(cloud, nodeObject, product); } catch(Exception e){ result.setStatus(Result.EXCEPTION); result.setException(e); } //Set payments try{ setPayments(cloud, nodeObject, product); } catch(Exception e){ result.setStatus(Result.EXCEPTION); result.setException(e); } //Set Properties try{ List listProperties = product.getProperties(); PropertyUtil.setProperties(cloud, nodeObject, listProperties); } catch(Exception e){ result.setStatus(Result.EXCEPTION); result.setException(e); } //Set evenement_type try { setEvenementType(cloud, nodeObject, product); } catch(Exception e){ result.setStatus(Result.EXCEPTION); result.setException(e); } } catch(Exception e){ result.setException(e); result.setStatus(Result.EXCEPTION); } } return arliResult; } /** * Tries to find an existing evenement node, * It returns null if there is no such node * * @param cloud Cloud * @param sExternID String * @return Node */ private static Node getObjectNode(NodeManager nodeManager, String sExternID){ NodeList nl = nodeManager.getCloud().getList("", nodeManager.getName(), nodeManager.getName() + ".number", nodeManager.getName() + ".externid='" + sExternID + "'", null, null, null, true); if (nl.size() == 0){ return null; } else{ return nodeManager.getCloud().getNode(nl.getNode(0).getStringValue(nodeManager.getName() + ".number")); } } private static void setPrice(Cloud cloud, Node nodeObject, Product product) throws Exception{ //deletes old relations for(Iterator it = nodeObject.getRelations("posrel", cloud.getNodeManager("deelnemers_categorie")).iterator(); it.hasNext();){ Node nodeRelation = (Node) it.next(); nodeRelation.delete(true); } String sKey; if(product.isMembershipRequired()){ sKey = "Leden"; } else{ sKey = "Niet leden"; } //Looks for a proper category NodeList nl = cloud.getList("", "deelnemers_categorie", "deelnemers_categorie.number,deelnemers_categorie.naam", "deelnemers_categorie.naam='" + sKey + "'", null, null, null, true); try{ Node nodeDeelnemers_categorie = cloud.getNode(nl.getNode(0).getStringValue("deelnemers_categorie.number")); Relation relPosrel = nodeObject.createRelation(nodeDeelnemers_categorie, cloud.getRelationManager("posrel")); relPosrel.setIntValue("pos", new Double(product.getPrice() * 100).intValue()); relPosrel.commit(); } catch(Exception e){ throw new Exception("Node deelnemers_categorie with name=\"" + sKey + "\" can't be found in db:" + e); } return; } private static void setPayments(Cloud cloud, Node nodeObject, Product product) throws Exception{ NodeManager nmPaymentType = cloud.getNodeManager("payment_type"); //deletes old relations for(Iterator it = nodeObject.getRelations("related", nmPaymentType).iterator(); it.hasNext();){ Node nodeRelation = (Node) it.next(); nodeRelation.delete(true); } ArrayList arliPaymentTypes = product.getPaymentTypes(); for(Iterator it = arliPaymentTypes.iterator(); it.hasNext();){ PaymentType paymentType = (PaymentType) it.next(); //Looks for an already existing Node NodeList nl = cloud.getList("", "payment_type", "payment_type.number,payment_type.externid", "payment_type.externid='" + paymentType.getId() + "'", null, null, null, true); Node nodePaymentType; if(nl.size() > 0){ //the Node already exist nodePaymentType = cloud.getNode(nl.getNode(0).getStringValue("payment_type.number")); } else{ //There is no such node nodePaymentType = nmPaymentType.createNode(); nodePaymentType.setStringValue("naam", paymentType.getDescription()); nodePaymentType.setStringValue("externid", paymentType.getId()); nodePaymentType.commit(); } nodeObject.createRelation(nodePaymentType, cloud.getRelationManager("related")).commit(); nodeObject.commit(); } } private static void setEvenementType(Cloud cloud, Node nodeObject, Product product) throws Exception{ NodeManager nmEvenementType = cloud.getNodeManager("evenement_type"); // deletes old relations // for(Iterator it = nodeObject.getRelations("related", nmEvenementType).iterator(); it.hasNext();){ // Node nodeRelation = (Node) it.next(); // nodeRelation.delete(true); // } //Look for an already existing Node NodeList nl = cloud.getList("", "evenement_type", "evenement_type.number,evenement_type.naam", "evenement_type.naam='" + product.getProductTypeName() + "'", null, null, null, true); Node nodeEvenementType; if(nl.size() > 0){ //the Node already exist nodeEvenementType = cloud.getNode(nl.getNode(0).getStringValue("evenement_type.number")); } else{ //There is no such node nodeEvenementType = nmEvenementType.createNode(); switch(product.getProductType()){ case Product.PRODUCT_TYPE_EVENT:{ nodeEvenementType.setStringValue("naam", product.getProductTypeName()); nodeEvenementType.setStringValue("isoninternet", "1"); break; } case Product.PRODUCT_TYPE_ITEM:{ nodeEvenementType.setStringValue("naam", product.getProductTypeName()); nodeEvenementType.setStringValue("isoninternet", "0"); break; } case Product.PRODUCT_TYPE_SUBSCRIPTION:{ nodeEvenementType.setStringValue("naam", product.getProductTypeName()); nodeEvenementType.setStringValue("isoninternet", "0"); break; } default:{ throw new Exception("Unsupported product type"); } } nodeEvenementType.commit(); } nodeObject.createRelation(nodeEvenementType, cloud.getRelationManager("related")).commit(); } }
mmbase/natmm
src/nl/leocms/connectors/UISconnector/input/products/process/Updater.java
3,046
// see nl.leocms.builders.ContenEvenement class
line_comment
nl
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Initial Developer of the Original Code is 'Media Competence' * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.connectors.UISconnector.input.products.process; import java.util.*; import org.mmbase.bridge.*; import org.mmbase.util.logging.*; import nl.leocms.connectors.UISconnector.input.products.model.*; import nl.leocms.connectors.UISconnector.input.products.process.Result; import nl.leocms.connectors.UISconnector.shared.properties.model.*; import nl.leocms.connectors.UISconnector.shared.properties.process.PropertyUtil; public class Updater { private static final Logger log = Logging.getLoggerInstance(Updater.class); public static ArrayList update(Cloud cloud, ArrayList arliProducts){ ArrayList arliResult = new ArrayList(); for(Iterator it = arliProducts.iterator(); it.hasNext(); ){ Product product = (Product) it.next(); Result result = new Result(); result.setProduct(product); arliResult.add(result); String sExternID = product.getExternID(); if (sExternID == null){ result.setException(new Exception("ExternID can't be null")); result.setStatus(Result.EXCEPTION); result.setEvenementNode(null); } try{ NodeManager objectNodeManager; /* UIS uses the same object for different types of forms. Something like the following switch could be used to fill the corresponding objects in NatMM. Now the distinction is made on the basis on evenement_type, see below. switch(product.getProductType()){ case Product.PRODUCT_TYPE_EVENT:{ objectNodeManager = cloud.getNodeManager("evenement"); break; } case Product.PRODUCT_TYPE_ITEM:{ objectNodeManager = cloud.getNodeManager("items"); break; } case Product.PRODUCT_TYPE_SUBSCRIPTION:{ objectNodeManager = cloud.getNodeManager("formulier"); break; } default:{ throw new Exception("Unsupported product type"); } } */ objectNodeManager = cloud.getNodeManager("evenement"); Node nodeObject = getObjectNode(objectNodeManager, sExternID); if(nodeObject == null){ //There is no such node in db nodeObject = objectNodeManager.createNode(); result.setStatus(result.ADDED); nodeObject.setStringValue("soort", "parent"); nodeObject.setStringValue("externid", sExternID); nodeObject.setStringValue("begindatum", "" + product.getEmbargoDate().getTime() / 1000); nodeObject.setStringValue("einddatum", "" + product.getExpireDate().getTime() / 1000); nodeObject.setStringValue("isspare", "false"); nodeObject.setStringValue("isoninternet", "true"); nodeObject.setStringValue("iscanceled", "false"); nodeObject.setStringValue("groepsexcursie", "0"); nodeObject.setStringValue("aanmelden_vooraf", "1"); nodeObject.setStringValue("adres_verplicht", "1"); nodeObject.setStringValue("reageer", "0"); nodeObject.setStringValue("min_aantal_deelnemers", "0"); nodeObject.setStringValue("max_aantal_deelnemers", "9999"); // prevent creation of NULL values (NULL and "" are represented the same way) nodeObject.setStringValue("dagomschrijving", ""); nodeObject.setStringValue("status", "-1"); nodeObject.setStringValue("use_verloopdatum", "-1"); nodeObject.setStringValue("achteraf_bevestigen", "-1"); // these values are not used in the agenda.jsp of natmm and the editors nodeObject.setStringValue("begininschrijving", "" + product.getEmbargoDate().getTime() / 1000); nodeObject.setStringValue("eindinschrijving", "" + product.getExpireDate().getTime() / 1000); // workaround use expiredate from UIS as begin and end date of event nodeObject.setStringValue("begindatum", "" + product.getExpireDate().getTime() / 1000); nodeObject.setStringValue("einddatum", "" + product.getExpireDate().getTime() / 1000); // for events of type parent the begindatum == embargo and verloopdatum == enddatum // see nl.leocms.builders.ContenEvenement<SUF> nodeObject.setStringValue("embargo", "" + product.getExpireDate().getTime() / 1000); nodeObject.setStringValue("verloopdatum", "" + product.getExpireDate().getTime() / 1000); } else{ //The node is already present result.setStatus(result.UPDATED); } nodeObject.setStringValue("titel", product.getDescription()); nodeObject.commit(); result.setEvenementNode(nodeObject); //Sets price try{ setPrice(cloud, nodeObject, product); } catch(Exception e){ result.setStatus(Result.EXCEPTION); result.setException(e); } //Set payments try{ setPayments(cloud, nodeObject, product); } catch(Exception e){ result.setStatus(Result.EXCEPTION); result.setException(e); } //Set Properties try{ List listProperties = product.getProperties(); PropertyUtil.setProperties(cloud, nodeObject, listProperties); } catch(Exception e){ result.setStatus(Result.EXCEPTION); result.setException(e); } //Set evenement_type try { setEvenementType(cloud, nodeObject, product); } catch(Exception e){ result.setStatus(Result.EXCEPTION); result.setException(e); } } catch(Exception e){ result.setException(e); result.setStatus(Result.EXCEPTION); } } return arliResult; } /** * Tries to find an existing evenement node, * It returns null if there is no such node * * @param cloud Cloud * @param sExternID String * @return Node */ private static Node getObjectNode(NodeManager nodeManager, String sExternID){ NodeList nl = nodeManager.getCloud().getList("", nodeManager.getName(), nodeManager.getName() + ".number", nodeManager.getName() + ".externid='" + sExternID + "'", null, null, null, true); if (nl.size() == 0){ return null; } else{ return nodeManager.getCloud().getNode(nl.getNode(0).getStringValue(nodeManager.getName() + ".number")); } } private static void setPrice(Cloud cloud, Node nodeObject, Product product) throws Exception{ //deletes old relations for(Iterator it = nodeObject.getRelations("posrel", cloud.getNodeManager("deelnemers_categorie")).iterator(); it.hasNext();){ Node nodeRelation = (Node) it.next(); nodeRelation.delete(true); } String sKey; if(product.isMembershipRequired()){ sKey = "Leden"; } else{ sKey = "Niet leden"; } //Looks for a proper category NodeList nl = cloud.getList("", "deelnemers_categorie", "deelnemers_categorie.number,deelnemers_categorie.naam", "deelnemers_categorie.naam='" + sKey + "'", null, null, null, true); try{ Node nodeDeelnemers_categorie = cloud.getNode(nl.getNode(0).getStringValue("deelnemers_categorie.number")); Relation relPosrel = nodeObject.createRelation(nodeDeelnemers_categorie, cloud.getRelationManager("posrel")); relPosrel.setIntValue("pos", new Double(product.getPrice() * 100).intValue()); relPosrel.commit(); } catch(Exception e){ throw new Exception("Node deelnemers_categorie with name=\"" + sKey + "\" can't be found in db:" + e); } return; } private static void setPayments(Cloud cloud, Node nodeObject, Product product) throws Exception{ NodeManager nmPaymentType = cloud.getNodeManager("payment_type"); //deletes old relations for(Iterator it = nodeObject.getRelations("related", nmPaymentType).iterator(); it.hasNext();){ Node nodeRelation = (Node) it.next(); nodeRelation.delete(true); } ArrayList arliPaymentTypes = product.getPaymentTypes(); for(Iterator it = arliPaymentTypes.iterator(); it.hasNext();){ PaymentType paymentType = (PaymentType) it.next(); //Looks for an already existing Node NodeList nl = cloud.getList("", "payment_type", "payment_type.number,payment_type.externid", "payment_type.externid='" + paymentType.getId() + "'", null, null, null, true); Node nodePaymentType; if(nl.size() > 0){ //the Node already exist nodePaymentType = cloud.getNode(nl.getNode(0).getStringValue("payment_type.number")); } else{ //There is no such node nodePaymentType = nmPaymentType.createNode(); nodePaymentType.setStringValue("naam", paymentType.getDescription()); nodePaymentType.setStringValue("externid", paymentType.getId()); nodePaymentType.commit(); } nodeObject.createRelation(nodePaymentType, cloud.getRelationManager("related")).commit(); nodeObject.commit(); } } private static void setEvenementType(Cloud cloud, Node nodeObject, Product product) throws Exception{ NodeManager nmEvenementType = cloud.getNodeManager("evenement_type"); // deletes old relations // for(Iterator it = nodeObject.getRelations("related", nmEvenementType).iterator(); it.hasNext();){ // Node nodeRelation = (Node) it.next(); // nodeRelation.delete(true); // } //Look for an already existing Node NodeList nl = cloud.getList("", "evenement_type", "evenement_type.number,evenement_type.naam", "evenement_type.naam='" + product.getProductTypeName() + "'", null, null, null, true); Node nodeEvenementType; if(nl.size() > 0){ //the Node already exist nodeEvenementType = cloud.getNode(nl.getNode(0).getStringValue("evenement_type.number")); } else{ //There is no such node nodeEvenementType = nmEvenementType.createNode(); switch(product.getProductType()){ case Product.PRODUCT_TYPE_EVENT:{ nodeEvenementType.setStringValue("naam", product.getProductTypeName()); nodeEvenementType.setStringValue("isoninternet", "1"); break; } case Product.PRODUCT_TYPE_ITEM:{ nodeEvenementType.setStringValue("naam", product.getProductTypeName()); nodeEvenementType.setStringValue("isoninternet", "0"); break; } case Product.PRODUCT_TYPE_SUBSCRIPTION:{ nodeEvenementType.setStringValue("naam", product.getProductTypeName()); nodeEvenementType.setStringValue("isoninternet", "0"); break; } default:{ throw new Exception("Unsupported product type"); } } nodeEvenementType.commit(); } nodeObject.createRelation(nodeEvenementType, cloud.getRelationManager("related")).commit(); } }
212751_0
package com.example.sanjiv.awarenessapp; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class Login extends AppCompatActivity implements View.OnClickListener { private static final int RC_SIGN_IN = 234; private static final String TAG = "LOGIN"; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private DatabaseReference databaseReference; private GoogleApiClient mGoogleApiClient; private FirebaseDatabase mDatabase; private GoogleSignInClient mGoogleSignInClient; private EditText emailInput, passwordInput; private Button normalLogin, googleLogin, confirmLogin; private TextView passwordForgot, registerAccount, toLogin; private ProgressDialog progressDialog; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); normalLogin = findViewById(R.id.btnEmployee); googleLogin = findViewById(R.id.btnGuest); emailInput = findViewById(R.id.loginUsername); passwordInput = findViewById(R.id.loginPassword); confirmLogin = findViewById(R.id.btnConfirm); passwordForgot= findViewById(R.id.forgotPassword); registerAccount = findViewById(R.id.registerAccount); toLogin = findViewById(R.id.toLogin); progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); databaseReference = FirebaseDatabase.getInstance().getReference("users"); mDatabase = FirebaseDatabase.getInstance(); mAuth = FirebaseAuth.getInstance(); //Auto generated GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.CLIENT_TAG_ID)) .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(this,gso); normalLogin.setOnClickListener(this); googleLogin.setOnClickListener(this); confirmLogin.setOnClickListener(this); registerAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Registration.class); startActivity(intent); } }); passwordForgot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, ResetPage.class); startActivity(intent); } }); toLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Login.class); startActivity(intent); } }); } //Check bij start of gebruiker al is ingelogd protected void onStart() { super.onStart(); mAuth = FirebaseAuth.getInstance(); if(mAuth.getCurrentUser() != null){ finish(); startActivity(new Intent(this, MainActivity.class)); } } //Login voor google private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { Log.w(TAG, "Google sign in failed", e); Toast.makeText(Login.this,e.getMessage(), Toast.LENGTH_SHORT).show(); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); progressDialog.setMessage("Bezig met inloggen"); progressDialog.show(); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); UserModel userModel = new UserModel("guest"); mDatabase.getReference("users").child(user.getUid()).child("rollen").setValue(userModel); finish(); startActivity(new Intent(Login.this, MainActivity.class)); Toast.makeText(Login.this,"Welkom!", Toast.LENGTH_SHORT).show(); } else { Log.w(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(Login.this,"Auth failed", Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); // ... } }); } public AlertDialog employeeCheckWithDialog(){ AlertDialog.Builder alert = new AlertDialog.Builder(Login.this); final EditText edittext = new EditText(Login.this); alert.setMessage("Voer de employee bevestiging code in"); alert.setTitle("Employee Code"); alert.setView(edittext); alert.setPositiveButton("Bevestigen", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String code = edittext.getText().toString(); if(code.equalsIgnoreCase("123")){ enableEmployeeLogin(); } } }); alert.setNegativeButton("Annuleren", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); return alert.create(); } private void enableEmployeeLogin(){ emailInput.setVisibility(View.VISIBLE); passwordInput.setVisibility(View.VISIBLE); confirmLogin.setVisibility(View.VISIBLE); normalLogin.setVisibility(View.GONE); googleLogin.setVisibility(View.GONE); passwordForgot.setVisibility(View.VISIBLE); registerAccount.setVisibility(View.VISIBLE); toLogin.setVisibility(View.VISIBLE); } private void signInNormal() { String email = emailInput.getText().toString().trim(); String password = passwordInput.getText().toString().trim(); if (TextUtils.isEmpty(email)) { Toast.makeText(this, "Emailadres veld is leeg !", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(this, "Wachtwoord veld is leeg !", Toast.LENGTH_SHORT).show(); return; } if (password.length() < 6) { Toast.makeText(this, "Wachtwoord is minimaal 6 tekens!", Toast.LENGTH_SHORT).show(); return; } progressDialog.setMessage("Bezig met inloggen"); progressDialog.show(); mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseUser user = mAuth.getCurrentUser(); UserModel userModel = new UserModel("admin"); mDatabase.getReference("users").child(user.getUid()).child("rollen").setValue(userModel); Intent intent = new Intent(Login.this, MainActivity.class); startActivity(intent); Toast.makeText(Login.this, "Welkom!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(Login.this, "Inloggen mislukt, check uw gegevens!", Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); } }); } public void onBackPressed() { finish(); } @Override public void onClick(View v) { if (v == normalLogin) { AlertDialog dialog = employeeCheckWithDialog(); dialog.show(); } if (v == googleLogin) { signIn(); } if(v == confirmLogin){ signInNormal(); } } }
Sannijiv/AwarenessApp
app/src/main/java/com/example/sanjiv/awarenessapp/Login.java
2,301
//Check bij start of gebruiker al is ingelogd
line_comment
nl
package com.example.sanjiv.awarenessapp; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class Login extends AppCompatActivity implements View.OnClickListener { private static final int RC_SIGN_IN = 234; private static final String TAG = "LOGIN"; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private DatabaseReference databaseReference; private GoogleApiClient mGoogleApiClient; private FirebaseDatabase mDatabase; private GoogleSignInClient mGoogleSignInClient; private EditText emailInput, passwordInput; private Button normalLogin, googleLogin, confirmLogin; private TextView passwordForgot, registerAccount, toLogin; private ProgressDialog progressDialog; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); normalLogin = findViewById(R.id.btnEmployee); googleLogin = findViewById(R.id.btnGuest); emailInput = findViewById(R.id.loginUsername); passwordInput = findViewById(R.id.loginPassword); confirmLogin = findViewById(R.id.btnConfirm); passwordForgot= findViewById(R.id.forgotPassword); registerAccount = findViewById(R.id.registerAccount); toLogin = findViewById(R.id.toLogin); progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); databaseReference = FirebaseDatabase.getInstance().getReference("users"); mDatabase = FirebaseDatabase.getInstance(); mAuth = FirebaseAuth.getInstance(); //Auto generated GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.CLIENT_TAG_ID)) .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(this,gso); normalLogin.setOnClickListener(this); googleLogin.setOnClickListener(this); confirmLogin.setOnClickListener(this); registerAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Registration.class); startActivity(intent); } }); passwordForgot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, ResetPage.class); startActivity(intent); } }); toLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Login.class); startActivity(intent); } }); } //Check bij<SUF> protected void onStart() { super.onStart(); mAuth = FirebaseAuth.getInstance(); if(mAuth.getCurrentUser() != null){ finish(); startActivity(new Intent(this, MainActivity.class)); } } //Login voor google private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { Log.w(TAG, "Google sign in failed", e); Toast.makeText(Login.this,e.getMessage(), Toast.LENGTH_SHORT).show(); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); progressDialog.setMessage("Bezig met inloggen"); progressDialog.show(); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); UserModel userModel = new UserModel("guest"); mDatabase.getReference("users").child(user.getUid()).child("rollen").setValue(userModel); finish(); startActivity(new Intent(Login.this, MainActivity.class)); Toast.makeText(Login.this,"Welkom!", Toast.LENGTH_SHORT).show(); } else { Log.w(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(Login.this,"Auth failed", Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); // ... } }); } public AlertDialog employeeCheckWithDialog(){ AlertDialog.Builder alert = new AlertDialog.Builder(Login.this); final EditText edittext = new EditText(Login.this); alert.setMessage("Voer de employee bevestiging code in"); alert.setTitle("Employee Code"); alert.setView(edittext); alert.setPositiveButton("Bevestigen", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String code = edittext.getText().toString(); if(code.equalsIgnoreCase("123")){ enableEmployeeLogin(); } } }); alert.setNegativeButton("Annuleren", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); return alert.create(); } private void enableEmployeeLogin(){ emailInput.setVisibility(View.VISIBLE); passwordInput.setVisibility(View.VISIBLE); confirmLogin.setVisibility(View.VISIBLE); normalLogin.setVisibility(View.GONE); googleLogin.setVisibility(View.GONE); passwordForgot.setVisibility(View.VISIBLE); registerAccount.setVisibility(View.VISIBLE); toLogin.setVisibility(View.VISIBLE); } private void signInNormal() { String email = emailInput.getText().toString().trim(); String password = passwordInput.getText().toString().trim(); if (TextUtils.isEmpty(email)) { Toast.makeText(this, "Emailadres veld is leeg !", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(this, "Wachtwoord veld is leeg !", Toast.LENGTH_SHORT).show(); return; } if (password.length() < 6) { Toast.makeText(this, "Wachtwoord is minimaal 6 tekens!", Toast.LENGTH_SHORT).show(); return; } progressDialog.setMessage("Bezig met inloggen"); progressDialog.show(); mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseUser user = mAuth.getCurrentUser(); UserModel userModel = new UserModel("admin"); mDatabase.getReference("users").child(user.getUid()).child("rollen").setValue(userModel); Intent intent = new Intent(Login.this, MainActivity.class); startActivity(intent); Toast.makeText(Login.this, "Welkom!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(Login.this, "Inloggen mislukt, check uw gegevens!", Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); } }); } public void onBackPressed() { finish(); } @Override public void onClick(View v) { if (v == normalLogin) { AlertDialog dialog = employeeCheckWithDialog(); dialog.show(); } if (v == googleLogin) { signIn(); } if(v == confirmLogin){ signInNormal(); } } }
212751_1
package com.example.sanjiv.awarenessapp; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class Login extends AppCompatActivity implements View.OnClickListener { private static final int RC_SIGN_IN = 234; private static final String TAG = "LOGIN"; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private DatabaseReference databaseReference; private GoogleApiClient mGoogleApiClient; private FirebaseDatabase mDatabase; private GoogleSignInClient mGoogleSignInClient; private EditText emailInput, passwordInput; private Button normalLogin, googleLogin, confirmLogin; private TextView passwordForgot, registerAccount, toLogin; private ProgressDialog progressDialog; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); normalLogin = findViewById(R.id.btnEmployee); googleLogin = findViewById(R.id.btnGuest); emailInput = findViewById(R.id.loginUsername); passwordInput = findViewById(R.id.loginPassword); confirmLogin = findViewById(R.id.btnConfirm); passwordForgot= findViewById(R.id.forgotPassword); registerAccount = findViewById(R.id.registerAccount); toLogin = findViewById(R.id.toLogin); progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); databaseReference = FirebaseDatabase.getInstance().getReference("users"); mDatabase = FirebaseDatabase.getInstance(); mAuth = FirebaseAuth.getInstance(); //Auto generated GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.CLIENT_TAG_ID)) .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(this,gso); normalLogin.setOnClickListener(this); googleLogin.setOnClickListener(this); confirmLogin.setOnClickListener(this); registerAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Registration.class); startActivity(intent); } }); passwordForgot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, ResetPage.class); startActivity(intent); } }); toLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Login.class); startActivity(intent); } }); } //Check bij start of gebruiker al is ingelogd protected void onStart() { super.onStart(); mAuth = FirebaseAuth.getInstance(); if(mAuth.getCurrentUser() != null){ finish(); startActivity(new Intent(this, MainActivity.class)); } } //Login voor google private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { Log.w(TAG, "Google sign in failed", e); Toast.makeText(Login.this,e.getMessage(), Toast.LENGTH_SHORT).show(); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); progressDialog.setMessage("Bezig met inloggen"); progressDialog.show(); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); UserModel userModel = new UserModel("guest"); mDatabase.getReference("users").child(user.getUid()).child("rollen").setValue(userModel); finish(); startActivity(new Intent(Login.this, MainActivity.class)); Toast.makeText(Login.this,"Welkom!", Toast.LENGTH_SHORT).show(); } else { Log.w(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(Login.this,"Auth failed", Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); // ... } }); } public AlertDialog employeeCheckWithDialog(){ AlertDialog.Builder alert = new AlertDialog.Builder(Login.this); final EditText edittext = new EditText(Login.this); alert.setMessage("Voer de employee bevestiging code in"); alert.setTitle("Employee Code"); alert.setView(edittext); alert.setPositiveButton("Bevestigen", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String code = edittext.getText().toString(); if(code.equalsIgnoreCase("123")){ enableEmployeeLogin(); } } }); alert.setNegativeButton("Annuleren", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); return alert.create(); } private void enableEmployeeLogin(){ emailInput.setVisibility(View.VISIBLE); passwordInput.setVisibility(View.VISIBLE); confirmLogin.setVisibility(View.VISIBLE); normalLogin.setVisibility(View.GONE); googleLogin.setVisibility(View.GONE); passwordForgot.setVisibility(View.VISIBLE); registerAccount.setVisibility(View.VISIBLE); toLogin.setVisibility(View.VISIBLE); } private void signInNormal() { String email = emailInput.getText().toString().trim(); String password = passwordInput.getText().toString().trim(); if (TextUtils.isEmpty(email)) { Toast.makeText(this, "Emailadres veld is leeg !", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(this, "Wachtwoord veld is leeg !", Toast.LENGTH_SHORT).show(); return; } if (password.length() < 6) { Toast.makeText(this, "Wachtwoord is minimaal 6 tekens!", Toast.LENGTH_SHORT).show(); return; } progressDialog.setMessage("Bezig met inloggen"); progressDialog.show(); mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseUser user = mAuth.getCurrentUser(); UserModel userModel = new UserModel("admin"); mDatabase.getReference("users").child(user.getUid()).child("rollen").setValue(userModel); Intent intent = new Intent(Login.this, MainActivity.class); startActivity(intent); Toast.makeText(Login.this, "Welkom!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(Login.this, "Inloggen mislukt, check uw gegevens!", Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); } }); } public void onBackPressed() { finish(); } @Override public void onClick(View v) { if (v == normalLogin) { AlertDialog dialog = employeeCheckWithDialog(); dialog.show(); } if (v == googleLogin) { signIn(); } if(v == confirmLogin){ signInNormal(); } } }
Sannijiv/AwarenessApp
app/src/main/java/com/example/sanjiv/awarenessapp/Login.java
2,301
//Login voor google
line_comment
nl
package com.example.sanjiv.awarenessapp; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class Login extends AppCompatActivity implements View.OnClickListener { private static final int RC_SIGN_IN = 234; private static final String TAG = "LOGIN"; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private DatabaseReference databaseReference; private GoogleApiClient mGoogleApiClient; private FirebaseDatabase mDatabase; private GoogleSignInClient mGoogleSignInClient; private EditText emailInput, passwordInput; private Button normalLogin, googleLogin, confirmLogin; private TextView passwordForgot, registerAccount, toLogin; private ProgressDialog progressDialog; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); normalLogin = findViewById(R.id.btnEmployee); googleLogin = findViewById(R.id.btnGuest); emailInput = findViewById(R.id.loginUsername); passwordInput = findViewById(R.id.loginPassword); confirmLogin = findViewById(R.id.btnConfirm); passwordForgot= findViewById(R.id.forgotPassword); registerAccount = findViewById(R.id.registerAccount); toLogin = findViewById(R.id.toLogin); progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); databaseReference = FirebaseDatabase.getInstance().getReference("users"); mDatabase = FirebaseDatabase.getInstance(); mAuth = FirebaseAuth.getInstance(); //Auto generated GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.CLIENT_TAG_ID)) .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(this,gso); normalLogin.setOnClickListener(this); googleLogin.setOnClickListener(this); confirmLogin.setOnClickListener(this); registerAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Registration.class); startActivity(intent); } }); passwordForgot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, ResetPage.class); startActivity(intent); } }); toLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Login.class); startActivity(intent); } }); } //Check bij start of gebruiker al is ingelogd protected void onStart() { super.onStart(); mAuth = FirebaseAuth.getInstance(); if(mAuth.getCurrentUser() != null){ finish(); startActivity(new Intent(this, MainActivity.class)); } } //Login voor<SUF> private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { Log.w(TAG, "Google sign in failed", e); Toast.makeText(Login.this,e.getMessage(), Toast.LENGTH_SHORT).show(); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); progressDialog.setMessage("Bezig met inloggen"); progressDialog.show(); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); UserModel userModel = new UserModel("guest"); mDatabase.getReference("users").child(user.getUid()).child("rollen").setValue(userModel); finish(); startActivity(new Intent(Login.this, MainActivity.class)); Toast.makeText(Login.this,"Welkom!", Toast.LENGTH_SHORT).show(); } else { Log.w(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(Login.this,"Auth failed", Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); // ... } }); } public AlertDialog employeeCheckWithDialog(){ AlertDialog.Builder alert = new AlertDialog.Builder(Login.this); final EditText edittext = new EditText(Login.this); alert.setMessage("Voer de employee bevestiging code in"); alert.setTitle("Employee Code"); alert.setView(edittext); alert.setPositiveButton("Bevestigen", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String code = edittext.getText().toString(); if(code.equalsIgnoreCase("123")){ enableEmployeeLogin(); } } }); alert.setNegativeButton("Annuleren", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); return alert.create(); } private void enableEmployeeLogin(){ emailInput.setVisibility(View.VISIBLE); passwordInput.setVisibility(View.VISIBLE); confirmLogin.setVisibility(View.VISIBLE); normalLogin.setVisibility(View.GONE); googleLogin.setVisibility(View.GONE); passwordForgot.setVisibility(View.VISIBLE); registerAccount.setVisibility(View.VISIBLE); toLogin.setVisibility(View.VISIBLE); } private void signInNormal() { String email = emailInput.getText().toString().trim(); String password = passwordInput.getText().toString().trim(); if (TextUtils.isEmpty(email)) { Toast.makeText(this, "Emailadres veld is leeg !", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(this, "Wachtwoord veld is leeg !", Toast.LENGTH_SHORT).show(); return; } if (password.length() < 6) { Toast.makeText(this, "Wachtwoord is minimaal 6 tekens!", Toast.LENGTH_SHORT).show(); return; } progressDialog.setMessage("Bezig met inloggen"); progressDialog.show(); mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseUser user = mAuth.getCurrentUser(); UserModel userModel = new UserModel("admin"); mDatabase.getReference("users").child(user.getUid()).child("rollen").setValue(userModel); Intent intent = new Intent(Login.this, MainActivity.class); startActivity(intent); Toast.makeText(Login.this, "Welkom!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(Login.this, "Inloggen mislukt, check uw gegevens!", Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); } }); } public void onBackPressed() { finish(); } @Override public void onClick(View v) { if (v == normalLogin) { AlertDialog dialog = employeeCheckWithDialog(); dialog.show(); } if (v == googleLogin) { signIn(); } if(v == confirmLogin){ signInNormal(); } } }
212759_20
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { JLabel infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(14, 278, 700, 350)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(getMijnTabbladenPanel(), null); jContentPane.add(infoLabel, null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab events private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweReguliereStudent(student, opleiding); studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab events private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student info private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
DreamEmulator/ou_java
advanced_object_oriented_programming/opdracht_01/src/studentenadmingui/StudentenAdministratieFrame.java
3,973
// Nieuwe student-tab events
line_comment
nl
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { JLabel infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(14, 278, 700, 350)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(getMijnTabbladenPanel(), null); jContentPane.add(infoLabel, null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab<SUF> private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweReguliereStudent(student, opleiding); studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab events private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student info private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
212759_21
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { JLabel infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(14, 278, 700, 350)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(getMijnTabbladenPanel(), null); jContentPane.add(infoLabel, null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab events private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweReguliereStudent(student, opleiding); studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab events private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student info private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
DreamEmulator/ou_java
advanced_object_oriented_programming/opdracht_01/src/studentenadmingui/StudentenAdministratieFrame.java
3,973
// Nieuwe scholer-tab events
line_comment
nl
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { JLabel infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(14, 278, 700, 350)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(getMijnTabbladenPanel(), null); jContentPane.add(infoLabel, null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab events private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweReguliereStudent(student, opleiding); studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab<SUF> private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student info private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
212759_22
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { JLabel infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(14, 278, 700, 350)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(getMijnTabbladenPanel(), null); jContentPane.add(infoLabel, null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab events private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweReguliereStudent(student, opleiding); studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab events private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student info private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
DreamEmulator/ou_java
advanced_object_oriented_programming/opdracht_01/src/studentenadmingui/StudentenAdministratieFrame.java
3,973
// Toon student info
line_comment
nl
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { JLabel infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(14, 278, 700, 350)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(getMijnTabbladenPanel(), null); jContentPane.add(infoLabel, null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab events private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweReguliereStudent(student, opleiding); studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab events private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student<SUF> private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
212761_20
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox<String> opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox<String> scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; private JLabel infoLabel = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(35, 370, 700, 50)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(infoLabel, null); jContentPane.add(getMijnTabbladenPanel(), null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox<String> getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox<String>(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox<String> getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox<>(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab events private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { infoLabel.setText(""); String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); try { studentenAdministratie.nieuweReguliereStudent(student, opleiding); } catch (StudentAdminException err){ infoLabel.setText(err.message); } studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab events private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); try { studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); } catch (StudentAdminException err){ infoLabel.setText(err.message); } scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student info private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } catch (NumberFormatException err){ infoLabel.setText("Let op: voer alleen cijfers in als punten"); } try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); } catch (StudentAdminException err){ infoLabel.setText(err.message); } try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
DreamEmulator/ou_java
advanced_object_oriented_programming/opdracht_02/src/studentenadmingui/StudentenAdministratieFrame.java
4,261
// Nieuwe student-tab events
line_comment
nl
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox<String> opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox<String> scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; private JLabel infoLabel = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(35, 370, 700, 50)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(infoLabel, null); jContentPane.add(getMijnTabbladenPanel(), null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox<String> getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox<String>(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox<String> getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox<>(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab<SUF> private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { infoLabel.setText(""); String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); try { studentenAdministratie.nieuweReguliereStudent(student, opleiding); } catch (StudentAdminException err){ infoLabel.setText(err.message); } studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab events private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); try { studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); } catch (StudentAdminException err){ infoLabel.setText(err.message); } scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student info private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } catch (NumberFormatException err){ infoLabel.setText("Let op: voer alleen cijfers in als punten"); } try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); } catch (StudentAdminException err){ infoLabel.setText(err.message); } try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
212761_21
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox<String> opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox<String> scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; private JLabel infoLabel = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(35, 370, 700, 50)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(infoLabel, null); jContentPane.add(getMijnTabbladenPanel(), null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox<String> getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox<String>(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox<String> getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox<>(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab events private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { infoLabel.setText(""); String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); try { studentenAdministratie.nieuweReguliereStudent(student, opleiding); } catch (StudentAdminException err){ infoLabel.setText(err.message); } studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab events private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); try { studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); } catch (StudentAdminException err){ infoLabel.setText(err.message); } scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student info private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } catch (NumberFormatException err){ infoLabel.setText("Let op: voer alleen cijfers in als punten"); } try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); } catch (StudentAdminException err){ infoLabel.setText(err.message); } try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
DreamEmulator/ou_java
advanced_object_oriented_programming/opdracht_02/src/studentenadmingui/StudentenAdministratieFrame.java
4,261
// Nieuwe scholer-tab events
line_comment
nl
package studentenadmingui; import studentenadmin.*; import javax.swing.*; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Objects; public class StudentenAdministratieFrame extends JFrame { private final StudentenAdministratie studentenAdministratie; private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea uitvoerGebied = null; private JButton toonAlleKnop = null; private JTabbedPane mijnTabbladenPanel = null; private JPanel voegStudenttoePanel = null; private JPanel voegScholertoePanel = null; private JPanel studentPanel = null; private JPanel alleStudentenPanel = null; private JTextField bestaandeNaamVeld = null; private JTextField studentInfoVeld = null; private JTextField puntenVeld = null; private JButton moduleKnop = null; private JComboBox<String> opleidingComboBox = null; private JTextField studentTextField = null; private JButton studentButton = null; private JComboBox<String> scholingComboBox = null; private JTextField scholerTextField = null; private JButton scholerButton = null; private JLabel infoLabel = null; /** * This is the default constructor */ public StudentenAdministratieFrame(StudentenAdministratie studentenAdministratie) { super(); this.studentenAdministratie = studentenAdministratie; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(850, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(getJContentPane()); this.setTitle("StudentAdministratie"); this.setVisible(true); bindEvents(); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { infoLabel = new JLabel(); infoLabel.setBounds(new Rectangle(35, 370, 700, 50)); infoLabel.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(infoLabel, null); jContentPane.add(getMijnTabbladenPanel(), null); } return jContentPane; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(6, 65, 682, 180)); jScrollPane.setViewportView(getUitvoerGebied()); } return jScrollPane; } /** * This method initializes uitvoerGebied * * @return javax.swing.JTextArea */ private JTextArea getUitvoerGebied() { if (uitvoerGebied == null) { uitvoerGebied = new JTextArea(); uitvoerGebied.setEditable(false); } return uitvoerGebied; } /** * This method initializes toonAlleKnop * * @return javax.swing.JButton */ private JButton getToonAlleKnop() { if (toonAlleKnop == null) { toonAlleKnop = new JButton(); toonAlleKnop.setText("Toon alle studenten"); toonAlleKnop.setBounds(new Rectangle(11, 8, 147, 20)); } return toonAlleKnop; } /** * This method initializes mijnTabbladenPanel * * @return javax.swing.JTabbedPane */ private JTabbedPane getMijnTabbladenPanel() { if (mijnTabbladenPanel == null) { mijnTabbladenPanel = new JTabbedPane(); mijnTabbladenPanel.setBounds(new Rectangle(13, 19, 800, 400)); mijnTabbladenPanel.addTab("nieuwe student", null, getVoegStudenttoePanel(), null); mijnTabbladenPanel.addTab("nieuwe scholer", null, getVoegScholertoePanel(), null); mijnTabbladenPanel.addTab("studentinfo", null, getStudentPanel(), null); mijnTabbladenPanel.addTab("alle studenten", null, getAlleStudentenPanel(), null); } return mijnTabbladenPanel; } /** * This method initializes voegStudenttoePanel * * @return javax.swing.JPanel */ private JPanel getVoegStudenttoePanel() { if (voegStudenttoePanel == null) { JLabel studentLabel = new JLabel(); studentLabel.setBounds(new Rectangle(15, 55, 91, 24)); studentLabel.setText("Naam student"); JLabel nstudentLabel = new JLabel(); nstudentLabel.setBounds(new Rectangle(16, 16, 146, 24)); nstudentLabel.setText("Selecteer een opleiding"); voegStudenttoePanel = new JPanel(); voegStudenttoePanel.setLayout(null); voegStudenttoePanel.add(nstudentLabel, null); voegStudenttoePanel.add(getOpleidingComboBox(), null); voegStudenttoePanel.add(studentLabel, null); voegStudenttoePanel.add(getStudentTextField(), null); voegStudenttoePanel.add(getStudentButton(), null); } return voegStudenttoePanel; } private JPanel getVoegScholertoePanel() { if (voegScholertoePanel == null) { JLabel scholerLabel = new JLabel(); scholerLabel.setBounds(new Rectangle(16, 54, 116, 25)); scholerLabel.setText("Naam scholer"); JLabel opleidingLabel = new JLabel(); opleidingLabel.setBounds(new Rectangle(16, 16, 173, 25)); opleidingLabel.setText("Selecteer een CPP-Opleiding"); voegScholertoePanel = new JPanel(); voegScholertoePanel.setLayout(null); voegScholertoePanel.add(opleidingLabel, null); voegScholertoePanel.add(getScholingComboBox(), null); voegScholertoePanel.add(scholerLabel, null); voegScholertoePanel.add(getScholerTextField(), null); voegScholertoePanel.add(getScholerButton(), null); } return voegScholertoePanel; } /** * This method initializes studentPanel * * @return javax.swing.JPanel */ private JPanel getStudentPanel() { if (studentPanel == null) { JLabel uitlegLabel = new JLabel(); uitlegLabel.setBounds(new Rectangle(16, 8, 334, 19)); uitlegLabel.setText("Geef enter om invoer te bevestigen"); JLabel nieuwepuntenLabel = new JLabel(); nieuwepuntenLabel.setBounds(new Rectangle(14, 63, 296, 20)); nieuwepuntenLabel.setText("Punten behaald (alleen reguliere opleiding) "); JLabel bestaandenaamLabel = new JLabel(); bestaandenaamLabel.setBounds(new Rectangle(14, 35, 86, 20)); bestaandenaamLabel.setText("Studentnaam"); studentPanel = new JPanel(); studentPanel.setLayout(null); studentPanel.add(bestaandenaamLabel, null); studentPanel.add(getBestaandeNaamVeld(), null); studentPanel.add(getStudentInfoVeld(), null); studentPanel.add(nieuwepuntenLabel, null); studentPanel.add(getPuntenVeld(), null); studentPanel.add(uitlegLabel, null); studentPanel.add(getModuleKnop(), null); } return studentPanel; } /** * This method initializes alleStudentenPanel * * @return javax.swing.JPanel */ private JPanel getAlleStudentenPanel() { if (alleStudentenPanel == null) { alleStudentenPanel = new JPanel(); alleStudentenPanel.setLayout(null); alleStudentenPanel.add(getToonAlleKnop(), null); alleStudentenPanel.add(getJScrollPane(), null); } return alleStudentenPanel; } /** * This method initializes bestaandeNaamVeld * * @return javax.swing.JTextField */ private JTextField getBestaandeNaamVeld() { if (bestaandeNaamVeld == null) { bestaandeNaamVeld = new JTextField(); bestaandeNaamVeld.setBounds(new Rectangle(114, 36, 151, 20)); } return bestaandeNaamVeld; } /** * This method initializes studentInfoVeld * * @return javax.swing.JTextField */ private JTextField getStudentInfoVeld() { if (studentInfoVeld == null) { studentInfoVeld = new JTextField(); studentInfoVeld.setBounds(new Rectangle(10, 152, 592, 27)); studentInfoVeld.setEditable(false); } return studentInfoVeld; } /** * This method initializes puntenVeld * * @return javax.swing.JTextField */ private JTextField getPuntenVeld() { if (puntenVeld == null) { puntenVeld = new JTextField(); puntenVeld.setBounds(new Rectangle(284, 63, 47, 20)); } return puntenVeld; } /** * This method initializes moduleKnop * * @return javax.swing.JButton */ private JButton getModuleKnop() { if (moduleKnop == null) { moduleKnop = new JButton(); moduleKnop.setBounds(new Rectangle(14, 91, 328, 21)); moduleKnop.setText("Module behaald (alleen CPP)"); } return moduleKnop; } /** * This method initializes opleidingComboBox * * @return javax.swing.JComboBox */ private JComboBox<String> getOpleidingComboBox() { if (opleidingComboBox == null) { opleidingComboBox = new JComboBox<String>(); opleidingComboBox.setBounds(new Rectangle(195, 16, 200, 24)); } return opleidingComboBox; } /** * This method initializes studentTextField * * @return javax.swing.JTextField */ private JTextField getStudentTextField() { if (studentTextField == null) { studentTextField = new JTextField(); studentTextField.setBounds(new Rectangle(195, 55, 197, 24)); } return studentTextField; } /** * This method initializes studentButton * * @return javax.swing.JButton */ private JButton getStudentButton() { if (studentButton == null) { studentButton = new JButton(); studentButton.setBounds(new Rectangle(15, 106, 153, 24)); studentButton.setText("Voeg student toe"); } return studentButton; } /** * This method initializes scholingComboBox * * @return javax.swing.JComboBox */ private JComboBox<String> getScholingComboBox() { if (scholingComboBox == null) { scholingComboBox = new JComboBox<>(); scholingComboBox.setBounds(new Rectangle(210, 16, 167, 25)); } return scholingComboBox; } /** * This method initializes scholerTextField * * @return javax.swing.JTextField */ private JTextField getScholerTextField() { if (scholerTextField == null) { scholerTextField = new JTextField(); scholerTextField.setBounds(new Rectangle(210, 54, 166, 25)); } return scholerTextField; } /** * This method initializes scholerButton * * @return javax.swing.JButton */ private JButton getScholerButton() { if (scholerButton == null) { scholerButton = new JButton(); scholerButton.setBounds(new Rectangle(14, 103, 163, 25)); scholerButton.setText("Voeg scholer toe"); } return scholerButton; } // Bind events private void bindEvents() { // Nieuwe student-tab populateStudentCombobox(); bindVoegStudentToeButton(); // Nieuwe scholer-tab populateScholerCombobox(); bindVoegScholerToeButton(); // Studentinfo-tab bindNaamEnter(); bindPuntenEnter(); bindModuleEnter(); // Alle studenten-tab bindToonAlleKnop(); } // Nieuwe student-tab events private void populateStudentCombobox() { for (String opleiding : studentenAdministratie.getOpleidingenList()) { opleidingComboBox.addItem(opleiding); } } private void bindVoegStudentToeButton() { studentButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { infoLabel.setText(""); String student = studentTextField.getText(); String opleiding = Objects.requireNonNull(opleidingComboBox.getSelectedItem()).toString(); try { studentenAdministratie.nieuweReguliereStudent(student, opleiding); } catch (StudentAdminException err){ infoLabel.setText(err.message); } studentTextField.setText(""); opleidingComboBox.setSelectedIndex(0); } }); } // Nieuwe scholer-tab<SUF> private void populateScholerCombobox() { for (String cpp : studentenAdministratie.getCppList()) { scholingComboBox.addItem(cpp); } } private void bindVoegScholerToeButton() { scholerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); String cppStudent = scholerTextField.getText(); String cpp = Objects.requireNonNull(scholingComboBox.getSelectedItem()).toString(); try { studentenAdministratie.nieuweCPPScholer(cppStudent, cpp); } catch (StudentAdminException err){ infoLabel.setText(err.message); } scholerTextField.setText(""); scholingComboBox.setSelectedIndex(0); } }); } // Toon student info private void bindNaamEnter() { bestaandeNaamVeld.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // Reguliere student private void bindPuntenEnter() { puntenVeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentenAdministratie.verhoogPunten(bestaandeNaamVeld.getText(),Double.parseDouble(puntenVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } catch (NumberFormatException err){ infoLabel.setText("Let op: voer alleen cijfers in als punten"); } try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // CPP-student private void bindModuleEnter() { moduleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); try { studentenAdministratie.verhoogBehaaldeModules(bestaandeNaamVeld.getText()); } catch (StudentAdminException err){ infoLabel.setText(err.message); } try { studentInfoVeld.setText(studentenAdministratie.toonStudent(bestaandeNaamVeld.getText())); } catch (StudentAdminException err){ infoLabel.setText(err.message); } } }); } // Alle studenten-tab private void bindToonAlleKnop() { toonAlleKnop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { infoLabel.setText(""); uitvoerGebied.setText(studentenAdministratie.toonAlleStudenten()); } }); } } // @jve:decl-index=0:visual-constraint="10,10"
212768_2
/* This file is part of javaProject2TI. javaProject2TI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. javaProject2TI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with javaProject2TI. If not, see <http://www.gnu.org/licenses/>. */ package info.toegepaste.www; import info.toegepaste.www.entity.*; import info.toepaste.www.enumeration.Soort; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author robin */ @WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"}) public class ManageServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); EntityManagerFactory emf = null; HttpSession session = request.getSession(); try { RequestDispatcher rd = null; emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); if (session.getAttribute("soorten") == null) { Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Vakken.alle"); List<Vak> vakken = q.getResultList(); session.setAttribute("vakken", vakken); q = em.createNamedQuery("ComputerLokalen.alle"); List<ComputerLokaal> computerLokalen = q.getResultList(); session.setAttribute("computerLokalen", computerLokalen); q = em.createNamedQuery("GewoonLokalen.alle"); List<Lokaal> lokalen = q.getResultList(); session.setAttribute("gewoonLokalen", lokalen); Soort[] soorten = Soort.values(); session.setAttribute("soorten", soorten); } if (!(request.getParameter("home") == null)) { rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("examen") == null)) { Query q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("datum") == null)) { String datum = request.getParameter("datum"); String[] datumArray = datum.split("/"); datum = datumArray[2] + "-" + datumArray[1] + "-" + datumArray[0]; Query q = em.createNamedQuery("Examen.zoekenOpDatum"); q.setParameter("datum", datum); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); String titel = " op datum: " + datumArray[0] + "/" + datumArray[1] + "/" + datumArray[2]; request.setAttribute("titel", titel); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("docent") == null)) { String docentId = request.getParameter("docent"); Query q = em.createNamedQuery("Examen.zoekenOpDocent"); q.setParameter("docentId", docentId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); String titel = " op docent: " + docent.getVoornaam() + " " + docent.getFamilienaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("vak") == null)) { String vakId = request.getParameter("vak"); Query q = em.createNamedQuery("Examen.zoekenOpVak"); q.setParameter("vakId", vakId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); String titel = " op vak: " + vak.getNaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("lokaal") == null)) { String lokaalId = request.getParameter("lokaal"); Query q = em.createNamedQuery("Examen.zoekenOpLokaal"); q.setParameter("lokaalId", lokaalId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); String titel = " op lokaal: " + lokaal.getNummer(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("soort") == null)) { String soort = request.getParameter("soort"); Query q = em.createNamedQuery("Examen.zoekenOpSoort"); q.setParameter("soort", soort); List<Examen> examens = q.getResultList(); String titel = " op soort: " + soort; request.setAttribute("titel", titel); request.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (session.getAttribute("ingelogd") != null) { if (!(request.getParameter("toevoegenExamen") == null)) { Examen examen = new Examen(); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); em.close(); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("wijzigenExamen") == null)) { String examenId = request.getParameter("wijzigenExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); em.close(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("toevoegenExamenBevestigen") == null)) { String docentId = request.getParameter("docentExamen"); String vakId = request.getParameter("vakExamen"); String datum = request.getParameter("datumExamen"); String lokaalId = request.getParameter("lokaalExamen"); String soort = request.getParameter("soortExamen"); String examenId = request.getParameter("examenId"); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); Examen examen = new Examen(); if (!examenId.isEmpty() && !(examenId == null)) { examen.setId(Long.parseLong(examenId)); } examen.setDocent(docent); examen.setVak(vak); examen.setLokaal(lokaal); examen.setSoort(Soort.valueOf(soort)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(simpleDateFormat.parse(datum)); examen.setDatum(gregorianCalendar); EntityTransaction tx = em.getTransaction(); tx.begin(); if (!examenId.isEmpty() && !(examenId == null)) { em.merge(examen); } else { em.persist(examen); } tx.commit(); em.close(); rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("deleteExamen") == null)) { String examenId = request.getParameter("deleteExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); EntityTransaction tx = em.getTransaction(); tx.begin(); em.remove(examen); tx.commit(); Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); session.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } } else { response.sendRedirect("index.jsp"); } //let op: gebruik hier de juiste naam van de persistence unit //(zoek op in persistence.xml) /* emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); Docent docentEen = new Docent(); Docent docentTwee = new Docent(); Examen examenEen = new Examen(); Examen examenTwee = new Examen(); Examen examenDrie = new Examen(); ComputerLokaal computerLokaal = new ComputerLokaal(); GewoonLokaal gewoonLokaal = new GewoonLokaal(); Vak vakEen = new Vak(); Vak vakTwee = new Vak(); Vak vakDrie = new Vak(); tx.begin(); computerLokaal.setAantalPlaatsen(100); computerLokaal.setNummer("D101"); computerLokaal.setLaptop(false); computerLokaal.setInfo("Niet roken!"); em.persist(computerLokaal); vakEen.setNummer("s5454"); vakEen.setNaam("C#"); em.persist(vakEen); docentEen.setNummer("r00001"); docentEen.setVoornaam("Miranda"); docentEen.setFamilienaam("Decabooter"); docentEen.setEmail("[email protected]"); em.persist(docentEen); examenEen.setVak(vakEen); examenEen.setDocent(docentEen); examenEen.setDatum(new GregorianCalendar()); examenEen.setLokaal(computerLokaal); examenEen.setSoort(Soort.SCHRIFTELIJK); em.persist(examenEen); //Insert 2 gewoonLokaal.setAantalPlaatsen(50); gewoonLokaal.setNummer("Noord-Korea"); gewoonLokaal.setWhiteBoard(true); em.persist(gewoonLokaal); vakTwee.setNummer("s5455"); vakTwee.setNaam("Dynamische webapplicaties in PHP"); em.persist(vakTwee); examenTwee.setVak(vakTwee); examenTwee.setDocent(docentEen); examenTwee.setDatum(new GregorianCalendar()); examenTwee.setLokaal(gewoonLokaal); examenTwee.setSoort(Soort.SCHRIFTELIJK); em.persist(examenTwee); //Insert 3 vakDrie.setNummer("s5456"); vakDrie.setNaam("UML"); em.persist(vakDrie); docentTwee.setNummer("r00002"); docentTwee.setVoornaam("Christine"); docentTwee.setFamilienaam("Smeets"); docentTwee.setEmail("[email protected]"); em.persist(docentTwee); examenDrie.setVak(vakDrie); examenDrie.setDocent(docentTwee); examenDrie.setDatum(new GregorianCalendar()); examenDrie.setLokaal(gewoonLokaal); examenDrie.setSoort(Soort.SCHRIFTELIJK); em.persist(examenDrie); tx.commit(); em.close(); */ } catch (Exception e) { e.printStackTrace(); } finally { emf.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
ripperr/javaProject2TI
src/java/info/toegepaste/www/ManageServlet.java
3,938
//let op: gebruik hier de juiste naam van de persistence unit
line_comment
nl
/* This file is part of javaProject2TI. javaProject2TI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. javaProject2TI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with javaProject2TI. If not, see <http://www.gnu.org/licenses/>. */ package info.toegepaste.www; import info.toegepaste.www.entity.*; import info.toepaste.www.enumeration.Soort; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author robin */ @WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"}) public class ManageServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); EntityManagerFactory emf = null; HttpSession session = request.getSession(); try { RequestDispatcher rd = null; emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); if (session.getAttribute("soorten") == null) { Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Vakken.alle"); List<Vak> vakken = q.getResultList(); session.setAttribute("vakken", vakken); q = em.createNamedQuery("ComputerLokalen.alle"); List<ComputerLokaal> computerLokalen = q.getResultList(); session.setAttribute("computerLokalen", computerLokalen); q = em.createNamedQuery("GewoonLokalen.alle"); List<Lokaal> lokalen = q.getResultList(); session.setAttribute("gewoonLokalen", lokalen); Soort[] soorten = Soort.values(); session.setAttribute("soorten", soorten); } if (!(request.getParameter("home") == null)) { rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("examen") == null)) { Query q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("datum") == null)) { String datum = request.getParameter("datum"); String[] datumArray = datum.split("/"); datum = datumArray[2] + "-" + datumArray[1] + "-" + datumArray[0]; Query q = em.createNamedQuery("Examen.zoekenOpDatum"); q.setParameter("datum", datum); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); String titel = " op datum: " + datumArray[0] + "/" + datumArray[1] + "/" + datumArray[2]; request.setAttribute("titel", titel); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("docent") == null)) { String docentId = request.getParameter("docent"); Query q = em.createNamedQuery("Examen.zoekenOpDocent"); q.setParameter("docentId", docentId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); String titel = " op docent: " + docent.getVoornaam() + " " + docent.getFamilienaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("vak") == null)) { String vakId = request.getParameter("vak"); Query q = em.createNamedQuery("Examen.zoekenOpVak"); q.setParameter("vakId", vakId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); String titel = " op vak: " + vak.getNaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("lokaal") == null)) { String lokaalId = request.getParameter("lokaal"); Query q = em.createNamedQuery("Examen.zoekenOpLokaal"); q.setParameter("lokaalId", lokaalId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); String titel = " op lokaal: " + lokaal.getNummer(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("soort") == null)) { String soort = request.getParameter("soort"); Query q = em.createNamedQuery("Examen.zoekenOpSoort"); q.setParameter("soort", soort); List<Examen> examens = q.getResultList(); String titel = " op soort: " + soort; request.setAttribute("titel", titel); request.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (session.getAttribute("ingelogd") != null) { if (!(request.getParameter("toevoegenExamen") == null)) { Examen examen = new Examen(); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); em.close(); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("wijzigenExamen") == null)) { String examenId = request.getParameter("wijzigenExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); em.close(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("toevoegenExamenBevestigen") == null)) { String docentId = request.getParameter("docentExamen"); String vakId = request.getParameter("vakExamen"); String datum = request.getParameter("datumExamen"); String lokaalId = request.getParameter("lokaalExamen"); String soort = request.getParameter("soortExamen"); String examenId = request.getParameter("examenId"); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); Examen examen = new Examen(); if (!examenId.isEmpty() && !(examenId == null)) { examen.setId(Long.parseLong(examenId)); } examen.setDocent(docent); examen.setVak(vak); examen.setLokaal(lokaal); examen.setSoort(Soort.valueOf(soort)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(simpleDateFormat.parse(datum)); examen.setDatum(gregorianCalendar); EntityTransaction tx = em.getTransaction(); tx.begin(); if (!examenId.isEmpty() && !(examenId == null)) { em.merge(examen); } else { em.persist(examen); } tx.commit(); em.close(); rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("deleteExamen") == null)) { String examenId = request.getParameter("deleteExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); EntityTransaction tx = em.getTransaction(); tx.begin(); em.remove(examen); tx.commit(); Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); session.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } } else { response.sendRedirect("index.jsp"); } //let op:<SUF> //(zoek op in persistence.xml) /* emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); Docent docentEen = new Docent(); Docent docentTwee = new Docent(); Examen examenEen = new Examen(); Examen examenTwee = new Examen(); Examen examenDrie = new Examen(); ComputerLokaal computerLokaal = new ComputerLokaal(); GewoonLokaal gewoonLokaal = new GewoonLokaal(); Vak vakEen = new Vak(); Vak vakTwee = new Vak(); Vak vakDrie = new Vak(); tx.begin(); computerLokaal.setAantalPlaatsen(100); computerLokaal.setNummer("D101"); computerLokaal.setLaptop(false); computerLokaal.setInfo("Niet roken!"); em.persist(computerLokaal); vakEen.setNummer("s5454"); vakEen.setNaam("C#"); em.persist(vakEen); docentEen.setNummer("r00001"); docentEen.setVoornaam("Miranda"); docentEen.setFamilienaam("Decabooter"); docentEen.setEmail("[email protected]"); em.persist(docentEen); examenEen.setVak(vakEen); examenEen.setDocent(docentEen); examenEen.setDatum(new GregorianCalendar()); examenEen.setLokaal(computerLokaal); examenEen.setSoort(Soort.SCHRIFTELIJK); em.persist(examenEen); //Insert 2 gewoonLokaal.setAantalPlaatsen(50); gewoonLokaal.setNummer("Noord-Korea"); gewoonLokaal.setWhiteBoard(true); em.persist(gewoonLokaal); vakTwee.setNummer("s5455"); vakTwee.setNaam("Dynamische webapplicaties in PHP"); em.persist(vakTwee); examenTwee.setVak(vakTwee); examenTwee.setDocent(docentEen); examenTwee.setDatum(new GregorianCalendar()); examenTwee.setLokaal(gewoonLokaal); examenTwee.setSoort(Soort.SCHRIFTELIJK); em.persist(examenTwee); //Insert 3 vakDrie.setNummer("s5456"); vakDrie.setNaam("UML"); em.persist(vakDrie); docentTwee.setNummer("r00002"); docentTwee.setVoornaam("Christine"); docentTwee.setFamilienaam("Smeets"); docentTwee.setEmail("[email protected]"); em.persist(docentTwee); examenDrie.setVak(vakDrie); examenDrie.setDocent(docentTwee); examenDrie.setDatum(new GregorianCalendar()); examenDrie.setLokaal(gewoonLokaal); examenDrie.setSoort(Soort.SCHRIFTELIJK); em.persist(examenDrie); tx.commit(); em.close(); */ } catch (Exception e) { e.printStackTrace(); } finally { emf.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
212768_3
/* This file is part of javaProject2TI. javaProject2TI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. javaProject2TI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with javaProject2TI. If not, see <http://www.gnu.org/licenses/>. */ package info.toegepaste.www; import info.toegepaste.www.entity.*; import info.toepaste.www.enumeration.Soort; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author robin */ @WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"}) public class ManageServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); EntityManagerFactory emf = null; HttpSession session = request.getSession(); try { RequestDispatcher rd = null; emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); if (session.getAttribute("soorten") == null) { Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Vakken.alle"); List<Vak> vakken = q.getResultList(); session.setAttribute("vakken", vakken); q = em.createNamedQuery("ComputerLokalen.alle"); List<ComputerLokaal> computerLokalen = q.getResultList(); session.setAttribute("computerLokalen", computerLokalen); q = em.createNamedQuery("GewoonLokalen.alle"); List<Lokaal> lokalen = q.getResultList(); session.setAttribute("gewoonLokalen", lokalen); Soort[] soorten = Soort.values(); session.setAttribute("soorten", soorten); } if (!(request.getParameter("home") == null)) { rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("examen") == null)) { Query q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("datum") == null)) { String datum = request.getParameter("datum"); String[] datumArray = datum.split("/"); datum = datumArray[2] + "-" + datumArray[1] + "-" + datumArray[0]; Query q = em.createNamedQuery("Examen.zoekenOpDatum"); q.setParameter("datum", datum); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); String titel = " op datum: " + datumArray[0] + "/" + datumArray[1] + "/" + datumArray[2]; request.setAttribute("titel", titel); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("docent") == null)) { String docentId = request.getParameter("docent"); Query q = em.createNamedQuery("Examen.zoekenOpDocent"); q.setParameter("docentId", docentId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); String titel = " op docent: " + docent.getVoornaam() + " " + docent.getFamilienaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("vak") == null)) { String vakId = request.getParameter("vak"); Query q = em.createNamedQuery("Examen.zoekenOpVak"); q.setParameter("vakId", vakId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); String titel = " op vak: " + vak.getNaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("lokaal") == null)) { String lokaalId = request.getParameter("lokaal"); Query q = em.createNamedQuery("Examen.zoekenOpLokaal"); q.setParameter("lokaalId", lokaalId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); String titel = " op lokaal: " + lokaal.getNummer(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("soort") == null)) { String soort = request.getParameter("soort"); Query q = em.createNamedQuery("Examen.zoekenOpSoort"); q.setParameter("soort", soort); List<Examen> examens = q.getResultList(); String titel = " op soort: " + soort; request.setAttribute("titel", titel); request.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (session.getAttribute("ingelogd") != null) { if (!(request.getParameter("toevoegenExamen") == null)) { Examen examen = new Examen(); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); em.close(); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("wijzigenExamen") == null)) { String examenId = request.getParameter("wijzigenExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); em.close(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("toevoegenExamenBevestigen") == null)) { String docentId = request.getParameter("docentExamen"); String vakId = request.getParameter("vakExamen"); String datum = request.getParameter("datumExamen"); String lokaalId = request.getParameter("lokaalExamen"); String soort = request.getParameter("soortExamen"); String examenId = request.getParameter("examenId"); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); Examen examen = new Examen(); if (!examenId.isEmpty() && !(examenId == null)) { examen.setId(Long.parseLong(examenId)); } examen.setDocent(docent); examen.setVak(vak); examen.setLokaal(lokaal); examen.setSoort(Soort.valueOf(soort)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(simpleDateFormat.parse(datum)); examen.setDatum(gregorianCalendar); EntityTransaction tx = em.getTransaction(); tx.begin(); if (!examenId.isEmpty() && !(examenId == null)) { em.merge(examen); } else { em.persist(examen); } tx.commit(); em.close(); rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("deleteExamen") == null)) { String examenId = request.getParameter("deleteExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); EntityTransaction tx = em.getTransaction(); tx.begin(); em.remove(examen); tx.commit(); Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); session.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } } else { response.sendRedirect("index.jsp"); } //let op: gebruik hier de juiste naam van de persistence unit //(zoek op in persistence.xml) /* emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); Docent docentEen = new Docent(); Docent docentTwee = new Docent(); Examen examenEen = new Examen(); Examen examenTwee = new Examen(); Examen examenDrie = new Examen(); ComputerLokaal computerLokaal = new ComputerLokaal(); GewoonLokaal gewoonLokaal = new GewoonLokaal(); Vak vakEen = new Vak(); Vak vakTwee = new Vak(); Vak vakDrie = new Vak(); tx.begin(); computerLokaal.setAantalPlaatsen(100); computerLokaal.setNummer("D101"); computerLokaal.setLaptop(false); computerLokaal.setInfo("Niet roken!"); em.persist(computerLokaal); vakEen.setNummer("s5454"); vakEen.setNaam("C#"); em.persist(vakEen); docentEen.setNummer("r00001"); docentEen.setVoornaam("Miranda"); docentEen.setFamilienaam("Decabooter"); docentEen.setEmail("[email protected]"); em.persist(docentEen); examenEen.setVak(vakEen); examenEen.setDocent(docentEen); examenEen.setDatum(new GregorianCalendar()); examenEen.setLokaal(computerLokaal); examenEen.setSoort(Soort.SCHRIFTELIJK); em.persist(examenEen); //Insert 2 gewoonLokaal.setAantalPlaatsen(50); gewoonLokaal.setNummer("Noord-Korea"); gewoonLokaal.setWhiteBoard(true); em.persist(gewoonLokaal); vakTwee.setNummer("s5455"); vakTwee.setNaam("Dynamische webapplicaties in PHP"); em.persist(vakTwee); examenTwee.setVak(vakTwee); examenTwee.setDocent(docentEen); examenTwee.setDatum(new GregorianCalendar()); examenTwee.setLokaal(gewoonLokaal); examenTwee.setSoort(Soort.SCHRIFTELIJK); em.persist(examenTwee); //Insert 3 vakDrie.setNummer("s5456"); vakDrie.setNaam("UML"); em.persist(vakDrie); docentTwee.setNummer("r00002"); docentTwee.setVoornaam("Christine"); docentTwee.setFamilienaam("Smeets"); docentTwee.setEmail("[email protected]"); em.persist(docentTwee); examenDrie.setVak(vakDrie); examenDrie.setDocent(docentTwee); examenDrie.setDatum(new GregorianCalendar()); examenDrie.setLokaal(gewoonLokaal); examenDrie.setSoort(Soort.SCHRIFTELIJK); em.persist(examenDrie); tx.commit(); em.close(); */ } catch (Exception e) { e.printStackTrace(); } finally { emf.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
ripperr/javaProject2TI
src/java/info/toegepaste/www/ManageServlet.java
3,938
//(zoek op in persistence.xml)
line_comment
nl
/* This file is part of javaProject2TI. javaProject2TI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. javaProject2TI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with javaProject2TI. If not, see <http://www.gnu.org/licenses/>. */ package info.toegepaste.www; import info.toegepaste.www.entity.*; import info.toepaste.www.enumeration.Soort; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author robin */ @WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"}) public class ManageServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); EntityManagerFactory emf = null; HttpSession session = request.getSession(); try { RequestDispatcher rd = null; emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); if (session.getAttribute("soorten") == null) { Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Vakken.alle"); List<Vak> vakken = q.getResultList(); session.setAttribute("vakken", vakken); q = em.createNamedQuery("ComputerLokalen.alle"); List<ComputerLokaal> computerLokalen = q.getResultList(); session.setAttribute("computerLokalen", computerLokalen); q = em.createNamedQuery("GewoonLokalen.alle"); List<Lokaal> lokalen = q.getResultList(); session.setAttribute("gewoonLokalen", lokalen); Soort[] soorten = Soort.values(); session.setAttribute("soorten", soorten); } if (!(request.getParameter("home") == null)) { rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("examen") == null)) { Query q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("datum") == null)) { String datum = request.getParameter("datum"); String[] datumArray = datum.split("/"); datum = datumArray[2] + "-" + datumArray[1] + "-" + datumArray[0]; Query q = em.createNamedQuery("Examen.zoekenOpDatum"); q.setParameter("datum", datum); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); String titel = " op datum: " + datumArray[0] + "/" + datumArray[1] + "/" + datumArray[2]; request.setAttribute("titel", titel); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("docent") == null)) { String docentId = request.getParameter("docent"); Query q = em.createNamedQuery("Examen.zoekenOpDocent"); q.setParameter("docentId", docentId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); String titel = " op docent: " + docent.getVoornaam() + " " + docent.getFamilienaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("vak") == null)) { String vakId = request.getParameter("vak"); Query q = em.createNamedQuery("Examen.zoekenOpVak"); q.setParameter("vakId", vakId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); String titel = " op vak: " + vak.getNaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("lokaal") == null)) { String lokaalId = request.getParameter("lokaal"); Query q = em.createNamedQuery("Examen.zoekenOpLokaal"); q.setParameter("lokaalId", lokaalId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); String titel = " op lokaal: " + lokaal.getNummer(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("soort") == null)) { String soort = request.getParameter("soort"); Query q = em.createNamedQuery("Examen.zoekenOpSoort"); q.setParameter("soort", soort); List<Examen> examens = q.getResultList(); String titel = " op soort: " + soort; request.setAttribute("titel", titel); request.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (session.getAttribute("ingelogd") != null) { if (!(request.getParameter("toevoegenExamen") == null)) { Examen examen = new Examen(); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); em.close(); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("wijzigenExamen") == null)) { String examenId = request.getParameter("wijzigenExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); em.close(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("toevoegenExamenBevestigen") == null)) { String docentId = request.getParameter("docentExamen"); String vakId = request.getParameter("vakExamen"); String datum = request.getParameter("datumExamen"); String lokaalId = request.getParameter("lokaalExamen"); String soort = request.getParameter("soortExamen"); String examenId = request.getParameter("examenId"); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); Examen examen = new Examen(); if (!examenId.isEmpty() && !(examenId == null)) { examen.setId(Long.parseLong(examenId)); } examen.setDocent(docent); examen.setVak(vak); examen.setLokaal(lokaal); examen.setSoort(Soort.valueOf(soort)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(simpleDateFormat.parse(datum)); examen.setDatum(gregorianCalendar); EntityTransaction tx = em.getTransaction(); tx.begin(); if (!examenId.isEmpty() && !(examenId == null)) { em.merge(examen); } else { em.persist(examen); } tx.commit(); em.close(); rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("deleteExamen") == null)) { String examenId = request.getParameter("deleteExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); EntityTransaction tx = em.getTransaction(); tx.begin(); em.remove(examen); tx.commit(); Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); session.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } } else { response.sendRedirect("index.jsp"); } //let op: gebruik hier de juiste naam van de persistence unit //(zoek op<SUF> /* emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); Docent docentEen = new Docent(); Docent docentTwee = new Docent(); Examen examenEen = new Examen(); Examen examenTwee = new Examen(); Examen examenDrie = new Examen(); ComputerLokaal computerLokaal = new ComputerLokaal(); GewoonLokaal gewoonLokaal = new GewoonLokaal(); Vak vakEen = new Vak(); Vak vakTwee = new Vak(); Vak vakDrie = new Vak(); tx.begin(); computerLokaal.setAantalPlaatsen(100); computerLokaal.setNummer("D101"); computerLokaal.setLaptop(false); computerLokaal.setInfo("Niet roken!"); em.persist(computerLokaal); vakEen.setNummer("s5454"); vakEen.setNaam("C#"); em.persist(vakEen); docentEen.setNummer("r00001"); docentEen.setVoornaam("Miranda"); docentEen.setFamilienaam("Decabooter"); docentEen.setEmail("[email protected]"); em.persist(docentEen); examenEen.setVak(vakEen); examenEen.setDocent(docentEen); examenEen.setDatum(new GregorianCalendar()); examenEen.setLokaal(computerLokaal); examenEen.setSoort(Soort.SCHRIFTELIJK); em.persist(examenEen); //Insert 2 gewoonLokaal.setAantalPlaatsen(50); gewoonLokaal.setNummer("Noord-Korea"); gewoonLokaal.setWhiteBoard(true); em.persist(gewoonLokaal); vakTwee.setNummer("s5455"); vakTwee.setNaam("Dynamische webapplicaties in PHP"); em.persist(vakTwee); examenTwee.setVak(vakTwee); examenTwee.setDocent(docentEen); examenTwee.setDatum(new GregorianCalendar()); examenTwee.setLokaal(gewoonLokaal); examenTwee.setSoort(Soort.SCHRIFTELIJK); em.persist(examenTwee); //Insert 3 vakDrie.setNummer("s5456"); vakDrie.setNaam("UML"); em.persist(vakDrie); docentTwee.setNummer("r00002"); docentTwee.setVoornaam("Christine"); docentTwee.setFamilienaam("Smeets"); docentTwee.setEmail("[email protected]"); em.persist(docentTwee); examenDrie.setVak(vakDrie); examenDrie.setDocent(docentTwee); examenDrie.setDatum(new GregorianCalendar()); examenDrie.setLokaal(gewoonLokaal); examenDrie.setSoort(Soort.SCHRIFTELIJK); em.persist(examenDrie); tx.commit(); em.close(); */ } catch (Exception e) { e.printStackTrace(); } finally { emf.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
212768_4
/* This file is part of javaProject2TI. javaProject2TI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. javaProject2TI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with javaProject2TI. If not, see <http://www.gnu.org/licenses/>. */ package info.toegepaste.www; import info.toegepaste.www.entity.*; import info.toepaste.www.enumeration.Soort; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author robin */ @WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"}) public class ManageServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); EntityManagerFactory emf = null; HttpSession session = request.getSession(); try { RequestDispatcher rd = null; emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); if (session.getAttribute("soorten") == null) { Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Vakken.alle"); List<Vak> vakken = q.getResultList(); session.setAttribute("vakken", vakken); q = em.createNamedQuery("ComputerLokalen.alle"); List<ComputerLokaal> computerLokalen = q.getResultList(); session.setAttribute("computerLokalen", computerLokalen); q = em.createNamedQuery("GewoonLokalen.alle"); List<Lokaal> lokalen = q.getResultList(); session.setAttribute("gewoonLokalen", lokalen); Soort[] soorten = Soort.values(); session.setAttribute("soorten", soorten); } if (!(request.getParameter("home") == null)) { rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("examen") == null)) { Query q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("datum") == null)) { String datum = request.getParameter("datum"); String[] datumArray = datum.split("/"); datum = datumArray[2] + "-" + datumArray[1] + "-" + datumArray[0]; Query q = em.createNamedQuery("Examen.zoekenOpDatum"); q.setParameter("datum", datum); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); String titel = " op datum: " + datumArray[0] + "/" + datumArray[1] + "/" + datumArray[2]; request.setAttribute("titel", titel); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("docent") == null)) { String docentId = request.getParameter("docent"); Query q = em.createNamedQuery("Examen.zoekenOpDocent"); q.setParameter("docentId", docentId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); String titel = " op docent: " + docent.getVoornaam() + " " + docent.getFamilienaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("vak") == null)) { String vakId = request.getParameter("vak"); Query q = em.createNamedQuery("Examen.zoekenOpVak"); q.setParameter("vakId", vakId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); String titel = " op vak: " + vak.getNaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("lokaal") == null)) { String lokaalId = request.getParameter("lokaal"); Query q = em.createNamedQuery("Examen.zoekenOpLokaal"); q.setParameter("lokaalId", lokaalId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); String titel = " op lokaal: " + lokaal.getNummer(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("soort") == null)) { String soort = request.getParameter("soort"); Query q = em.createNamedQuery("Examen.zoekenOpSoort"); q.setParameter("soort", soort); List<Examen> examens = q.getResultList(); String titel = " op soort: " + soort; request.setAttribute("titel", titel); request.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (session.getAttribute("ingelogd") != null) { if (!(request.getParameter("toevoegenExamen") == null)) { Examen examen = new Examen(); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); em.close(); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("wijzigenExamen") == null)) { String examenId = request.getParameter("wijzigenExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); em.close(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("toevoegenExamenBevestigen") == null)) { String docentId = request.getParameter("docentExamen"); String vakId = request.getParameter("vakExamen"); String datum = request.getParameter("datumExamen"); String lokaalId = request.getParameter("lokaalExamen"); String soort = request.getParameter("soortExamen"); String examenId = request.getParameter("examenId"); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); Examen examen = new Examen(); if (!examenId.isEmpty() && !(examenId == null)) { examen.setId(Long.parseLong(examenId)); } examen.setDocent(docent); examen.setVak(vak); examen.setLokaal(lokaal); examen.setSoort(Soort.valueOf(soort)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(simpleDateFormat.parse(datum)); examen.setDatum(gregorianCalendar); EntityTransaction tx = em.getTransaction(); tx.begin(); if (!examenId.isEmpty() && !(examenId == null)) { em.merge(examen); } else { em.persist(examen); } tx.commit(); em.close(); rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("deleteExamen") == null)) { String examenId = request.getParameter("deleteExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); EntityTransaction tx = em.getTransaction(); tx.begin(); em.remove(examen); tx.commit(); Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); session.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } } else { response.sendRedirect("index.jsp"); } //let op: gebruik hier de juiste naam van de persistence unit //(zoek op in persistence.xml) /* emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); Docent docentEen = new Docent(); Docent docentTwee = new Docent(); Examen examenEen = new Examen(); Examen examenTwee = new Examen(); Examen examenDrie = new Examen(); ComputerLokaal computerLokaal = new ComputerLokaal(); GewoonLokaal gewoonLokaal = new GewoonLokaal(); Vak vakEen = new Vak(); Vak vakTwee = new Vak(); Vak vakDrie = new Vak(); tx.begin(); computerLokaal.setAantalPlaatsen(100); computerLokaal.setNummer("D101"); computerLokaal.setLaptop(false); computerLokaal.setInfo("Niet roken!"); em.persist(computerLokaal); vakEen.setNummer("s5454"); vakEen.setNaam("C#"); em.persist(vakEen); docentEen.setNummer("r00001"); docentEen.setVoornaam("Miranda"); docentEen.setFamilienaam("Decabooter"); docentEen.setEmail("[email protected]"); em.persist(docentEen); examenEen.setVak(vakEen); examenEen.setDocent(docentEen); examenEen.setDatum(new GregorianCalendar()); examenEen.setLokaal(computerLokaal); examenEen.setSoort(Soort.SCHRIFTELIJK); em.persist(examenEen); //Insert 2 gewoonLokaal.setAantalPlaatsen(50); gewoonLokaal.setNummer("Noord-Korea"); gewoonLokaal.setWhiteBoard(true); em.persist(gewoonLokaal); vakTwee.setNummer("s5455"); vakTwee.setNaam("Dynamische webapplicaties in PHP"); em.persist(vakTwee); examenTwee.setVak(vakTwee); examenTwee.setDocent(docentEen); examenTwee.setDatum(new GregorianCalendar()); examenTwee.setLokaal(gewoonLokaal); examenTwee.setSoort(Soort.SCHRIFTELIJK); em.persist(examenTwee); //Insert 3 vakDrie.setNummer("s5456"); vakDrie.setNaam("UML"); em.persist(vakDrie); docentTwee.setNummer("r00002"); docentTwee.setVoornaam("Christine"); docentTwee.setFamilienaam("Smeets"); docentTwee.setEmail("[email protected]"); em.persist(docentTwee); examenDrie.setVak(vakDrie); examenDrie.setDocent(docentTwee); examenDrie.setDatum(new GregorianCalendar()); examenDrie.setLokaal(gewoonLokaal); examenDrie.setSoort(Soort.SCHRIFTELIJK); em.persist(examenDrie); tx.commit(); em.close(); */ } catch (Exception e) { e.printStackTrace(); } finally { emf.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
ripperr/javaProject2TI
src/java/info/toegepaste/www/ManageServlet.java
3,938
/* emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); Docent docentEen = new Docent(); Docent docentTwee = new Docent(); Examen examenEen = new Examen(); Examen examenTwee = new Examen(); Examen examenDrie = new Examen(); ComputerLokaal computerLokaal = new ComputerLokaal(); GewoonLokaal gewoonLokaal = new GewoonLokaal(); Vak vakEen = new Vak(); Vak vakTwee = new Vak(); Vak vakDrie = new Vak(); tx.begin(); computerLokaal.setAantalPlaatsen(100); computerLokaal.setNummer("D101"); computerLokaal.setLaptop(false); computerLokaal.setInfo("Niet roken!"); em.persist(computerLokaal); vakEen.setNummer("s5454"); vakEen.setNaam("C#"); em.persist(vakEen); docentEen.setNummer("r00001"); docentEen.setVoornaam("Miranda"); docentEen.setFamilienaam("Decabooter"); docentEen.setEmail("[email protected]"); em.persist(docentEen); examenEen.setVak(vakEen); examenEen.setDocent(docentEen); examenEen.setDatum(new GregorianCalendar()); examenEen.setLokaal(computerLokaal); examenEen.setSoort(Soort.SCHRIFTELIJK); em.persist(examenEen); //Insert 2 gewoonLokaal.setAantalPlaatsen(50); gewoonLokaal.setNummer("Noord-Korea"); gewoonLokaal.setWhiteBoard(true); em.persist(gewoonLokaal); vakTwee.setNummer("s5455"); vakTwee.setNaam("Dynamische webapplicaties in PHP"); em.persist(vakTwee); examenTwee.setVak(vakTwee); examenTwee.setDocent(docentEen); examenTwee.setDatum(new GregorianCalendar()); examenTwee.setLokaal(gewoonLokaal); examenTwee.setSoort(Soort.SCHRIFTELIJK); em.persist(examenTwee); //Insert 3 vakDrie.setNummer("s5456"); vakDrie.setNaam("UML"); em.persist(vakDrie); docentTwee.setNummer("r00002"); docentTwee.setVoornaam("Christine"); docentTwee.setFamilienaam("Smeets"); docentTwee.setEmail("[email protected]"); em.persist(docentTwee); examenDrie.setVak(vakDrie); examenDrie.setDocent(docentTwee); examenDrie.setDatum(new GregorianCalendar()); examenDrie.setLokaal(gewoonLokaal); examenDrie.setSoort(Soort.SCHRIFTELIJK); em.persist(examenDrie); tx.commit(); em.close(); */
block_comment
nl
/* This file is part of javaProject2TI. javaProject2TI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. javaProject2TI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with javaProject2TI. If not, see <http://www.gnu.org/licenses/>. */ package info.toegepaste.www; import info.toegepaste.www.entity.*; import info.toepaste.www.enumeration.Soort; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author robin */ @WebServlet(name = "ManageServlet", urlPatterns = {"/ManageServlet"}) public class ManageServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); EntityManagerFactory emf = null; HttpSession session = request.getSession(); try { RequestDispatcher rd = null; emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); EntityManager em = emf.createEntityManager(); if (session.getAttribute("soorten") == null) { Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Vakken.alle"); List<Vak> vakken = q.getResultList(); session.setAttribute("vakken", vakken); q = em.createNamedQuery("ComputerLokalen.alle"); List<ComputerLokaal> computerLokalen = q.getResultList(); session.setAttribute("computerLokalen", computerLokalen); q = em.createNamedQuery("GewoonLokalen.alle"); List<Lokaal> lokalen = q.getResultList(); session.setAttribute("gewoonLokalen", lokalen); Soort[] soorten = Soort.values(); session.setAttribute("soorten", soorten); } if (!(request.getParameter("home") == null)) { rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("examen") == null)) { Query q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("datum") == null)) { String datum = request.getParameter("datum"); String[] datumArray = datum.split("/"); datum = datumArray[2] + "-" + datumArray[1] + "-" + datumArray[0]; Query q = em.createNamedQuery("Examen.zoekenOpDatum"); q.setParameter("datum", datum); List<Examen> examens = q.getResultList(); em.close(); request.setAttribute("examens", examens); String titel = " op datum: " + datumArray[0] + "/" + datumArray[1] + "/" + datumArray[2]; request.setAttribute("titel", titel); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("docent") == null)) { String docentId = request.getParameter("docent"); Query q = em.createNamedQuery("Examen.zoekenOpDocent"); q.setParameter("docentId", docentId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); String titel = " op docent: " + docent.getVoornaam() + " " + docent.getFamilienaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("vak") == null)) { String vakId = request.getParameter("vak"); Query q = em.createNamedQuery("Examen.zoekenOpVak"); q.setParameter("vakId", vakId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); String titel = " op vak: " + vak.getNaam(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("lokaal") == null)) { String lokaalId = request.getParameter("lokaal"); Query q = em.createNamedQuery("Examen.zoekenOpLokaal"); q.setParameter("lokaalId", lokaalId); List<Examen> examens = q.getResultList(); request.setAttribute("examens", examens); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); String titel = " op lokaal: " + lokaal.getNummer(); request.setAttribute("titel", titel); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (!(request.getParameter("soort") == null)) { String soort = request.getParameter("soort"); Query q = em.createNamedQuery("Examen.zoekenOpSoort"); q.setParameter("soort", soort); List<Examen> examens = q.getResultList(); String titel = " op soort: " + soort; request.setAttribute("titel", titel); request.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } else if (session.getAttribute("ingelogd") != null) { if (!(request.getParameter("toevoegenExamen") == null)) { Examen examen = new Examen(); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); em.close(); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("wijzigenExamen") == null)) { String examenId = request.getParameter("wijzigenExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); Query q = em.createNamedQuery("Lokaal.alle"); List<Lokaal> lokalen = q.getResultList(); em.close(); request.setAttribute("lokalen", lokalen); request.setAttribute("examen", examen); rd = request.getRequestDispatcher("toevoegenExamen.jsp"); rd.forward(request, response); } else if (!(request.getParameter("toevoegenExamenBevestigen") == null)) { String docentId = request.getParameter("docentExamen"); String vakId = request.getParameter("vakExamen"); String datum = request.getParameter("datumExamen"); String lokaalId = request.getParameter("lokaalExamen"); String soort = request.getParameter("soortExamen"); String examenId = request.getParameter("examenId"); Docent docent = em.find(Docent.class, Long.parseLong(docentId)); Vak vak = em.find(Vak.class, Long.parseLong(vakId)); Lokaal lokaal = em.find(Lokaal.class, Long.parseLong(lokaalId)); Examen examen = new Examen(); if (!examenId.isEmpty() && !(examenId == null)) { examen.setId(Long.parseLong(examenId)); } examen.setDocent(docent); examen.setVak(vak); examen.setLokaal(lokaal); examen.setSoort(Soort.valueOf(soort)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(simpleDateFormat.parse(datum)); examen.setDatum(gregorianCalendar); EntityTransaction tx = em.getTransaction(); tx.begin(); if (!examenId.isEmpty() && !(examenId == null)) { em.merge(examen); } else { em.persist(examen); } tx.commit(); em.close(); rd = request.getRequestDispatcher("index.jsp"); rd.forward(request, response); } else if (!(request.getParameter("deleteExamen") == null)) { String examenId = request.getParameter("deleteExamen"); Examen examen = em.find(Examen.class, Long.parseLong(examenId)); EntityTransaction tx = em.getTransaction(); tx.begin(); em.remove(examen); tx.commit(); Query q = em.createNamedQuery("Docenten.alle"); List<Docent> docenten = q.getResultList(); session.setAttribute("docenten", docenten); q = em.createNamedQuery("Examen.alle"); List<Examen> examens = q.getResultList(); session.setAttribute("examens", examens); em.close(); rd = request.getRequestDispatcher("overzichtExamens.jsp"); rd.forward(request, response); } } else { response.sendRedirect("index.jsp"); } //let op: gebruik hier de juiste naam van de persistence unit //(zoek op in persistence.xml) /* emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU"); <SUF>*/ } catch (Exception e) { e.printStackTrace(); } finally { emf.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
212771_10
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is LeoCMS. * * The Initial Developer of the Original Code is * 'De Gemeente Leeuwarden' (The dutch municipality Leeuwarden). * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.evenementen.forms; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import org.mmbase.bridge.*; import org.mmbase.module.core.*; import org.mmbase.util.logging.*; import javax.servlet.*; import nl.leocms.evenementen.Evenement; import com.finalist.mmbase.util.CloudFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.*; /** * EvenementAction * * @author Henk Hangyi * * @struts:action name="EvenementForm" * path="/editors/evenementen/EvenementAction" * scope="request" * validate="true" * input="/editors/evenementen/evenement.jsp" * * @struts:action-forward name="success" path="/editors/evenementen/evenement.jsp" */ public class EvenementAction extends Action { private static final Logger log = Logging.getLoggerInstance(EvenementAction.class); private void removeObsoleteFormBean(ActionMapping mapping, HttpServletRequest request) { // *** Remove the obsolete form bean *** if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else { HttpSession session = request.getSession(); session.removeAttribute(mapping.getAttribute()); } } } /** * The actual perform function: MUST be implemented by subclasses. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("EvenementAction.execute()"); EvenementForm evenementForm = (EvenementForm) form; ActionForward forwardAction = null; String action = evenementForm.getAction(); if (isCancelled(request)) { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } else if(evenementForm.getButtons().getShowPastDates().pressed()) { // ****************** ShowPastDates ************* if(evenementForm.getShowPastDates().equals("true")) { evenementForm.setShowPastDates("false"); } else { evenementForm.setShowPastDates("true"); } forwardAction = mapping.findForward("continue"); } else if(action.indexOf("Opslaan")>-1) { // ********** Opslaan ******** // change history: // concurrent modification exception -> clone() // duplicated dates one not related to parent -> Iterators // flush the coming events cache (see nl.mmatch.CSVReader) MMBaseContext mc = new MMBaseContext(); ServletContext application = mc.getServletContext(); application.removeAttribute("events_till"); TreeSet newEvents = (TreeSet) evenementForm.getDates().clone(); log.info("newEvents = " + newEvents); TreeSet oldEvents = (TreeSet) evenementForm.getOldDates().clone(); log.info("oldEvents = " + oldEvents); Cloud cloud = CloudFactory.getCloud(); String nodeNumber = evenementForm.getNode(); Node node = null; if (!nodeNumber.equals("")) { node= cloud.getNode(nodeNumber); } Iterator newEventsIt = newEvents.iterator(); while(newEventsIt.hasNext()) { Evenement thisEvent = (Evenement) newEventsIt.next(); Node thisEventNode = null; if(!oldEvents.contains(thisEvent)) { // *** this is a new node *** thisEventNode = cloud.getNodeManager("evenement").createNode(); if(node==null) { thisEventNode.setStringValue("soort","parent"); thisEventNode.setIntValue("reageer",12); // ** default closing time 12 hours before event } else { thisEventNode.setStringValue("soort","child"); } // these values are set to their defaults (and will not be updated for child events) thisEventNode.setIntValue("min_aantal_deelnemers",0); thisEventNode.setIntValue("max_aantal_deelnemers",9999); thisEventNode.setIntValue("cur_aantal_deelnemers",0); thisEventNode.setStringValue("groepsexcursie","0"); // not used, see deelnemerscategorie.groepsactiviteit thisEventNode.setStringValue("adres_verplicht","0"); thisEventNode.setStringValue("aanmelden_vooraf","1"); thisEventNode.setStringValue("achteraf_bevestigen","1"); thisEventNode.setStringValue("voorkeur_verplicht","0"); thisEventNode.commit(); if(node==null) { node = thisEventNode; } else { Relation relation = node.createRelation(thisEventNode,cloud.getRelationManager("partrel")); relation.commit(); } } else { // *** this is an already existing node *** thisEventNode= cloud.getNode(thisEvent.getNumber()); oldEvents.remove(thisEvent); } String titel = evenementForm.getName(); titel = titel.substring(0,1).toUpperCase() + titel.substring(1); thisEventNode.setStringValue("titel",titel); thisEventNode.setLongValue("begindatum",(thisEvent.getBegin().getTime())/1000); thisEventNode.setLongValue("einddatum",(thisEvent.getEnd().getTime())/1000); thisEventNode.setStringValue("isspare",thisEvent.getIsSpareDate()); thisEventNode.setStringValue("isoninternet",thisEvent.getIsOnInternet()); if (!thisEventNode.getStringValue("iscanceled").equals(thisEvent.getIsCanceled())){ thisEventNode.setStringValue("iscanceled",thisEvent.getIsCanceled()); } thisEventNode.setStringValue("dagomschrijving",evenementForm.selectedDays(thisEvent.getNumber())); thisEventNode.commit(); NodeList userList = cloud.getNodeManager("users").getList("account='"+evenementForm.getUserId()+"'",null,null); if (userList.size()!=0) { userList.getNode(0).createRelation(thisEventNode,cloud.getRelationManager("schrijver")).commit(); } } // *** delete nodes not available in the user input from MMBase *** Iterator oldEventsIt = oldEvents.iterator(); while(oldEventsIt.hasNext()) { Evenement thisEvent = (Evenement) oldEventsIt.next(); Node oldEvent = cloud.getNode(thisEvent.getNumber()); oldEvent.delete(true); } if(action.equals("Opslaan")) { evenementForm.initDates("" + node.getNumber()); forwardAction = mapping.findForward("continue"); } else { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } } else if(action.equals("Voeg toe")) { // *** Voeg toe *** Evenement newEvent = new Evenement(evenementForm.nextNewNodeNumber()); evenementForm.update(newEvent); forwardAction = mapping.findForward("continue"); } else if(action.equals("Wijzig")) { // *** Wijzig *** TreeSet dates = evenementForm.getDates(); String selectedEvent = evenementForm.getSelectedEvent(); Iterator datesIterator = dates.iterator(); while(datesIterator.hasNext()) { Evenement thisEvent = (Evenement) datesIterator.next(); if(thisEvent.getNumber().equals(selectedEvent)) { evenementForm.update(thisEvent); } } forwardAction = mapping.findForward("continue"); } else if(action.equals("Wis")) { // *** Wis *** evenementForm.setBeginYear(""); evenementForm.setBeginMonth(""); evenementForm.setBeginDay(""); evenementForm.setBeginHour(""); evenementForm.setBeginMinute(""); evenementForm.setEndYear(""); evenementForm.setEndMonth(""); evenementForm.setEndDay(""); evenementForm.setEndHour(""); evenementForm.setEndMinute(""); evenementForm.setIsSpareDate("false"); evenementForm.setIsOnInternet("false"); evenementForm.setIsCanceled("false"); forwardAction = mapping.findForward("continue"); } else if(action.equals("Verwijder selectie")) { // *** Verwijder selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { datesMap.remove(selectedDates[i]); // *** could also remove from selectedDaysOfWeek, but this is not necessary *** } } evenementForm.setDates(new TreeSet(datesMap.values())); evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Activeer selectie")||action.equals("Annuleer selectie")) { // *** Annuleer / Activeer selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); if(action.equals("Activeer selectie")) { thisEvent.setIsCanceled("false"); } else { thisEvent.setIsCanceled("true"); } } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Periode -> data")) { // *** Periode -> data *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); evenementForm.createDatesFromPeriod(thisEvent); } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } return forwardAction; } }
mmbase/natmm
src/nl/leocms/evenementen/forms/EvenementAction.java
2,827
// not used, see deelnemerscategorie.groepsactiviteit
line_comment
nl
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is LeoCMS. * * The Initial Developer of the Original Code is * 'De Gemeente Leeuwarden' (The dutch municipality Leeuwarden). * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.evenementen.forms; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import org.mmbase.bridge.*; import org.mmbase.module.core.*; import org.mmbase.util.logging.*; import javax.servlet.*; import nl.leocms.evenementen.Evenement; import com.finalist.mmbase.util.CloudFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.*; /** * EvenementAction * * @author Henk Hangyi * * @struts:action name="EvenementForm" * path="/editors/evenementen/EvenementAction" * scope="request" * validate="true" * input="/editors/evenementen/evenement.jsp" * * @struts:action-forward name="success" path="/editors/evenementen/evenement.jsp" */ public class EvenementAction extends Action { private static final Logger log = Logging.getLoggerInstance(EvenementAction.class); private void removeObsoleteFormBean(ActionMapping mapping, HttpServletRequest request) { // *** Remove the obsolete form bean *** if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else { HttpSession session = request.getSession(); session.removeAttribute(mapping.getAttribute()); } } } /** * The actual perform function: MUST be implemented by subclasses. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("EvenementAction.execute()"); EvenementForm evenementForm = (EvenementForm) form; ActionForward forwardAction = null; String action = evenementForm.getAction(); if (isCancelled(request)) { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } else if(evenementForm.getButtons().getShowPastDates().pressed()) { // ****************** ShowPastDates ************* if(evenementForm.getShowPastDates().equals("true")) { evenementForm.setShowPastDates("false"); } else { evenementForm.setShowPastDates("true"); } forwardAction = mapping.findForward("continue"); } else if(action.indexOf("Opslaan")>-1) { // ********** Opslaan ******** // change history: // concurrent modification exception -> clone() // duplicated dates one not related to parent -> Iterators // flush the coming events cache (see nl.mmatch.CSVReader) MMBaseContext mc = new MMBaseContext(); ServletContext application = mc.getServletContext(); application.removeAttribute("events_till"); TreeSet newEvents = (TreeSet) evenementForm.getDates().clone(); log.info("newEvents = " + newEvents); TreeSet oldEvents = (TreeSet) evenementForm.getOldDates().clone(); log.info("oldEvents = " + oldEvents); Cloud cloud = CloudFactory.getCloud(); String nodeNumber = evenementForm.getNode(); Node node = null; if (!nodeNumber.equals("")) { node= cloud.getNode(nodeNumber); } Iterator newEventsIt = newEvents.iterator(); while(newEventsIt.hasNext()) { Evenement thisEvent = (Evenement) newEventsIt.next(); Node thisEventNode = null; if(!oldEvents.contains(thisEvent)) { // *** this is a new node *** thisEventNode = cloud.getNodeManager("evenement").createNode(); if(node==null) { thisEventNode.setStringValue("soort","parent"); thisEventNode.setIntValue("reageer",12); // ** default closing time 12 hours before event } else { thisEventNode.setStringValue("soort","child"); } // these values are set to their defaults (and will not be updated for child events) thisEventNode.setIntValue("min_aantal_deelnemers",0); thisEventNode.setIntValue("max_aantal_deelnemers",9999); thisEventNode.setIntValue("cur_aantal_deelnemers",0); thisEventNode.setStringValue("groepsexcursie","0"); // not used,<SUF> thisEventNode.setStringValue("adres_verplicht","0"); thisEventNode.setStringValue("aanmelden_vooraf","1"); thisEventNode.setStringValue("achteraf_bevestigen","1"); thisEventNode.setStringValue("voorkeur_verplicht","0"); thisEventNode.commit(); if(node==null) { node = thisEventNode; } else { Relation relation = node.createRelation(thisEventNode,cloud.getRelationManager("partrel")); relation.commit(); } } else { // *** this is an already existing node *** thisEventNode= cloud.getNode(thisEvent.getNumber()); oldEvents.remove(thisEvent); } String titel = evenementForm.getName(); titel = titel.substring(0,1).toUpperCase() + titel.substring(1); thisEventNode.setStringValue("titel",titel); thisEventNode.setLongValue("begindatum",(thisEvent.getBegin().getTime())/1000); thisEventNode.setLongValue("einddatum",(thisEvent.getEnd().getTime())/1000); thisEventNode.setStringValue("isspare",thisEvent.getIsSpareDate()); thisEventNode.setStringValue("isoninternet",thisEvent.getIsOnInternet()); if (!thisEventNode.getStringValue("iscanceled").equals(thisEvent.getIsCanceled())){ thisEventNode.setStringValue("iscanceled",thisEvent.getIsCanceled()); } thisEventNode.setStringValue("dagomschrijving",evenementForm.selectedDays(thisEvent.getNumber())); thisEventNode.commit(); NodeList userList = cloud.getNodeManager("users").getList("account='"+evenementForm.getUserId()+"'",null,null); if (userList.size()!=0) { userList.getNode(0).createRelation(thisEventNode,cloud.getRelationManager("schrijver")).commit(); } } // *** delete nodes not available in the user input from MMBase *** Iterator oldEventsIt = oldEvents.iterator(); while(oldEventsIt.hasNext()) { Evenement thisEvent = (Evenement) oldEventsIt.next(); Node oldEvent = cloud.getNode(thisEvent.getNumber()); oldEvent.delete(true); } if(action.equals("Opslaan")) { evenementForm.initDates("" + node.getNumber()); forwardAction = mapping.findForward("continue"); } else { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } } else if(action.equals("Voeg toe")) { // *** Voeg toe *** Evenement newEvent = new Evenement(evenementForm.nextNewNodeNumber()); evenementForm.update(newEvent); forwardAction = mapping.findForward("continue"); } else if(action.equals("Wijzig")) { // *** Wijzig *** TreeSet dates = evenementForm.getDates(); String selectedEvent = evenementForm.getSelectedEvent(); Iterator datesIterator = dates.iterator(); while(datesIterator.hasNext()) { Evenement thisEvent = (Evenement) datesIterator.next(); if(thisEvent.getNumber().equals(selectedEvent)) { evenementForm.update(thisEvent); } } forwardAction = mapping.findForward("continue"); } else if(action.equals("Wis")) { // *** Wis *** evenementForm.setBeginYear(""); evenementForm.setBeginMonth(""); evenementForm.setBeginDay(""); evenementForm.setBeginHour(""); evenementForm.setBeginMinute(""); evenementForm.setEndYear(""); evenementForm.setEndMonth(""); evenementForm.setEndDay(""); evenementForm.setEndHour(""); evenementForm.setEndMinute(""); evenementForm.setIsSpareDate("false"); evenementForm.setIsOnInternet("false"); evenementForm.setIsCanceled("false"); forwardAction = mapping.findForward("continue"); } else if(action.equals("Verwijder selectie")) { // *** Verwijder selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { datesMap.remove(selectedDates[i]); // *** could also remove from selectedDaysOfWeek, but this is not necessary *** } } evenementForm.setDates(new TreeSet(datesMap.values())); evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Activeer selectie")||action.equals("Annuleer selectie")) { // *** Annuleer / Activeer selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); if(action.equals("Activeer selectie")) { thisEvent.setIsCanceled("false"); } else { thisEvent.setIsCanceled("true"); } } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Periode -> data")) { // *** Periode -> data *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); evenementForm.createDatesFromPeriod(thisEvent); } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } return forwardAction; } }
212771_14
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is LeoCMS. * * The Initial Developer of the Original Code is * 'De Gemeente Leeuwarden' (The dutch municipality Leeuwarden). * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.evenementen.forms; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import org.mmbase.bridge.*; import org.mmbase.module.core.*; import org.mmbase.util.logging.*; import javax.servlet.*; import nl.leocms.evenementen.Evenement; import com.finalist.mmbase.util.CloudFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.*; /** * EvenementAction * * @author Henk Hangyi * * @struts:action name="EvenementForm" * path="/editors/evenementen/EvenementAction" * scope="request" * validate="true" * input="/editors/evenementen/evenement.jsp" * * @struts:action-forward name="success" path="/editors/evenementen/evenement.jsp" */ public class EvenementAction extends Action { private static final Logger log = Logging.getLoggerInstance(EvenementAction.class); private void removeObsoleteFormBean(ActionMapping mapping, HttpServletRequest request) { // *** Remove the obsolete form bean *** if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else { HttpSession session = request.getSession(); session.removeAttribute(mapping.getAttribute()); } } } /** * The actual perform function: MUST be implemented by subclasses. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("EvenementAction.execute()"); EvenementForm evenementForm = (EvenementForm) form; ActionForward forwardAction = null; String action = evenementForm.getAction(); if (isCancelled(request)) { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } else if(evenementForm.getButtons().getShowPastDates().pressed()) { // ****************** ShowPastDates ************* if(evenementForm.getShowPastDates().equals("true")) { evenementForm.setShowPastDates("false"); } else { evenementForm.setShowPastDates("true"); } forwardAction = mapping.findForward("continue"); } else if(action.indexOf("Opslaan")>-1) { // ********** Opslaan ******** // change history: // concurrent modification exception -> clone() // duplicated dates one not related to parent -> Iterators // flush the coming events cache (see nl.mmatch.CSVReader) MMBaseContext mc = new MMBaseContext(); ServletContext application = mc.getServletContext(); application.removeAttribute("events_till"); TreeSet newEvents = (TreeSet) evenementForm.getDates().clone(); log.info("newEvents = " + newEvents); TreeSet oldEvents = (TreeSet) evenementForm.getOldDates().clone(); log.info("oldEvents = " + oldEvents); Cloud cloud = CloudFactory.getCloud(); String nodeNumber = evenementForm.getNode(); Node node = null; if (!nodeNumber.equals("")) { node= cloud.getNode(nodeNumber); } Iterator newEventsIt = newEvents.iterator(); while(newEventsIt.hasNext()) { Evenement thisEvent = (Evenement) newEventsIt.next(); Node thisEventNode = null; if(!oldEvents.contains(thisEvent)) { // *** this is a new node *** thisEventNode = cloud.getNodeManager("evenement").createNode(); if(node==null) { thisEventNode.setStringValue("soort","parent"); thisEventNode.setIntValue("reageer",12); // ** default closing time 12 hours before event } else { thisEventNode.setStringValue("soort","child"); } // these values are set to their defaults (and will not be updated for child events) thisEventNode.setIntValue("min_aantal_deelnemers",0); thisEventNode.setIntValue("max_aantal_deelnemers",9999); thisEventNode.setIntValue("cur_aantal_deelnemers",0); thisEventNode.setStringValue("groepsexcursie","0"); // not used, see deelnemerscategorie.groepsactiviteit thisEventNode.setStringValue("adres_verplicht","0"); thisEventNode.setStringValue("aanmelden_vooraf","1"); thisEventNode.setStringValue("achteraf_bevestigen","1"); thisEventNode.setStringValue("voorkeur_verplicht","0"); thisEventNode.commit(); if(node==null) { node = thisEventNode; } else { Relation relation = node.createRelation(thisEventNode,cloud.getRelationManager("partrel")); relation.commit(); } } else { // *** this is an already existing node *** thisEventNode= cloud.getNode(thisEvent.getNumber()); oldEvents.remove(thisEvent); } String titel = evenementForm.getName(); titel = titel.substring(0,1).toUpperCase() + titel.substring(1); thisEventNode.setStringValue("titel",titel); thisEventNode.setLongValue("begindatum",(thisEvent.getBegin().getTime())/1000); thisEventNode.setLongValue("einddatum",(thisEvent.getEnd().getTime())/1000); thisEventNode.setStringValue("isspare",thisEvent.getIsSpareDate()); thisEventNode.setStringValue("isoninternet",thisEvent.getIsOnInternet()); if (!thisEventNode.getStringValue("iscanceled").equals(thisEvent.getIsCanceled())){ thisEventNode.setStringValue("iscanceled",thisEvent.getIsCanceled()); } thisEventNode.setStringValue("dagomschrijving",evenementForm.selectedDays(thisEvent.getNumber())); thisEventNode.commit(); NodeList userList = cloud.getNodeManager("users").getList("account='"+evenementForm.getUserId()+"'",null,null); if (userList.size()!=0) { userList.getNode(0).createRelation(thisEventNode,cloud.getRelationManager("schrijver")).commit(); } } // *** delete nodes not available in the user input from MMBase *** Iterator oldEventsIt = oldEvents.iterator(); while(oldEventsIt.hasNext()) { Evenement thisEvent = (Evenement) oldEventsIt.next(); Node oldEvent = cloud.getNode(thisEvent.getNumber()); oldEvent.delete(true); } if(action.equals("Opslaan")) { evenementForm.initDates("" + node.getNumber()); forwardAction = mapping.findForward("continue"); } else { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } } else if(action.equals("Voeg toe")) { // *** Voeg toe *** Evenement newEvent = new Evenement(evenementForm.nextNewNodeNumber()); evenementForm.update(newEvent); forwardAction = mapping.findForward("continue"); } else if(action.equals("Wijzig")) { // *** Wijzig *** TreeSet dates = evenementForm.getDates(); String selectedEvent = evenementForm.getSelectedEvent(); Iterator datesIterator = dates.iterator(); while(datesIterator.hasNext()) { Evenement thisEvent = (Evenement) datesIterator.next(); if(thisEvent.getNumber().equals(selectedEvent)) { evenementForm.update(thisEvent); } } forwardAction = mapping.findForward("continue"); } else if(action.equals("Wis")) { // *** Wis *** evenementForm.setBeginYear(""); evenementForm.setBeginMonth(""); evenementForm.setBeginDay(""); evenementForm.setBeginHour(""); evenementForm.setBeginMinute(""); evenementForm.setEndYear(""); evenementForm.setEndMonth(""); evenementForm.setEndDay(""); evenementForm.setEndHour(""); evenementForm.setEndMinute(""); evenementForm.setIsSpareDate("false"); evenementForm.setIsOnInternet("false"); evenementForm.setIsCanceled("false"); forwardAction = mapping.findForward("continue"); } else if(action.equals("Verwijder selectie")) { // *** Verwijder selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { datesMap.remove(selectedDates[i]); // *** could also remove from selectedDaysOfWeek, but this is not necessary *** } } evenementForm.setDates(new TreeSet(datesMap.values())); evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Activeer selectie")||action.equals("Annuleer selectie")) { // *** Annuleer / Activeer selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); if(action.equals("Activeer selectie")) { thisEvent.setIsCanceled("false"); } else { thisEvent.setIsCanceled("true"); } } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Periode -> data")) { // *** Periode -> data *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); evenementForm.createDatesFromPeriod(thisEvent); } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } return forwardAction; } }
mmbase/natmm
src/nl/leocms/evenementen/forms/EvenementAction.java
2,827
// *** Verwijder selectie ***
line_comment
nl
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is LeoCMS. * * The Initial Developer of the Original Code is * 'De Gemeente Leeuwarden' (The dutch municipality Leeuwarden). * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.evenementen.forms; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import org.mmbase.bridge.*; import org.mmbase.module.core.*; import org.mmbase.util.logging.*; import javax.servlet.*; import nl.leocms.evenementen.Evenement; import com.finalist.mmbase.util.CloudFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.*; /** * EvenementAction * * @author Henk Hangyi * * @struts:action name="EvenementForm" * path="/editors/evenementen/EvenementAction" * scope="request" * validate="true" * input="/editors/evenementen/evenement.jsp" * * @struts:action-forward name="success" path="/editors/evenementen/evenement.jsp" */ public class EvenementAction extends Action { private static final Logger log = Logging.getLoggerInstance(EvenementAction.class); private void removeObsoleteFormBean(ActionMapping mapping, HttpServletRequest request) { // *** Remove the obsolete form bean *** if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else { HttpSession session = request.getSession(); session.removeAttribute(mapping.getAttribute()); } } } /** * The actual perform function: MUST be implemented by subclasses. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("EvenementAction.execute()"); EvenementForm evenementForm = (EvenementForm) form; ActionForward forwardAction = null; String action = evenementForm.getAction(); if (isCancelled(request)) { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } else if(evenementForm.getButtons().getShowPastDates().pressed()) { // ****************** ShowPastDates ************* if(evenementForm.getShowPastDates().equals("true")) { evenementForm.setShowPastDates("false"); } else { evenementForm.setShowPastDates("true"); } forwardAction = mapping.findForward("continue"); } else if(action.indexOf("Opslaan")>-1) { // ********** Opslaan ******** // change history: // concurrent modification exception -> clone() // duplicated dates one not related to parent -> Iterators // flush the coming events cache (see nl.mmatch.CSVReader) MMBaseContext mc = new MMBaseContext(); ServletContext application = mc.getServletContext(); application.removeAttribute("events_till"); TreeSet newEvents = (TreeSet) evenementForm.getDates().clone(); log.info("newEvents = " + newEvents); TreeSet oldEvents = (TreeSet) evenementForm.getOldDates().clone(); log.info("oldEvents = " + oldEvents); Cloud cloud = CloudFactory.getCloud(); String nodeNumber = evenementForm.getNode(); Node node = null; if (!nodeNumber.equals("")) { node= cloud.getNode(nodeNumber); } Iterator newEventsIt = newEvents.iterator(); while(newEventsIt.hasNext()) { Evenement thisEvent = (Evenement) newEventsIt.next(); Node thisEventNode = null; if(!oldEvents.contains(thisEvent)) { // *** this is a new node *** thisEventNode = cloud.getNodeManager("evenement").createNode(); if(node==null) { thisEventNode.setStringValue("soort","parent"); thisEventNode.setIntValue("reageer",12); // ** default closing time 12 hours before event } else { thisEventNode.setStringValue("soort","child"); } // these values are set to their defaults (and will not be updated for child events) thisEventNode.setIntValue("min_aantal_deelnemers",0); thisEventNode.setIntValue("max_aantal_deelnemers",9999); thisEventNode.setIntValue("cur_aantal_deelnemers",0); thisEventNode.setStringValue("groepsexcursie","0"); // not used, see deelnemerscategorie.groepsactiviteit thisEventNode.setStringValue("adres_verplicht","0"); thisEventNode.setStringValue("aanmelden_vooraf","1"); thisEventNode.setStringValue("achteraf_bevestigen","1"); thisEventNode.setStringValue("voorkeur_verplicht","0"); thisEventNode.commit(); if(node==null) { node = thisEventNode; } else { Relation relation = node.createRelation(thisEventNode,cloud.getRelationManager("partrel")); relation.commit(); } } else { // *** this is an already existing node *** thisEventNode= cloud.getNode(thisEvent.getNumber()); oldEvents.remove(thisEvent); } String titel = evenementForm.getName(); titel = titel.substring(0,1).toUpperCase() + titel.substring(1); thisEventNode.setStringValue("titel",titel); thisEventNode.setLongValue("begindatum",(thisEvent.getBegin().getTime())/1000); thisEventNode.setLongValue("einddatum",(thisEvent.getEnd().getTime())/1000); thisEventNode.setStringValue("isspare",thisEvent.getIsSpareDate()); thisEventNode.setStringValue("isoninternet",thisEvent.getIsOnInternet()); if (!thisEventNode.getStringValue("iscanceled").equals(thisEvent.getIsCanceled())){ thisEventNode.setStringValue("iscanceled",thisEvent.getIsCanceled()); } thisEventNode.setStringValue("dagomschrijving",evenementForm.selectedDays(thisEvent.getNumber())); thisEventNode.commit(); NodeList userList = cloud.getNodeManager("users").getList("account='"+evenementForm.getUserId()+"'",null,null); if (userList.size()!=0) { userList.getNode(0).createRelation(thisEventNode,cloud.getRelationManager("schrijver")).commit(); } } // *** delete nodes not available in the user input from MMBase *** Iterator oldEventsIt = oldEvents.iterator(); while(oldEventsIt.hasNext()) { Evenement thisEvent = (Evenement) oldEventsIt.next(); Node oldEvent = cloud.getNode(thisEvent.getNumber()); oldEvent.delete(true); } if(action.equals("Opslaan")) { evenementForm.initDates("" + node.getNumber()); forwardAction = mapping.findForward("continue"); } else { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } } else if(action.equals("Voeg toe")) { // *** Voeg toe *** Evenement newEvent = new Evenement(evenementForm.nextNewNodeNumber()); evenementForm.update(newEvent); forwardAction = mapping.findForward("continue"); } else if(action.equals("Wijzig")) { // *** Wijzig *** TreeSet dates = evenementForm.getDates(); String selectedEvent = evenementForm.getSelectedEvent(); Iterator datesIterator = dates.iterator(); while(datesIterator.hasNext()) { Evenement thisEvent = (Evenement) datesIterator.next(); if(thisEvent.getNumber().equals(selectedEvent)) { evenementForm.update(thisEvent); } } forwardAction = mapping.findForward("continue"); } else if(action.equals("Wis")) { // *** Wis *** evenementForm.setBeginYear(""); evenementForm.setBeginMonth(""); evenementForm.setBeginDay(""); evenementForm.setBeginHour(""); evenementForm.setBeginMinute(""); evenementForm.setEndYear(""); evenementForm.setEndMonth(""); evenementForm.setEndDay(""); evenementForm.setEndHour(""); evenementForm.setEndMinute(""); evenementForm.setIsSpareDate("false"); evenementForm.setIsOnInternet("false"); evenementForm.setIsCanceled("false"); forwardAction = mapping.findForward("continue"); } else if(action.equals("Verwijder selectie")) { // *** Verwijder selectie<SUF> String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { datesMap.remove(selectedDates[i]); // *** could also remove from selectedDaysOfWeek, but this is not necessary *** } } evenementForm.setDates(new TreeSet(datesMap.values())); evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Activeer selectie")||action.equals("Annuleer selectie")) { // *** Annuleer / Activeer selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); if(action.equals("Activeer selectie")) { thisEvent.setIsCanceled("false"); } else { thisEvent.setIsCanceled("true"); } } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Periode -> data")) { // *** Periode -> data *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); evenementForm.createDatesFromPeriod(thisEvent); } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } return forwardAction; } }
212771_16
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is LeoCMS. * * The Initial Developer of the Original Code is * 'De Gemeente Leeuwarden' (The dutch municipality Leeuwarden). * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.evenementen.forms; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import org.mmbase.bridge.*; import org.mmbase.module.core.*; import org.mmbase.util.logging.*; import javax.servlet.*; import nl.leocms.evenementen.Evenement; import com.finalist.mmbase.util.CloudFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.*; /** * EvenementAction * * @author Henk Hangyi * * @struts:action name="EvenementForm" * path="/editors/evenementen/EvenementAction" * scope="request" * validate="true" * input="/editors/evenementen/evenement.jsp" * * @struts:action-forward name="success" path="/editors/evenementen/evenement.jsp" */ public class EvenementAction extends Action { private static final Logger log = Logging.getLoggerInstance(EvenementAction.class); private void removeObsoleteFormBean(ActionMapping mapping, HttpServletRequest request) { // *** Remove the obsolete form bean *** if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else { HttpSession session = request.getSession(); session.removeAttribute(mapping.getAttribute()); } } } /** * The actual perform function: MUST be implemented by subclasses. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("EvenementAction.execute()"); EvenementForm evenementForm = (EvenementForm) form; ActionForward forwardAction = null; String action = evenementForm.getAction(); if (isCancelled(request)) { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } else if(evenementForm.getButtons().getShowPastDates().pressed()) { // ****************** ShowPastDates ************* if(evenementForm.getShowPastDates().equals("true")) { evenementForm.setShowPastDates("false"); } else { evenementForm.setShowPastDates("true"); } forwardAction = mapping.findForward("continue"); } else if(action.indexOf("Opslaan")>-1) { // ********** Opslaan ******** // change history: // concurrent modification exception -> clone() // duplicated dates one not related to parent -> Iterators // flush the coming events cache (see nl.mmatch.CSVReader) MMBaseContext mc = new MMBaseContext(); ServletContext application = mc.getServletContext(); application.removeAttribute("events_till"); TreeSet newEvents = (TreeSet) evenementForm.getDates().clone(); log.info("newEvents = " + newEvents); TreeSet oldEvents = (TreeSet) evenementForm.getOldDates().clone(); log.info("oldEvents = " + oldEvents); Cloud cloud = CloudFactory.getCloud(); String nodeNumber = evenementForm.getNode(); Node node = null; if (!nodeNumber.equals("")) { node= cloud.getNode(nodeNumber); } Iterator newEventsIt = newEvents.iterator(); while(newEventsIt.hasNext()) { Evenement thisEvent = (Evenement) newEventsIt.next(); Node thisEventNode = null; if(!oldEvents.contains(thisEvent)) { // *** this is a new node *** thisEventNode = cloud.getNodeManager("evenement").createNode(); if(node==null) { thisEventNode.setStringValue("soort","parent"); thisEventNode.setIntValue("reageer",12); // ** default closing time 12 hours before event } else { thisEventNode.setStringValue("soort","child"); } // these values are set to their defaults (and will not be updated for child events) thisEventNode.setIntValue("min_aantal_deelnemers",0); thisEventNode.setIntValue("max_aantal_deelnemers",9999); thisEventNode.setIntValue("cur_aantal_deelnemers",0); thisEventNode.setStringValue("groepsexcursie","0"); // not used, see deelnemerscategorie.groepsactiviteit thisEventNode.setStringValue("adres_verplicht","0"); thisEventNode.setStringValue("aanmelden_vooraf","1"); thisEventNode.setStringValue("achteraf_bevestigen","1"); thisEventNode.setStringValue("voorkeur_verplicht","0"); thisEventNode.commit(); if(node==null) { node = thisEventNode; } else { Relation relation = node.createRelation(thisEventNode,cloud.getRelationManager("partrel")); relation.commit(); } } else { // *** this is an already existing node *** thisEventNode= cloud.getNode(thisEvent.getNumber()); oldEvents.remove(thisEvent); } String titel = evenementForm.getName(); titel = titel.substring(0,1).toUpperCase() + titel.substring(1); thisEventNode.setStringValue("titel",titel); thisEventNode.setLongValue("begindatum",(thisEvent.getBegin().getTime())/1000); thisEventNode.setLongValue("einddatum",(thisEvent.getEnd().getTime())/1000); thisEventNode.setStringValue("isspare",thisEvent.getIsSpareDate()); thisEventNode.setStringValue("isoninternet",thisEvent.getIsOnInternet()); if (!thisEventNode.getStringValue("iscanceled").equals(thisEvent.getIsCanceled())){ thisEventNode.setStringValue("iscanceled",thisEvent.getIsCanceled()); } thisEventNode.setStringValue("dagomschrijving",evenementForm.selectedDays(thisEvent.getNumber())); thisEventNode.commit(); NodeList userList = cloud.getNodeManager("users").getList("account='"+evenementForm.getUserId()+"'",null,null); if (userList.size()!=0) { userList.getNode(0).createRelation(thisEventNode,cloud.getRelationManager("schrijver")).commit(); } } // *** delete nodes not available in the user input from MMBase *** Iterator oldEventsIt = oldEvents.iterator(); while(oldEventsIt.hasNext()) { Evenement thisEvent = (Evenement) oldEventsIt.next(); Node oldEvent = cloud.getNode(thisEvent.getNumber()); oldEvent.delete(true); } if(action.equals("Opslaan")) { evenementForm.initDates("" + node.getNumber()); forwardAction = mapping.findForward("continue"); } else { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } } else if(action.equals("Voeg toe")) { // *** Voeg toe *** Evenement newEvent = new Evenement(evenementForm.nextNewNodeNumber()); evenementForm.update(newEvent); forwardAction = mapping.findForward("continue"); } else if(action.equals("Wijzig")) { // *** Wijzig *** TreeSet dates = evenementForm.getDates(); String selectedEvent = evenementForm.getSelectedEvent(); Iterator datesIterator = dates.iterator(); while(datesIterator.hasNext()) { Evenement thisEvent = (Evenement) datesIterator.next(); if(thisEvent.getNumber().equals(selectedEvent)) { evenementForm.update(thisEvent); } } forwardAction = mapping.findForward("continue"); } else if(action.equals("Wis")) { // *** Wis *** evenementForm.setBeginYear(""); evenementForm.setBeginMonth(""); evenementForm.setBeginDay(""); evenementForm.setBeginHour(""); evenementForm.setBeginMinute(""); evenementForm.setEndYear(""); evenementForm.setEndMonth(""); evenementForm.setEndDay(""); evenementForm.setEndHour(""); evenementForm.setEndMinute(""); evenementForm.setIsSpareDate("false"); evenementForm.setIsOnInternet("false"); evenementForm.setIsCanceled("false"); forwardAction = mapping.findForward("continue"); } else if(action.equals("Verwijder selectie")) { // *** Verwijder selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { datesMap.remove(selectedDates[i]); // *** could also remove from selectedDaysOfWeek, but this is not necessary *** } } evenementForm.setDates(new TreeSet(datesMap.values())); evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Activeer selectie")||action.equals("Annuleer selectie")) { // *** Annuleer / Activeer selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); if(action.equals("Activeer selectie")) { thisEvent.setIsCanceled("false"); } else { thisEvent.setIsCanceled("true"); } } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Periode -> data")) { // *** Periode -> data *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); evenementForm.createDatesFromPeriod(thisEvent); } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } return forwardAction; } }
mmbase/natmm
src/nl/leocms/evenementen/forms/EvenementAction.java
2,827
// *** Annuleer / Activeer selectie ***
line_comment
nl
/* * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is LeoCMS. * * The Initial Developer of the Original Code is * 'De Gemeente Leeuwarden' (The dutch municipality Leeuwarden). * * See license.txt in the root of the LeoCMS directory for the full license. */ package nl.leocms.evenementen.forms; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import org.mmbase.bridge.*; import org.mmbase.module.core.*; import org.mmbase.util.logging.*; import javax.servlet.*; import nl.leocms.evenementen.Evenement; import com.finalist.mmbase.util.CloudFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.*; /** * EvenementAction * * @author Henk Hangyi * * @struts:action name="EvenementForm" * path="/editors/evenementen/EvenementAction" * scope="request" * validate="true" * input="/editors/evenementen/evenement.jsp" * * @struts:action-forward name="success" path="/editors/evenementen/evenement.jsp" */ public class EvenementAction extends Action { private static final Logger log = Logging.getLoggerInstance(EvenementAction.class); private void removeObsoleteFormBean(ActionMapping mapping, HttpServletRequest request) { // *** Remove the obsolete form bean *** if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else { HttpSession session = request.getSession(); session.removeAttribute(mapping.getAttribute()); } } } /** * The actual perform function: MUST be implemented by subclasses. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("EvenementAction.execute()"); EvenementForm evenementForm = (EvenementForm) form; ActionForward forwardAction = null; String action = evenementForm.getAction(); if (isCancelled(request)) { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } else if(evenementForm.getButtons().getShowPastDates().pressed()) { // ****************** ShowPastDates ************* if(evenementForm.getShowPastDates().equals("true")) { evenementForm.setShowPastDates("false"); } else { evenementForm.setShowPastDates("true"); } forwardAction = mapping.findForward("continue"); } else if(action.indexOf("Opslaan")>-1) { // ********** Opslaan ******** // change history: // concurrent modification exception -> clone() // duplicated dates one not related to parent -> Iterators // flush the coming events cache (see nl.mmatch.CSVReader) MMBaseContext mc = new MMBaseContext(); ServletContext application = mc.getServletContext(); application.removeAttribute("events_till"); TreeSet newEvents = (TreeSet) evenementForm.getDates().clone(); log.info("newEvents = " + newEvents); TreeSet oldEvents = (TreeSet) evenementForm.getOldDates().clone(); log.info("oldEvents = " + oldEvents); Cloud cloud = CloudFactory.getCloud(); String nodeNumber = evenementForm.getNode(); Node node = null; if (!nodeNumber.equals("")) { node= cloud.getNode(nodeNumber); } Iterator newEventsIt = newEvents.iterator(); while(newEventsIt.hasNext()) { Evenement thisEvent = (Evenement) newEventsIt.next(); Node thisEventNode = null; if(!oldEvents.contains(thisEvent)) { // *** this is a new node *** thisEventNode = cloud.getNodeManager("evenement").createNode(); if(node==null) { thisEventNode.setStringValue("soort","parent"); thisEventNode.setIntValue("reageer",12); // ** default closing time 12 hours before event } else { thisEventNode.setStringValue("soort","child"); } // these values are set to their defaults (and will not be updated for child events) thisEventNode.setIntValue("min_aantal_deelnemers",0); thisEventNode.setIntValue("max_aantal_deelnemers",9999); thisEventNode.setIntValue("cur_aantal_deelnemers",0); thisEventNode.setStringValue("groepsexcursie","0"); // not used, see deelnemerscategorie.groepsactiviteit thisEventNode.setStringValue("adres_verplicht","0"); thisEventNode.setStringValue("aanmelden_vooraf","1"); thisEventNode.setStringValue("achteraf_bevestigen","1"); thisEventNode.setStringValue("voorkeur_verplicht","0"); thisEventNode.commit(); if(node==null) { node = thisEventNode; } else { Relation relation = node.createRelation(thisEventNode,cloud.getRelationManager("partrel")); relation.commit(); } } else { // *** this is an already existing node *** thisEventNode= cloud.getNode(thisEvent.getNumber()); oldEvents.remove(thisEvent); } String titel = evenementForm.getName(); titel = titel.substring(0,1).toUpperCase() + titel.substring(1); thisEventNode.setStringValue("titel",titel); thisEventNode.setLongValue("begindatum",(thisEvent.getBegin().getTime())/1000); thisEventNode.setLongValue("einddatum",(thisEvent.getEnd().getTime())/1000); thisEventNode.setStringValue("isspare",thisEvent.getIsSpareDate()); thisEventNode.setStringValue("isoninternet",thisEvent.getIsOnInternet()); if (!thisEventNode.getStringValue("iscanceled").equals(thisEvent.getIsCanceled())){ thisEventNode.setStringValue("iscanceled",thisEvent.getIsCanceled()); } thisEventNode.setStringValue("dagomschrijving",evenementForm.selectedDays(thisEvent.getNumber())); thisEventNode.commit(); NodeList userList = cloud.getNodeManager("users").getList("account='"+evenementForm.getUserId()+"'",null,null); if (userList.size()!=0) { userList.getNode(0).createRelation(thisEventNode,cloud.getRelationManager("schrijver")).commit(); } } // *** delete nodes not available in the user input from MMBase *** Iterator oldEventsIt = oldEvents.iterator(); while(oldEventsIt.hasNext()) { Evenement thisEvent = (Evenement) oldEventsIt.next(); Node oldEvent = cloud.getNode(thisEvent.getNumber()); oldEvent.delete(true); } if(action.equals("Opslaan")) { evenementForm.initDates("" + node.getNumber()); forwardAction = mapping.findForward("continue"); } else { removeObsoleteFormBean(mapping, request); forwardAction = mapping.findForward("success"); } } else if(action.equals("Voeg toe")) { // *** Voeg toe *** Evenement newEvent = new Evenement(evenementForm.nextNewNodeNumber()); evenementForm.update(newEvent); forwardAction = mapping.findForward("continue"); } else if(action.equals("Wijzig")) { // *** Wijzig *** TreeSet dates = evenementForm.getDates(); String selectedEvent = evenementForm.getSelectedEvent(); Iterator datesIterator = dates.iterator(); while(datesIterator.hasNext()) { Evenement thisEvent = (Evenement) datesIterator.next(); if(thisEvent.getNumber().equals(selectedEvent)) { evenementForm.update(thisEvent); } } forwardAction = mapping.findForward("continue"); } else if(action.equals("Wis")) { // *** Wis *** evenementForm.setBeginYear(""); evenementForm.setBeginMonth(""); evenementForm.setBeginDay(""); evenementForm.setBeginHour(""); evenementForm.setBeginMinute(""); evenementForm.setEndYear(""); evenementForm.setEndMonth(""); evenementForm.setEndDay(""); evenementForm.setEndHour(""); evenementForm.setEndMinute(""); evenementForm.setIsSpareDate("false"); evenementForm.setIsOnInternet("false"); evenementForm.setIsCanceled("false"); forwardAction = mapping.findForward("continue"); } else if(action.equals("Verwijder selectie")) { // *** Verwijder selectie *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { datesMap.remove(selectedDates[i]); // *** could also remove from selectedDaysOfWeek, but this is not necessary *** } } evenementForm.setDates(new TreeSet(datesMap.values())); evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Activeer selectie")||action.equals("Annuleer selectie")) { // *** Annuleer /<SUF> String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); if(action.equals("Activeer selectie")) { thisEvent.setIsCanceled("false"); } else { thisEvent.setIsCanceled("true"); } } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } else if(action.equals("Periode -> data")) { // *** Periode -> data *** String [] selectedDates = evenementForm.getSelectedDates(); TreeMap datesMap = evenementForm.getDatesMap(); for(int i=0; i< selectedDates.length; i++) { if(datesMap.containsKey(selectedDates[i])) { Evenement thisEvent = (Evenement) datesMap.get(selectedDates[i]); evenementForm.createDatesFromPeriod(thisEvent); } } evenementForm.setSelectedDates(null); forwardAction = mapping.findForward("continue"); } return forwardAction; } }
212801_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2016/migratie 2016-02-09/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
567
/** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response<SUF>*/ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
212801_2
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2016/migratie 2016-02-09/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
567
/** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. <SUF>*/ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
212801_3
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2016/migratie 2016-02-09/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
567
/** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de<SUF>*/ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
212801_4
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2016/migratie 2016-02-09/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
567
/** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde<SUF>*/ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
212801_5
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2016/migratie 2016-02-09/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
567
/** * Geef de waarde van fout regels. * * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param list * De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde<SUF>*/ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
212802_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen lijst. */ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2013/migratie 2013-02-13/migr-ggo-viewer/src/main/java/nl/moderniseringgba/migratie/conversie/viewer/ViewerResponse.java
504
/** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response<SUF>*/ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen lijst. */ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
212802_2
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen lijst. */ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2013/migratie 2013-02-13/migr-ggo-viewer/src/main/java/nl/moderniseringgba/migratie/conversie/viewer/ViewerResponse.java
504
/** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. <SUF>*/ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen lijst. */ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
212802_3
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen lijst. */ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2013/migratie 2013-02-13/migr-ggo-viewer/src/main/java/nl/moderniseringgba/migratie/conversie/viewer/ViewerResponse.java
504
/** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de<SUF>*/ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen lijst. */ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
212802_4
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen lijst. */ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2013/migratie 2013-02-13/migr-ggo-viewer/src/main/java/nl/moderniseringgba/migratie/conversie/viewer/ViewerResponse.java
504
/** * @return De persoonslijstGroepen lijst. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen<SUF>*/ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
212802_5
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen lijst. */ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
MinBZK/OperatieBRP
2013/migratie 2013-02-13/migr-ggo-viewer/src/main/java/nl/moderniseringgba/migratie/conversie/viewer/ViewerResponse.java
504
/** * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.moderniseringgba.migratie.conversie.viewer; import java.util.List; import nl.moderniseringgba.migratie.conversie.viewer.log.FoutRegel; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<PersoonslijstGroep> persoonslijstGroepen; private final List<FoutRegel> foutRegels; /** * Constructor. * * @param persoonslijstGroepen * De lijst met persoonslijstgroepen. * @param foutRegels * De lijst met foutRegels. */ public ViewerResponse(final List<PersoonslijstGroep> persoonslijstGroepen, final List<FoutRegel> foutRegels) { this.persoonslijstGroepen = persoonslijstGroepen; this.foutRegels = foutRegels; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * @return De persoonslijstGroepen lijst. */ public final List<PersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * @return Een lijst<SUF>*/ public final List<FoutRegel> getFoutRegels() { return foutRegels; } }
212803_0
/* Deze broncode is openbaar gemaakt vanwege een Woo-verzoek zodat deze gericht is op transparantie en niet op hergebruik. Hergebruik van de broncode is toegestaan onder de EUPL licentie, met uitzondering van broncode waarvoor een andere licentie is aangegeven. Het archief waar dit bestand deel van uitmaakt is te vinden op: https://github.com/MinBZK/woo-besluit-broncode-digid Eventuele kwetsbaarheden kunnen worden gemeld bij het NCSC via: https://www.ncsc.nl/contact/kwetsbaarheid-melden onder vermelding van "Logius, openbaar gemaakte broncode DigiD" Voor overige vragen over dit Woo-besluit kunt u mailen met [email protected] This code has been disclosed in response to a request under the Dutch Open Government Act ("Wet open Overheid"). This implies that publication is primarily driven by the need for transparence, not re-use. Re-use is permitted under the EUPL-license, with the exception of source files that contain a different license. The archive that this file originates from can be found at: https://github.com/MinBZK/woo-besluit-broncode-digid Security vulnerabilities may be responsibly disclosed via the Dutch NCSC: https://www.ncsc.nl/contact/kwetsbaarheid-melden using the reference "Logius, publicly disclosed source code DigiD" Other questions regarding this Open Goverment Act decision may be directed via email to [email protected] */ package nl.logius.digid.app.config; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.oas.models.tags.Tag; import nl.logius.digid.sharedlib.config.AbstractSwaggerConfig; import org.springdoc.core.GroupedOpenApi; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.List; @Configuration public class SwaggerConfig extends AbstractSwaggerConfig { public static final String REQUEST_ACCOUNT_AND_APP = "DigiD app - Aanvragen DigiD account (en Digid app) via de app (zonder gn/ww)"; public static final String REQUEST_ACCOUNT_AND_APP_DESCRIPTION = "Startpunt -> geen DigiD account OF account in aanvraag. Actie -> Aanvragen DigiD account en app (via de app) zonder gebruikersnaam en wachtwoord. Optioneel om na het versturen van de brief (gebeurt op het endpoint /apps/pincode) de ID-check uit te voeren. Eindresultaat -> DigiD account en app aangevraagd en activatiebrief verstuurd. Indien ID-check uitgevoerd de aanvraag is op niveau Substantieel."; public static final String ACTIVATE_LETTER = "DigiD app - Activeren met basis authenticatie en notificatie brief"; public static final String ACTIVATE_LETTER_DESCRIPTION = "Startpunt -> Een actief DigiD account, geen sms-controle aan EN geen NFC-lezer OF ID-check niet mogelijk/negeren. Actie -> Alternatieve activatie op niveau Midden. Eindresultaat -> Geactiveerde app op niveau Midden. Notificatiebrief ontvangen."; public static final String ACTIVATE_SMS = "DigiD app - Activeren met basis authenticatie en sms verificatie"; public static final String ACTIVATE_SMS_DESCRIPTION = "Startpunt -> Een actief DigiD account, sms-controle aan EN geen NFC-lezer OF ID-check niet mogelijk/negeren. Actie -> Alternatieve activatie op niveau Midden met sms-controle. Eindresultaat -> Geactiveerde app op niveau Midden."; public static final String ACTIVATE_RDA = "DigiD app - Activeren met basis authenticatie en ID-check"; public static final String ACTIVATE_RDA_DESCRIPTION = "Startpunt -> Een actief DigiD account op basis/midden niveau. Actie -> DigiD app activeren op Substantieel door het uitvoeren van de ID-check (indien ID-check negeren/niet mogelijk wordt een alternatief activatieproces gestart). Eindresultaat -> Geactiveerde app op niveau Substantieel."; public static final String ACTIVATE_WITH_APP = "DigiD app - Activeren app met andere DigiD app"; public static final String ACTIVATE_WITH_APP_DESCRIPTION = ""; public static final String RS_ACTIVATE_WITH_APP = "DigiD app - Activeren app bij aanvraagstation"; public static final String RS_ACTIVATE_WITH_APP_DESCRIPTION = ""; public static final String ACTIVATE_WEBSITE = "DigiD app - Activeren account en app na aanvraag via de website"; public static final String ACTIVATE_WEBSITE_DESCRIPTION = "Startpunt -> aangevraagd account met gn/ww en eventueel sms (via de website). Actie -> Activeren van je account via een nieuwe app. Eindresultaat -> Actief account met een nieuwe app"; public static final String ACTIVATE_APP_WITH_CODE = "DigiD app - Invoer activeringscode brief (aangevraag via app/aanvraagstation) in app met status: Wacht op activering"; public static final String ACTIVATE_APP_WITH_CODE_DESCRIPTION = "DigiD app - Invoer activeringscode brief (aangevraag via app/aanvraagstation) in app met status: Wacht op activering"; public static final String UPGRADE_LOGIN_LEVEL = "DigiD app - Verhogen inlogniveau naar substantieel"; public static final String UPGRADE_LOGIN_LEVEL_DESCRIPTION = "DigiD app - Verhogen inlogniveau naar substantieel"; public static final String RE_APPLY_ACTIVATIONCODE = "DigiD app - Heraanvraag brief met activeringscode voor DigiD account en app (via app of gemeentebalie)"; public static final String RE_APPLY_ACTIVATIONCODE_DESCRIPTION = "DigiD app - Heraanvraag brief met activeringscode voor DigiD account en app (via app of gemeentebalie)"; public static final String AUTH_WITH_WID = "DigiD app - Authenticeren met identiteitsdocument (DigiD Hoog)"; public static final String AUTH_WITH_WID_DESCRIPTION = "Startpunt -> Een actief DigiD account met geactiveerd hoog middel. Actie -> Inloggen met identiteitsdocument op niveau hoog Eindresultaat -> Ingelogd bij webdienst op niveau hoog"; public static final String HEADER = "header"; public static final String MANAGE_ACCOUNT_SESSION = "DigiD app - Accounthandelingen Mijn DigiD"; public static final String PINCODE_RESET_OF_APP = "DigiD app - Reset pincode of app"; public static final String WIDCHECKER_RAISE_TO_SUB = "DigiD Wid Checker - Verhogen naar substantieel"; public static final String APP_LOGIN = "DigiD app - Starten app (inloggen met pincode)"; public static final String APP_LOGIN_DESCRIPTION = "Bij het openen van de app wordt je gelijk gevraagd om te authenticeren met pincode, voor andere flows die hierna komen hoeft niet meer te worden geauthenticeerd alleen eventueel bevestigd."; public static final String CONFIRM_SESSION = "DigiD app - Bevestigen actie/login met geauthenticeerde sessie"; public static final String SHARED = "Shared endpoints"; public static final String SHARED_DESCRIPTION = "Bij het starten van de app haalt deze een aantal gegevens op via deze endpoints. Bijv of switches aan/of uit."; @Value("${urls.external.app}") private String appBaseUrl; @Bean public GroupedOpenApi publicOpenApi() { var paths = new String[]{"/iapi/**", "/apps/**"}; return GroupedOpenApi.builder().group("Public-api").pathsToMatch(paths).build(); } @Override public OpenAPI IapiOpenAPI(){ return new OpenAPI().addServersItem(new Server().url(appBaseUrl)) .components(new Components() .addParameters("API-V", apiVersionHeader()) .addParameters("OS-T", osTypeHeader()) .addParameters("APP-V", appVersionHeader()) .addParameters("OS-V", osVersionHeader()) .addParameters("REL-T", releaseTypeHeader()) .addParameters("X-Auth-Token", xAuthToken()) ).tags(getFlowTags()); } public List<Tag> getFlowTags(){ return List.of( createTag(REQUEST_ACCOUNT_AND_APP, REQUEST_ACCOUNT_AND_APP_DESCRIPTION), createTag(ACTIVATE_LETTER, ACTIVATE_LETTER_DESCRIPTION), createTag(ACTIVATE_SMS, ACTIVATE_SMS_DESCRIPTION), createTag(ACTIVATE_RDA, ACTIVATE_RDA_DESCRIPTION), createTag(ACTIVATE_WITH_APP, ACTIVATE_WITH_APP_DESCRIPTION), createTag(ACTIVATE_APP_WITH_CODE, ACTIVATE_APP_WITH_CODE_DESCRIPTION), createTag(AUTH_WITH_WID, AUTH_WITH_WID_DESCRIPTION), createTag(RE_APPLY_ACTIVATIONCODE, RE_APPLY_ACTIVATIONCODE_DESCRIPTION), createTag(RS_ACTIVATE_WITH_APP, RS_ACTIVATE_WITH_APP_DESCRIPTION), createTag(UPGRADE_LOGIN_LEVEL, UPGRADE_LOGIN_LEVEL_DESCRIPTION), createTag(APP_LOGIN, APP_LOGIN_DESCRIPTION), createTag(ACTIVATE_WEBSITE, ACTIVATE_WEBSITE_DESCRIPTION), createTag(SHARED, SHARED_DESCRIPTION) ); } private Tag createTag(String name, String description) { var tag = new Tag(); tag.setName(name); tag.setDescription(description); return tag; } protected static Parameter apiVersionHeader() { return new Parameter() .in(HEADER) .name("API-Version") .description("API-Version") .example("1") .required(true) .schema(new StringSchema()); } protected static Parameter osTypeHeader() { return new Parameter() .in(HEADER) .name("OS-Type") .description("OS-Type") .example("Android") .required(true) .schema(new StringSchema()); } protected static Parameter appVersionHeader() { return new Parameter() .in(HEADER) .name("App-version") .description("App-version") .example("1.0.0") .required(true) .schema(new StringSchema()); } protected static Parameter osVersionHeader() { return new Parameter() .in(HEADER) .name("OS-Version") .description("OS-Version") .example("10") .required(true) .schema(new StringSchema()); } protected static Parameter releaseTypeHeader() { return new Parameter() .in(HEADER) .name("Release-Type") .description("Release-Type") .example("Productie") .required(true) .schema(new StringSchema()); } protected static Parameter xAuthToken() { return new Parameter() .in("header") .name("X-Auth-Token") .description("X-Auth-Token") .example("development") .required(true) .schema(new StringSchema()); } }
MinBZK/woo-besluit-broncode-digid
components/digid_app/src/main/java/nl/logius/digid/app/config/SwaggerConfig.java
2,786
/* Deze broncode is openbaar gemaakt vanwege een Woo-verzoek zodat deze gericht is op transparantie en niet op hergebruik. Hergebruik van de broncode is toegestaan onder de EUPL licentie, met uitzondering van broncode waarvoor een andere licentie is aangegeven. Het archief waar dit bestand deel van uitmaakt is te vinden op: https://github.com/MinBZK/woo-besluit-broncode-digid Eventuele kwetsbaarheden kunnen worden gemeld bij het NCSC via: https://www.ncsc.nl/contact/kwetsbaarheid-melden onder vermelding van "Logius, openbaar gemaakte broncode DigiD" Voor overige vragen over dit Woo-besluit kunt u mailen met [email protected] This code has been disclosed in response to a request under the Dutch Open Government Act ("Wet open Overheid"). This implies that publication is primarily driven by the need for transparence, not re-use. Re-use is permitted under the EUPL-license, with the exception of source files that contain a different license. The archive that this file originates from can be found at: https://github.com/MinBZK/woo-besluit-broncode-digid Security vulnerabilities may be responsibly disclosed via the Dutch NCSC: https://www.ncsc.nl/contact/kwetsbaarheid-melden using the reference "Logius, publicly disclosed source code DigiD" Other questions regarding this Open Goverment Act decision may be directed via email to [email protected] */
block_comment
nl
/* Deze broncode is<SUF>*/ package nl.logius.digid.app.config; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.oas.models.tags.Tag; import nl.logius.digid.sharedlib.config.AbstractSwaggerConfig; import org.springdoc.core.GroupedOpenApi; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.List; @Configuration public class SwaggerConfig extends AbstractSwaggerConfig { public static final String REQUEST_ACCOUNT_AND_APP = "DigiD app - Aanvragen DigiD account (en Digid app) via de app (zonder gn/ww)"; public static final String REQUEST_ACCOUNT_AND_APP_DESCRIPTION = "Startpunt -> geen DigiD account OF account in aanvraag. Actie -> Aanvragen DigiD account en app (via de app) zonder gebruikersnaam en wachtwoord. Optioneel om na het versturen van de brief (gebeurt op het endpoint /apps/pincode) de ID-check uit te voeren. Eindresultaat -> DigiD account en app aangevraagd en activatiebrief verstuurd. Indien ID-check uitgevoerd de aanvraag is op niveau Substantieel."; public static final String ACTIVATE_LETTER = "DigiD app - Activeren met basis authenticatie en notificatie brief"; public static final String ACTIVATE_LETTER_DESCRIPTION = "Startpunt -> Een actief DigiD account, geen sms-controle aan EN geen NFC-lezer OF ID-check niet mogelijk/negeren. Actie -> Alternatieve activatie op niveau Midden. Eindresultaat -> Geactiveerde app op niveau Midden. Notificatiebrief ontvangen."; public static final String ACTIVATE_SMS = "DigiD app - Activeren met basis authenticatie en sms verificatie"; public static final String ACTIVATE_SMS_DESCRIPTION = "Startpunt -> Een actief DigiD account, sms-controle aan EN geen NFC-lezer OF ID-check niet mogelijk/negeren. Actie -> Alternatieve activatie op niveau Midden met sms-controle. Eindresultaat -> Geactiveerde app op niveau Midden."; public static final String ACTIVATE_RDA = "DigiD app - Activeren met basis authenticatie en ID-check"; public static final String ACTIVATE_RDA_DESCRIPTION = "Startpunt -> Een actief DigiD account op basis/midden niveau. Actie -> DigiD app activeren op Substantieel door het uitvoeren van de ID-check (indien ID-check negeren/niet mogelijk wordt een alternatief activatieproces gestart). Eindresultaat -> Geactiveerde app op niveau Substantieel."; public static final String ACTIVATE_WITH_APP = "DigiD app - Activeren app met andere DigiD app"; public static final String ACTIVATE_WITH_APP_DESCRIPTION = ""; public static final String RS_ACTIVATE_WITH_APP = "DigiD app - Activeren app bij aanvraagstation"; public static final String RS_ACTIVATE_WITH_APP_DESCRIPTION = ""; public static final String ACTIVATE_WEBSITE = "DigiD app - Activeren account en app na aanvraag via de website"; public static final String ACTIVATE_WEBSITE_DESCRIPTION = "Startpunt -> aangevraagd account met gn/ww en eventueel sms (via de website). Actie -> Activeren van je account via een nieuwe app. Eindresultaat -> Actief account met een nieuwe app"; public static final String ACTIVATE_APP_WITH_CODE = "DigiD app - Invoer activeringscode brief (aangevraag via app/aanvraagstation) in app met status: Wacht op activering"; public static final String ACTIVATE_APP_WITH_CODE_DESCRIPTION = "DigiD app - Invoer activeringscode brief (aangevraag via app/aanvraagstation) in app met status: Wacht op activering"; public static final String UPGRADE_LOGIN_LEVEL = "DigiD app - Verhogen inlogniveau naar substantieel"; public static final String UPGRADE_LOGIN_LEVEL_DESCRIPTION = "DigiD app - Verhogen inlogniveau naar substantieel"; public static final String RE_APPLY_ACTIVATIONCODE = "DigiD app - Heraanvraag brief met activeringscode voor DigiD account en app (via app of gemeentebalie)"; public static final String RE_APPLY_ACTIVATIONCODE_DESCRIPTION = "DigiD app - Heraanvraag brief met activeringscode voor DigiD account en app (via app of gemeentebalie)"; public static final String AUTH_WITH_WID = "DigiD app - Authenticeren met identiteitsdocument (DigiD Hoog)"; public static final String AUTH_WITH_WID_DESCRIPTION = "Startpunt -> Een actief DigiD account met geactiveerd hoog middel. Actie -> Inloggen met identiteitsdocument op niveau hoog Eindresultaat -> Ingelogd bij webdienst op niveau hoog"; public static final String HEADER = "header"; public static final String MANAGE_ACCOUNT_SESSION = "DigiD app - Accounthandelingen Mijn DigiD"; public static final String PINCODE_RESET_OF_APP = "DigiD app - Reset pincode of app"; public static final String WIDCHECKER_RAISE_TO_SUB = "DigiD Wid Checker - Verhogen naar substantieel"; public static final String APP_LOGIN = "DigiD app - Starten app (inloggen met pincode)"; public static final String APP_LOGIN_DESCRIPTION = "Bij het openen van de app wordt je gelijk gevraagd om te authenticeren met pincode, voor andere flows die hierna komen hoeft niet meer te worden geauthenticeerd alleen eventueel bevestigd."; public static final String CONFIRM_SESSION = "DigiD app - Bevestigen actie/login met geauthenticeerde sessie"; public static final String SHARED = "Shared endpoints"; public static final String SHARED_DESCRIPTION = "Bij het starten van de app haalt deze een aantal gegevens op via deze endpoints. Bijv of switches aan/of uit."; @Value("${urls.external.app}") private String appBaseUrl; @Bean public GroupedOpenApi publicOpenApi() { var paths = new String[]{"/iapi/**", "/apps/**"}; return GroupedOpenApi.builder().group("Public-api").pathsToMatch(paths).build(); } @Override public OpenAPI IapiOpenAPI(){ return new OpenAPI().addServersItem(new Server().url(appBaseUrl)) .components(new Components() .addParameters("API-V", apiVersionHeader()) .addParameters("OS-T", osTypeHeader()) .addParameters("APP-V", appVersionHeader()) .addParameters("OS-V", osVersionHeader()) .addParameters("REL-T", releaseTypeHeader()) .addParameters("X-Auth-Token", xAuthToken()) ).tags(getFlowTags()); } public List<Tag> getFlowTags(){ return List.of( createTag(REQUEST_ACCOUNT_AND_APP, REQUEST_ACCOUNT_AND_APP_DESCRIPTION), createTag(ACTIVATE_LETTER, ACTIVATE_LETTER_DESCRIPTION), createTag(ACTIVATE_SMS, ACTIVATE_SMS_DESCRIPTION), createTag(ACTIVATE_RDA, ACTIVATE_RDA_DESCRIPTION), createTag(ACTIVATE_WITH_APP, ACTIVATE_WITH_APP_DESCRIPTION), createTag(ACTIVATE_APP_WITH_CODE, ACTIVATE_APP_WITH_CODE_DESCRIPTION), createTag(AUTH_WITH_WID, AUTH_WITH_WID_DESCRIPTION), createTag(RE_APPLY_ACTIVATIONCODE, RE_APPLY_ACTIVATIONCODE_DESCRIPTION), createTag(RS_ACTIVATE_WITH_APP, RS_ACTIVATE_WITH_APP_DESCRIPTION), createTag(UPGRADE_LOGIN_LEVEL, UPGRADE_LOGIN_LEVEL_DESCRIPTION), createTag(APP_LOGIN, APP_LOGIN_DESCRIPTION), createTag(ACTIVATE_WEBSITE, ACTIVATE_WEBSITE_DESCRIPTION), createTag(SHARED, SHARED_DESCRIPTION) ); } private Tag createTag(String name, String description) { var tag = new Tag(); tag.setName(name); tag.setDescription(description); return tag; } protected static Parameter apiVersionHeader() { return new Parameter() .in(HEADER) .name("API-Version") .description("API-Version") .example("1") .required(true) .schema(new StringSchema()); } protected static Parameter osTypeHeader() { return new Parameter() .in(HEADER) .name("OS-Type") .description("OS-Type") .example("Android") .required(true) .schema(new StringSchema()); } protected static Parameter appVersionHeader() { return new Parameter() .in(HEADER) .name("App-version") .description("App-version") .example("1.0.0") .required(true) .schema(new StringSchema()); } protected static Parameter osVersionHeader() { return new Parameter() .in(HEADER) .name("OS-Version") .description("OS-Version") .example("10") .required(true) .schema(new StringSchema()); } protected static Parameter releaseTypeHeader() { return new Parameter() .in(HEADER) .name("Release-Type") .description("Release-Type") .example("Productie") .required(true) .schema(new StringSchema()); } protected static Parameter xAuthToken() { return new Parameter() .in("header") .name("X-Auth-Token") .description("X-Auth-Token") .example("development") .required(true) .schema(new StringSchema()); } }
212818_2
/** * Copyright (c) 2013-2024 Nikita Koksharov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.codec; import com.fasterxml.jackson.databind.cfg.SerializerFactoryConfig; import com.fasterxml.jackson.databind.ser.BasicSerializerFactory; import com.google.protobuf.MessageLite; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.runtime.RuntimeSchema; import org.redisson.client.codec.BaseCodec; import org.redisson.client.codec.Codec; import org.redisson.client.handler.State; import org.redisson.client.protocol.Decoder; import org.redisson.client.protocol.Encoder; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class ProtobufCodec extends BaseCodec { private final Class<?> mapKeyClass; private final Class<?> mapValueClass; private final Class<?> valueClass; //classes in blacklist will not be serialized using protobuf ,but instead will use blacklistCodec private final Set<String> protobufBlacklist; //default value is JsonJacksonCodec private final Codec blacklistCodec; public ProtobufCodec(Class<?> mapKeyClass, Class<?> mapValueClass) { this(mapKeyClass, mapValueClass, null, null); } /** * @param blacklistCodec classes in protobufBlacklist will use this codec */ public ProtobufCodec(Class<?> mapKeyClass, Class<?> mapValueClass, Codec blacklistCodec) { this(mapKeyClass, mapValueClass, null, blacklistCodec); } public ProtobufCodec(Class<?> valueClass) { this(null, null, valueClass, null); } /** * @param blacklistCodec classes in protobufBlacklist will use this codec */ public ProtobufCodec(Class<?> valueClass, Codec blacklistCodec) { this(null, null, valueClass, blacklistCodec); } private ProtobufCodec(Class<?> mapKeyClass, Class<?> mapValueClass, Class<?> valueClass, Codec blacklistCodec) { this.mapKeyClass = mapKeyClass; this.mapValueClass = mapValueClass; this.valueClass = valueClass; if (blacklistCodec == null) { this.blacklistCodec = new JsonJacksonCodec(); } else { if (blacklistCodec instanceof ProtobufCodec) { //will loop infinitely when encode or decode throw new IllegalArgumentException("BlacklistCodec can not be ProtobufCodec"); } this.blacklistCodec = blacklistCodec; } protobufBlacklist = new HashSet<>(); protobufBlacklist.addAll(BasicSerializerFactoryConcreteGetter.getConcreteKeySet()); protobufBlacklist.add(ArrayList.class.getName()); protobufBlacklist.add(HashSet.class.getName()); protobufBlacklist.add(HashMap.class.getName()); } public void addBlacklist(Class<?> clazz) { protobufBlacklist.add(clazz.getName()); } public void removeBlacklist(Class<?> clazz) { protobufBlacklist.remove(clazz.getName()); } @Override public Decoder<Object> getValueDecoder() { return createDecoder(valueClass, blacklistCodec.getValueDecoder()); } @Override public Encoder getValueEncoder() { return createEncoder(valueClass, blacklistCodec.getValueEncoder()); } @Override public Decoder<Object> getMapValueDecoder() { return createDecoder(mapValueClass, blacklistCodec.getMapValueDecoder()); } @Override public Encoder getMapValueEncoder() { return createEncoder(mapValueClass, blacklistCodec.getMapValueEncoder()); } @Override public Decoder<Object> getMapKeyDecoder() { return createDecoder(mapKeyClass, blacklistCodec.getMapKeyDecoder()); } @Override public Encoder getMapKeyEncoder() { return createEncoder(mapKeyClass, blacklistCodec.getMapKeyEncoder()); } private Decoder<Object> createDecoder(Class<?> clazz, Decoder<Object> blacklistDecoder) { if (clazz == null) { throw new IllegalArgumentException("class to create protobuf decoder can not be null"); } return new Decoder<Object>() { @Override public Object decode(ByteBuf buf, State state) throws IOException { //use blacklistDecoder if (protobufBlacklist.contains(clazz.getName())) { return blacklistDecoder.decode(buf, state); } byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); if (MessageLite.class.isAssignableFrom(clazz)) { //native deserialize try { return clazz.getDeclaredMethod("parseFrom", byte[].class).invoke(clazz, bytes); } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { throw new RuntimeException(e); } } else { //protostuff return ProtostuffUtils.deserialize(bytes, clazz); } } }; } private Encoder createEncoder(Class<?> clazz, Encoder blacklistEncoder) { if (clazz == null) { throw new IllegalArgumentException("class to create protobuf encoder can not be null"); } return new Encoder() { @Override public ByteBuf encode(Object in) throws IOException { //use blacklistEncoder if (protobufBlacklist.contains(clazz.getName())) { return blacklistEncoder.encode(in); } ByteBuf out = ByteBufAllocator.DEFAULT.buffer(); if (MessageLite.class.isAssignableFrom(clazz)) { //native serialize out.writeBytes(((MessageLite) in).toByteArray()); } else { //protostuff out.writeBytes(ProtostuffUtils.serialize(in)); } return out; } }; } private static final class ProtostuffUtils { @SuppressWarnings("unchecked") public static <T> byte[] serialize(T obj) { LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); try { return ProtostuffIOUtil.toByteArray(obj, RuntimeSchema.getSchema((Class<T>) obj.getClass()), buffer); } finally { buffer.clear(); } } public static <T> T deserialize(byte[] data, Class<T> clazz) { Schema<T> schema = RuntimeSchema.getSchema(clazz); T obj = schema.newMessage(); ProtostuffIOUtil.mergeFrom(data, obj, schema); return obj; } } private abstract static class BasicSerializerFactoryConcreteGetter extends BasicSerializerFactory { protected BasicSerializerFactoryConcreteGetter(SerializerFactoryConfig config) { super(config); } private static Set<String> getConcreteKeySet() { Set<String> concreteKeySet = new HashSet<>(); if (_concrete != null && !_concrete.isEmpty()) { concreteKeySet.addAll(_concrete.keySet()); } if (_concreteLazy != null && !_concreteLazy.isEmpty()) { concreteKeySet.addAll(_concreteLazy.keySet()); } return concreteKeySet; } } }
redisson/redisson
redisson/src/main/java/org/redisson/codec/ProtobufCodec.java
1,893
//default value is JsonJacksonCodec
line_comment
nl
/** * Copyright (c) 2013-2024 Nikita Koksharov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.codec; import com.fasterxml.jackson.databind.cfg.SerializerFactoryConfig; import com.fasterxml.jackson.databind.ser.BasicSerializerFactory; import com.google.protobuf.MessageLite; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.runtime.RuntimeSchema; import org.redisson.client.codec.BaseCodec; import org.redisson.client.codec.Codec; import org.redisson.client.handler.State; import org.redisson.client.protocol.Decoder; import org.redisson.client.protocol.Encoder; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class ProtobufCodec extends BaseCodec { private final Class<?> mapKeyClass; private final Class<?> mapValueClass; private final Class<?> valueClass; //classes in blacklist will not be serialized using protobuf ,but instead will use blacklistCodec private final Set<String> protobufBlacklist; //default value<SUF> private final Codec blacklistCodec; public ProtobufCodec(Class<?> mapKeyClass, Class<?> mapValueClass) { this(mapKeyClass, mapValueClass, null, null); } /** * @param blacklistCodec classes in protobufBlacklist will use this codec */ public ProtobufCodec(Class<?> mapKeyClass, Class<?> mapValueClass, Codec blacklistCodec) { this(mapKeyClass, mapValueClass, null, blacklistCodec); } public ProtobufCodec(Class<?> valueClass) { this(null, null, valueClass, null); } /** * @param blacklistCodec classes in protobufBlacklist will use this codec */ public ProtobufCodec(Class<?> valueClass, Codec blacklistCodec) { this(null, null, valueClass, blacklistCodec); } private ProtobufCodec(Class<?> mapKeyClass, Class<?> mapValueClass, Class<?> valueClass, Codec blacklistCodec) { this.mapKeyClass = mapKeyClass; this.mapValueClass = mapValueClass; this.valueClass = valueClass; if (blacklistCodec == null) { this.blacklistCodec = new JsonJacksonCodec(); } else { if (blacklistCodec instanceof ProtobufCodec) { //will loop infinitely when encode or decode throw new IllegalArgumentException("BlacklistCodec can not be ProtobufCodec"); } this.blacklistCodec = blacklistCodec; } protobufBlacklist = new HashSet<>(); protobufBlacklist.addAll(BasicSerializerFactoryConcreteGetter.getConcreteKeySet()); protobufBlacklist.add(ArrayList.class.getName()); protobufBlacklist.add(HashSet.class.getName()); protobufBlacklist.add(HashMap.class.getName()); } public void addBlacklist(Class<?> clazz) { protobufBlacklist.add(clazz.getName()); } public void removeBlacklist(Class<?> clazz) { protobufBlacklist.remove(clazz.getName()); } @Override public Decoder<Object> getValueDecoder() { return createDecoder(valueClass, blacklistCodec.getValueDecoder()); } @Override public Encoder getValueEncoder() { return createEncoder(valueClass, blacklistCodec.getValueEncoder()); } @Override public Decoder<Object> getMapValueDecoder() { return createDecoder(mapValueClass, blacklistCodec.getMapValueDecoder()); } @Override public Encoder getMapValueEncoder() { return createEncoder(mapValueClass, blacklistCodec.getMapValueEncoder()); } @Override public Decoder<Object> getMapKeyDecoder() { return createDecoder(mapKeyClass, blacklistCodec.getMapKeyDecoder()); } @Override public Encoder getMapKeyEncoder() { return createEncoder(mapKeyClass, blacklistCodec.getMapKeyEncoder()); } private Decoder<Object> createDecoder(Class<?> clazz, Decoder<Object> blacklistDecoder) { if (clazz == null) { throw new IllegalArgumentException("class to create protobuf decoder can not be null"); } return new Decoder<Object>() { @Override public Object decode(ByteBuf buf, State state) throws IOException { //use blacklistDecoder if (protobufBlacklist.contains(clazz.getName())) { return blacklistDecoder.decode(buf, state); } byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); if (MessageLite.class.isAssignableFrom(clazz)) { //native deserialize try { return clazz.getDeclaredMethod("parseFrom", byte[].class).invoke(clazz, bytes); } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { throw new RuntimeException(e); } } else { //protostuff return ProtostuffUtils.deserialize(bytes, clazz); } } }; } private Encoder createEncoder(Class<?> clazz, Encoder blacklistEncoder) { if (clazz == null) { throw new IllegalArgumentException("class to create protobuf encoder can not be null"); } return new Encoder() { @Override public ByteBuf encode(Object in) throws IOException { //use blacklistEncoder if (protobufBlacklist.contains(clazz.getName())) { return blacklistEncoder.encode(in); } ByteBuf out = ByteBufAllocator.DEFAULT.buffer(); if (MessageLite.class.isAssignableFrom(clazz)) { //native serialize out.writeBytes(((MessageLite) in).toByteArray()); } else { //protostuff out.writeBytes(ProtostuffUtils.serialize(in)); } return out; } }; } private static final class ProtostuffUtils { @SuppressWarnings("unchecked") public static <T> byte[] serialize(T obj) { LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); try { return ProtostuffIOUtil.toByteArray(obj, RuntimeSchema.getSchema((Class<T>) obj.getClass()), buffer); } finally { buffer.clear(); } } public static <T> T deserialize(byte[] data, Class<T> clazz) { Schema<T> schema = RuntimeSchema.getSchema(clazz); T obj = schema.newMessage(); ProtostuffIOUtil.mergeFrom(data, obj, schema); return obj; } } private abstract static class BasicSerializerFactoryConcreteGetter extends BasicSerializerFactory { protected BasicSerializerFactoryConcreteGetter(SerializerFactoryConfig config) { super(config); } private static Set<String> getConcreteKeySet() { Set<String> concreteKeySet = new HashSet<>(); if (_concrete != null && !_concrete.isEmpty()) { concreteKeySet.addAll(_concrete.keySet()); } if (_concreteLazy != null && !_concreteLazy.isEmpty()) { concreteKeySet.addAll(_concreteLazy.keySet()); } return concreteKeySet; } } }
212873_2
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.images.ui; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.ui.JBColor; import com.intellij.ui.scale.ScaleContext; import com.intellij.ui.scale.ScaleContextCache; import com.intellij.util.containers.ContainerUtil; import org.intellij.images.ImagesBundle; import org.intellij.images.editor.ImageDocument; import org.intellij.images.options.GridOptions; import org.intellij.images.options.TransparencyChessboardOptions; import org.intellij.images.options.impl.ImageEditorColorSchemeSettingsKt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import static com.intellij.ui.scale.ScaleType.OBJ_SCALE; /** * Image component is draw image box with effects. * * @author <a href="mailto:[email protected]">Alexey Efimov</a> */ public class ImageComponent extends JComponent { public static final int IMAGE_INSETS = 2; @NonNls public static final String TRANSPARENCY_CHESSBOARD_CELL_SIZE_PROP = "TransparencyChessboard.cellSize"; @NonNls public static final String TRANSPARENCY_CHESSBOARD_WHITE_COLOR_PROP = "TransparencyChessboard.whiteColor"; @NonNls public static final String TRANSPARENCY_CHESSBOARD_BLACK_COLOR_PROP = "TransparencyChessboard.blackColor"; @NonNls private static final String TRANSPARENCY_CHESSBOARD_VISIBLE_PROP = "TransparencyChessboard.visible"; @NonNls private static final String GRID_LINE_ZOOM_FACTOR_PROP = "Grid.lineZoomFactor"; @NonNls private static final String GRID_LINE_SPAN_PROP = "Grid.lineSpan"; @NonNls private static final String GRID_LINE_COLOR_PROP = "Grid.lineColor"; @NonNls private static final String GRID_VISIBLE_PROP = "Grid.visible"; @NonNls private static final String FILE_SIZE_VISIBLE_PROP = "FileSize.visible"; @NonNls private static final String FILE_NAME_VISIBLE_PROP = "FileName.visible"; /** * @see #getUIClassID * @see #readObject */ @NonNls private static final String uiClassID = "ImageComponentUI"; private final ImageDocument document = new ImageDocumentImpl(this); private final Grid grid = new Grid(); private final Chessboard chessboard = new Chessboard(); private boolean myFileSizeVisible = true; private boolean myFileNameVisible = true; private double zoomFactor = 1d; private boolean myBorderVisible = true; public ImageComponent() { updateUI(); } public ImageDocument getDocument() { return document; } public double getZoomFactor() { return zoomFactor; } public void setZoomFactor(double zoomFactor) { this.zoomFactor = zoomFactor; } public void setTransparencyChessboardCellSize(int cellSize) { int oldValue = chessboard.getCellSize(); if (oldValue != cellSize) { chessboard.setCellSize(cellSize); firePropertyChange(TRANSPARENCY_CHESSBOARD_CELL_SIZE_PROP, oldValue, cellSize); } } public void setTransparencyChessboardWhiteColor(Color color) { Color oldValue = chessboard.getWhiteColor(); if (oldValue != null && !oldValue.equals(color) || oldValue == null && color != null) { chessboard.setWhiteColor(color); firePropertyChange(TRANSPARENCY_CHESSBOARD_WHITE_COLOR_PROP, oldValue, color); } } public void setTransparencyChessboardBlankColor(Color color) { Color oldValue = chessboard.getBlackColor(); if (oldValue != null && !oldValue.equals(color) || oldValue == null && color != null) { chessboard.setBlackColor(color); firePropertyChange(TRANSPARENCY_CHESSBOARD_BLACK_COLOR_PROP, oldValue, color); } } public void setTransparencyChessboardVisible(boolean visible) { boolean oldValue = chessboard.isVisible(); if (oldValue != visible) { chessboard.setVisible(visible); firePropertyChange(TRANSPARENCY_CHESSBOARD_VISIBLE_PROP, oldValue, visible); } } public int getTransparencyChessboardCellSize() { return chessboard.getCellSize(); } public Color getTransparencyChessboardWhiteColor() { return chessboard.getWhiteColor(); } public Color getTransparencyChessboardBlackColor() { return chessboard.getBlackColor(); } public boolean isTransparencyChessboardVisible() { return chessboard.isVisible(); } public boolean isFileSizeVisible() { return myFileSizeVisible; } public void setFileSizeVisible(boolean fileSizeVisible) { boolean oldValue = myFileSizeVisible; myFileSizeVisible = fileSizeVisible; firePropertyChange(FILE_SIZE_VISIBLE_PROP, oldValue, fileSizeVisible); } public boolean isFileNameVisible() { return myFileNameVisible; } public void setFileNameVisible(boolean fileNameVisible) { boolean oldValue = myFileNameVisible; myFileNameVisible = fileNameVisible; firePropertyChange(FILE_NAME_VISIBLE_PROP, oldValue, fileNameVisible); } public boolean isBorderVisible() { return myBorderVisible; } public void setBorderVisible(boolean borderVisible) { boolean oldValue = myBorderVisible; myBorderVisible = borderVisible; firePropertyChange("Border.visible", oldValue, myBorderVisible); } public void setGridLineZoomFactor(int lineZoomFactor) { int oldValue = grid.getLineZoomFactor(); if (oldValue != lineZoomFactor) { grid.setLineZoomFactor(lineZoomFactor); firePropertyChange(GRID_LINE_ZOOM_FACTOR_PROP, oldValue, lineZoomFactor); } } public void setGridLineSpan(int lineSpan) { int oldValue = grid.getLineSpan(); if (oldValue != lineSpan) { grid.setLineSpan(lineSpan); firePropertyChange(GRID_LINE_SPAN_PROP, oldValue, lineSpan); } } public void setGridLineColor(Color color) { Color oldValue = grid.getLineColor(); if (oldValue != null && !oldValue.equals(color) || oldValue == null && color != null) { grid.setLineColor(color); firePropertyChange(GRID_LINE_COLOR_PROP, oldValue, color); } } public void setGridVisible(boolean visible) { boolean oldValue = grid.isVisible(); if (oldValue != visible) { grid.setVisible(visible); firePropertyChange(GRID_VISIBLE_PROP, oldValue, visible); } } public int getGridLineZoomFactor() { return grid.getLineZoomFactor(); } public int getGridLineSpan() { return grid.getLineSpan(); } public Color getGridLineColor() { return grid.getLineColor(); } public boolean isGridVisible() { return grid.isVisible(); } @Nullable public String getDescription() { BufferedImage image = getDocument().getValue(); if (image != null) { return ImagesBundle.message("icon.dimensions", image.getWidth(), image.getHeight(), image.getColorModel().getPixelSize()); } return null; } public void setCanvasSize(int width, int height) { setSize(width + IMAGE_INSETS * 2, height + IMAGE_INSETS * 2); } public void setCanvasSize(Dimension dimension) { setCanvasSize(dimension.width, dimension.height); } public Dimension getCanvasSize() { Dimension size = getSize(); return new Dimension(size.width - IMAGE_INSETS * 2, size.height - IMAGE_INSETS * 2); } @Override public String getUIClassID() { return uiClassID; } @Override public void updateUI() { boolean customUI = UIManager.getDefaults().get(uiClassID) != null; setUI(customUI ? UIManager.getUI(this) : new ImageComponentUI(this)); } private static class ImageDocumentImpl implements ImageDocument { private final List<ChangeListener> listeners = ContainerUtil.createLockFreeCopyOnWriteList(); private CachedScaledImageProvider imageProvider; private String format; private Image renderer; private final Component myComponent; private final ScaleContextCache<Rectangle> cachedBounds = new ScaleContextCache<>((ctx) -> { BufferedImage image = getValue(ctx.getScale(OBJ_SCALE)); return image != null ? new Rectangle(image.getWidth(), image.getHeight()) : null; }); ImageDocumentImpl(Component component) { myComponent = component; myComponent.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals("ancestor") && e.getNewValue() == null && imageProvider != null) { imageProvider.clearCache(); } } }); } @Override public Image getRenderer() { return renderer; } @Override public Image getRenderer(double scale) { return getValue(scale); } @Nullable @Override public Rectangle getBounds(double scale) { ScaleContext ctx = ScaleContext.create(myComponent); ctx.setScale(OBJ_SCALE.of(scale)); return cachedBounds.getOrProvide(ctx); } @Override public BufferedImage getValue() { return getValue(1d); } @Override public BufferedImage getValue(double scale) { return imageProvider != null ? imageProvider.apply(scale, myComponent) : null; } @Override public void setValue(BufferedImage image) { this.renderer = image != null ? Toolkit.getDefaultToolkit().createImage(image.getSource()) : null; setValue(image != null ? (scale, anchor) -> image : null); } @Override public void setValue(ScaledImageProvider imageProvider) { this.imageProvider = imageProvider instanceof CachedScaledImageProvider ? (CachedScaledImageProvider)imageProvider : imageProvider != null ? (zoom, ancestor) -> imageProvider.apply(zoom, ancestor) : null; cachedBounds.clear(); fireChangeEvent(new ChangeEvent(this)); } @Override public String getFormat() { return format; } @Override public void setFormat(String format) { this.format = format; fireChangeEvent(new ChangeEvent(this)); } private void fireChangeEvent(ChangeEvent e) { for (ChangeListener listener : listeners) { listener.stateChanged(e); } } @Override public void addChangeListener(ChangeListener listener) { listeners.add(listener); } @Override public void removeChangeListener(ChangeListener listener) { listeners.remove(listener); } } private static final class Chessboard { private int cellSize = TransparencyChessboardOptions.DEFAULT_CELL_SIZE; private Color whiteColor = TransparencyChessboardOptions.DEFAULT_WHITE_COLOR; private Color blackColor = TransparencyChessboardOptions.DEFAULT_BLACK_COLOR; private boolean visible = false; public int getCellSize() { return cellSize; } public void setCellSize(int cellSize) { this.cellSize = cellSize; } public Color getWhiteColor() { return whiteColor; } public void setWhiteColor(Color whiteColor) { this.whiteColor = whiteColor; } public Color getBlackColor() { return blackColor; } public void setBlackColor(Color blackColor) { this.blackColor = blackColor; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } } private static final class Grid { private int lineZoomFactor = GridOptions.DEFAULT_LINE_ZOOM_FACTOR; private int lineSpan = GridOptions.DEFAULT_LINE_SPAN; private Color lineColor = GridOptions.DEFAULT_LINE_COLOR; private boolean visible = false; public int getLineZoomFactor() { return lineZoomFactor; } public void setLineZoomFactor(int lineZoomFactor) { this.lineZoomFactor = lineZoomFactor; } public int getLineSpan() { return lineSpan; } public void setLineSpan(int lineSpan) { this.lineSpan = lineSpan; } public Color getLineColor() { EditorColorsScheme editorScheme = EditorColorsManager.getInstance().getGlobalScheme(); Color color = editorScheme.getColor(ImageEditorColorSchemeSettingsKt.getGRID_LINE_COLOR_KEY()); return color != null ? color : JBColor.DARK_GRAY; } public void setLineColor(Color lineColor) { this.lineColor = lineColor; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } } }
foresterre/fork.intellij-community
images/src/org/intellij/images/ui/ImageComponent.java
3,392
/** * @see #getUIClassID * @see #readObject */
block_comment
nl
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.images.ui; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.ui.JBColor; import com.intellij.ui.scale.ScaleContext; import com.intellij.ui.scale.ScaleContextCache; import com.intellij.util.containers.ContainerUtil; import org.intellij.images.ImagesBundle; import org.intellij.images.editor.ImageDocument; import org.intellij.images.options.GridOptions; import org.intellij.images.options.TransparencyChessboardOptions; import org.intellij.images.options.impl.ImageEditorColorSchemeSettingsKt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import static com.intellij.ui.scale.ScaleType.OBJ_SCALE; /** * Image component is draw image box with effects. * * @author <a href="mailto:[email protected]">Alexey Efimov</a> */ public class ImageComponent extends JComponent { public static final int IMAGE_INSETS = 2; @NonNls public static final String TRANSPARENCY_CHESSBOARD_CELL_SIZE_PROP = "TransparencyChessboard.cellSize"; @NonNls public static final String TRANSPARENCY_CHESSBOARD_WHITE_COLOR_PROP = "TransparencyChessboard.whiteColor"; @NonNls public static final String TRANSPARENCY_CHESSBOARD_BLACK_COLOR_PROP = "TransparencyChessboard.blackColor"; @NonNls private static final String TRANSPARENCY_CHESSBOARD_VISIBLE_PROP = "TransparencyChessboard.visible"; @NonNls private static final String GRID_LINE_ZOOM_FACTOR_PROP = "Grid.lineZoomFactor"; @NonNls private static final String GRID_LINE_SPAN_PROP = "Grid.lineSpan"; @NonNls private static final String GRID_LINE_COLOR_PROP = "Grid.lineColor"; @NonNls private static final String GRID_VISIBLE_PROP = "Grid.visible"; @NonNls private static final String FILE_SIZE_VISIBLE_PROP = "FileSize.visible"; @NonNls private static final String FILE_NAME_VISIBLE_PROP = "FileName.visible"; /** * @see #getUIClassID <SUF>*/ @NonNls private static final String uiClassID = "ImageComponentUI"; private final ImageDocument document = new ImageDocumentImpl(this); private final Grid grid = new Grid(); private final Chessboard chessboard = new Chessboard(); private boolean myFileSizeVisible = true; private boolean myFileNameVisible = true; private double zoomFactor = 1d; private boolean myBorderVisible = true; public ImageComponent() { updateUI(); } public ImageDocument getDocument() { return document; } public double getZoomFactor() { return zoomFactor; } public void setZoomFactor(double zoomFactor) { this.zoomFactor = zoomFactor; } public void setTransparencyChessboardCellSize(int cellSize) { int oldValue = chessboard.getCellSize(); if (oldValue != cellSize) { chessboard.setCellSize(cellSize); firePropertyChange(TRANSPARENCY_CHESSBOARD_CELL_SIZE_PROP, oldValue, cellSize); } } public void setTransparencyChessboardWhiteColor(Color color) { Color oldValue = chessboard.getWhiteColor(); if (oldValue != null && !oldValue.equals(color) || oldValue == null && color != null) { chessboard.setWhiteColor(color); firePropertyChange(TRANSPARENCY_CHESSBOARD_WHITE_COLOR_PROP, oldValue, color); } } public void setTransparencyChessboardBlankColor(Color color) { Color oldValue = chessboard.getBlackColor(); if (oldValue != null && !oldValue.equals(color) || oldValue == null && color != null) { chessboard.setBlackColor(color); firePropertyChange(TRANSPARENCY_CHESSBOARD_BLACK_COLOR_PROP, oldValue, color); } } public void setTransparencyChessboardVisible(boolean visible) { boolean oldValue = chessboard.isVisible(); if (oldValue != visible) { chessboard.setVisible(visible); firePropertyChange(TRANSPARENCY_CHESSBOARD_VISIBLE_PROP, oldValue, visible); } } public int getTransparencyChessboardCellSize() { return chessboard.getCellSize(); } public Color getTransparencyChessboardWhiteColor() { return chessboard.getWhiteColor(); } public Color getTransparencyChessboardBlackColor() { return chessboard.getBlackColor(); } public boolean isTransparencyChessboardVisible() { return chessboard.isVisible(); } public boolean isFileSizeVisible() { return myFileSizeVisible; } public void setFileSizeVisible(boolean fileSizeVisible) { boolean oldValue = myFileSizeVisible; myFileSizeVisible = fileSizeVisible; firePropertyChange(FILE_SIZE_VISIBLE_PROP, oldValue, fileSizeVisible); } public boolean isFileNameVisible() { return myFileNameVisible; } public void setFileNameVisible(boolean fileNameVisible) { boolean oldValue = myFileNameVisible; myFileNameVisible = fileNameVisible; firePropertyChange(FILE_NAME_VISIBLE_PROP, oldValue, fileNameVisible); } public boolean isBorderVisible() { return myBorderVisible; } public void setBorderVisible(boolean borderVisible) { boolean oldValue = myBorderVisible; myBorderVisible = borderVisible; firePropertyChange("Border.visible", oldValue, myBorderVisible); } public void setGridLineZoomFactor(int lineZoomFactor) { int oldValue = grid.getLineZoomFactor(); if (oldValue != lineZoomFactor) { grid.setLineZoomFactor(lineZoomFactor); firePropertyChange(GRID_LINE_ZOOM_FACTOR_PROP, oldValue, lineZoomFactor); } } public void setGridLineSpan(int lineSpan) { int oldValue = grid.getLineSpan(); if (oldValue != lineSpan) { grid.setLineSpan(lineSpan); firePropertyChange(GRID_LINE_SPAN_PROP, oldValue, lineSpan); } } public void setGridLineColor(Color color) { Color oldValue = grid.getLineColor(); if (oldValue != null && !oldValue.equals(color) || oldValue == null && color != null) { grid.setLineColor(color); firePropertyChange(GRID_LINE_COLOR_PROP, oldValue, color); } } public void setGridVisible(boolean visible) { boolean oldValue = grid.isVisible(); if (oldValue != visible) { grid.setVisible(visible); firePropertyChange(GRID_VISIBLE_PROP, oldValue, visible); } } public int getGridLineZoomFactor() { return grid.getLineZoomFactor(); } public int getGridLineSpan() { return grid.getLineSpan(); } public Color getGridLineColor() { return grid.getLineColor(); } public boolean isGridVisible() { return grid.isVisible(); } @Nullable public String getDescription() { BufferedImage image = getDocument().getValue(); if (image != null) { return ImagesBundle.message("icon.dimensions", image.getWidth(), image.getHeight(), image.getColorModel().getPixelSize()); } return null; } public void setCanvasSize(int width, int height) { setSize(width + IMAGE_INSETS * 2, height + IMAGE_INSETS * 2); } public void setCanvasSize(Dimension dimension) { setCanvasSize(dimension.width, dimension.height); } public Dimension getCanvasSize() { Dimension size = getSize(); return new Dimension(size.width - IMAGE_INSETS * 2, size.height - IMAGE_INSETS * 2); } @Override public String getUIClassID() { return uiClassID; } @Override public void updateUI() { boolean customUI = UIManager.getDefaults().get(uiClassID) != null; setUI(customUI ? UIManager.getUI(this) : new ImageComponentUI(this)); } private static class ImageDocumentImpl implements ImageDocument { private final List<ChangeListener> listeners = ContainerUtil.createLockFreeCopyOnWriteList(); private CachedScaledImageProvider imageProvider; private String format; private Image renderer; private final Component myComponent; private final ScaleContextCache<Rectangle> cachedBounds = new ScaleContextCache<>((ctx) -> { BufferedImage image = getValue(ctx.getScale(OBJ_SCALE)); return image != null ? new Rectangle(image.getWidth(), image.getHeight()) : null; }); ImageDocumentImpl(Component component) { myComponent = component; myComponent.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals("ancestor") && e.getNewValue() == null && imageProvider != null) { imageProvider.clearCache(); } } }); } @Override public Image getRenderer() { return renderer; } @Override public Image getRenderer(double scale) { return getValue(scale); } @Nullable @Override public Rectangle getBounds(double scale) { ScaleContext ctx = ScaleContext.create(myComponent); ctx.setScale(OBJ_SCALE.of(scale)); return cachedBounds.getOrProvide(ctx); } @Override public BufferedImage getValue() { return getValue(1d); } @Override public BufferedImage getValue(double scale) { return imageProvider != null ? imageProvider.apply(scale, myComponent) : null; } @Override public void setValue(BufferedImage image) { this.renderer = image != null ? Toolkit.getDefaultToolkit().createImage(image.getSource()) : null; setValue(image != null ? (scale, anchor) -> image : null); } @Override public void setValue(ScaledImageProvider imageProvider) { this.imageProvider = imageProvider instanceof CachedScaledImageProvider ? (CachedScaledImageProvider)imageProvider : imageProvider != null ? (zoom, ancestor) -> imageProvider.apply(zoom, ancestor) : null; cachedBounds.clear(); fireChangeEvent(new ChangeEvent(this)); } @Override public String getFormat() { return format; } @Override public void setFormat(String format) { this.format = format; fireChangeEvent(new ChangeEvent(this)); } private void fireChangeEvent(ChangeEvent e) { for (ChangeListener listener : listeners) { listener.stateChanged(e); } } @Override public void addChangeListener(ChangeListener listener) { listeners.add(listener); } @Override public void removeChangeListener(ChangeListener listener) { listeners.remove(listener); } } private static final class Chessboard { private int cellSize = TransparencyChessboardOptions.DEFAULT_CELL_SIZE; private Color whiteColor = TransparencyChessboardOptions.DEFAULT_WHITE_COLOR; private Color blackColor = TransparencyChessboardOptions.DEFAULT_BLACK_COLOR; private boolean visible = false; public int getCellSize() { return cellSize; } public void setCellSize(int cellSize) { this.cellSize = cellSize; } public Color getWhiteColor() { return whiteColor; } public void setWhiteColor(Color whiteColor) { this.whiteColor = whiteColor; } public Color getBlackColor() { return blackColor; } public void setBlackColor(Color blackColor) { this.blackColor = blackColor; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } } private static final class Grid { private int lineZoomFactor = GridOptions.DEFAULT_LINE_ZOOM_FACTOR; private int lineSpan = GridOptions.DEFAULT_LINE_SPAN; private Color lineColor = GridOptions.DEFAULT_LINE_COLOR; private boolean visible = false; public int getLineZoomFactor() { return lineZoomFactor; } public void setLineZoomFactor(int lineZoomFactor) { this.lineZoomFactor = lineZoomFactor; } public int getLineSpan() { return lineSpan; } public void setLineSpan(int lineSpan) { this.lineSpan = lineSpan; } public Color getLineColor() { EditorColorsScheme editorScheme = EditorColorsManager.getInstance().getGlobalScheme(); Color color = editorScheme.getColor(ImageEditorColorSchemeSettingsKt.getGRID_LINE_COLOR_KEY()); return color != null ? color : JBColor.DARK_GRAY; } public void setLineColor(Color lineColor) { this.lineColor = lineColor; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } } }
212918_68
package edu.stanford.nlp.pipeline; import edu.stanford.nlp.io.FileSequentialCollection; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.io.RuntimeIOException; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.util.PropertiesUtils; import edu.stanford.nlp.util.StringUtils; import edu.stanford.nlp.util.logging.Redwood; import edu.stanford.nlp.util.logging.StanfordRedwoodConfiguration; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static edu.stanford.nlp.util.logging.Redwood.Util.*; /** * An annotation pipeline in spirit identical to {@link StanfordCoreNLP}, but * with the backend supported by a web server. * * @author Gabor Angeli */ @SuppressWarnings("FieldCanBeLocal") public class StanfordCoreNLPClient extends AnnotationPipeline { /** A logger for this class */ private static final Redwood.RedwoodChannels log = Redwood.channels(StanfordCoreNLPClient.class); /** A simple URL spec, for parsing backend URLs */ private static final Pattern URL_PATTERN = Pattern.compile("(?:(https?)://)?([^:]+)(?::([0-9]+))?"); /** * Information on how to connect to a backend. * The semantics of one of these objects is as follows: * * <ul> * <li>It should define a hostname and port to connect to.</li> * <li>This represents ONE thread on the remote server. The client should * treat it as such.</li> * <li>Two backends that are .equals() point to the same endpoint, but there can be * multiple of them if we want to run multiple threads on that endpoint.</li> * </ul> */ private static class Backend { /** The protocol to connect to the server with. */ public final String protocol; /** The hostname of the server running the CoreNLP annotators */ public final String host; /** The port of the server running the CoreNLP annotators */ public final int port; public Backend(String protocol, String host, int port) { this.protocol = protocol; this.host = host; this.port = port; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Backend)) return false; Backend backend = (Backend) o; return port == backend.port && protocol.equals(backend.protocol) && host.equals(backend.host); } @Override public int hashCode() { throw new IllegalStateException("Hashing backends is dangerous!"); } @Override public String toString() { return protocol + "://" + host + ':' + port; } } // end static class Backend /** * A special type of {@link Thread}, which is responsible for scheduling jobs * on the backend. */ private static class BackendScheduler extends Thread { /** * The list of backends that we can schedule on. * This should not generally be called directly from anywhere */ public final List<Backend> backends; /** * The queue on requests for the scheduler to handle. * Each element of this queue is a function: calling the function signals * that this backend is available to perform a task on the passed backend. * It is then obligated to call the passed Consumer to signal that it has * released control of the backend, and it can be used for other things. * Remember to lock access to this object with {@link BackendScheduler#stateLock}. */ private final Queue<BiConsumer<Backend, Consumer<Backend>>> queue; /** * The lock on access to {@link BackendScheduler#queue}. */ private final Lock stateLock = new ReentrantLock(); /** * Represents the event that an item has been added to the work queue. * Linked to {@link BackendScheduler#stateLock}. */ private final Condition enqueued = stateLock.newCondition(); /** * Represents the event that the queue has become empty, and this schedule is no * longer needed. */ public final Condition shouldShutdown = stateLock.newCondition(); /** * The queue of annotators (backends) that are free to be run on. * Remember to lock access to this object with {@link BackendScheduler#stateLock}. */ private final Queue<Backend> freeAnnotators; /** * Represents the event that an annotator has freed up and is available for * work on the {@link BackendScheduler#freeAnnotators} queue. * Linked to {@link BackendScheduler#stateLock}. */ private final Condition newlyFree = stateLock.newCondition(); /** * While this is true, continue running the scheduler. */ private boolean doRun = true; /** * Create a new scheduler from a list of backends. * These can contain duplicates -- in that case, that many concurrent * calls can be made to that backend. */ public BackendScheduler(List<Backend> backends) { super(); setDaemon(true); this.backends = backends; this.freeAnnotators = new LinkedList<>(backends); this.queue = new LinkedList<>(); } /** {@inheritDoc} */ @Override public void run() { try { while (doRun) { // Wait for a request BiConsumer<Backend, Consumer<Backend>> request; Backend annotator; stateLock.lock(); try { while (queue.isEmpty()) { enqueued.await(); if (!doRun) { return; } } // Get the actual request request = queue.poll(); // We have a request // Find a free annotator while (freeAnnotators.isEmpty()) { newlyFree.await(); } annotator = freeAnnotators.poll(); } finally { stateLock.unlock(); } // We have an annotator // Run the annotation request.accept(annotator, freedAnnotator -> { // ASYNC: we've freed this annotator // add it back to the queue and register it as available stateLock.lock(); try { freeAnnotators.add(freedAnnotator); // If the queue is empty, and all the annotators have returned, we're done if (queue.isEmpty() && freeAnnotators.size() == backends.size()) { log.debug("All annotations completed. Signaling for shutdown"); shouldShutdown.signalAll(); } newlyFree.signal(); } finally { stateLock.unlock(); } }); // Annotator is running (in parallel, most likely) } } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * Schedule a new job on the backend * @param annotate A callback, which will be called when a backend is free * to do some processing. The implementation of this callback * MUST CALL the second argument when it is done processing, * to register the backend as free for further work. */ public void schedule(BiConsumer<Backend, Consumer<Backend>> annotate) { stateLock.lock(); try { queue.add(annotate); enqueued.signal(); } finally { stateLock.unlock(); } } } // end static class BackEndScheduler /** The path on the server to connect to. */ private final String path = ""; /** The Properties file to annotate with. */ private final Properties properties; /** The Properties file to send to the server, serialized as JSON. */ private final String propsAsJSON; /** The API key to authenticate with, or null */ private final String apiKey; /** The API secret to authenticate with, or null */ private final String apiSecret; /** The scheduler to use when running on multiple backends at a time */ private final BackendScheduler scheduler; /** * The annotation serializer responsible for translating between the wire format * (protocol buffers) and the {@link Annotation} classes. */ private final ProtobufAnnotationSerializer serializer = new ProtobufAnnotationSerializer(true); private boolean fallbackToLocalPipeline; private int timeoutMilliseconds=0; /** * The main constructor. Create a client from a properties file and a list of backends. * Note that this creates at least one Daemon thread. * * @param properties The properties file, as would be passed to {@link StanfordCoreNLP}. * @param backends The backends to run on. * @param apiKey The key to authenticate with as a username * @param apiSecret The key to authenticate with as a password */ private StanfordCoreNLPClient(Properties properties, List<Backend> backends, String apiKey, String apiSecret) { // Save the constructor variables this.properties = properties; Properties serverProperties = new Properties(); for (String key : properties.stringPropertyNames()) { serverProperties.setProperty(key, properties.getProperty(key)); } Collections.shuffle(backends, new Random(System.currentTimeMillis())); this.scheduler = new BackendScheduler(backends); this.apiKey = apiKey; this.apiSecret = apiSecret; // Set required serverProperties serverProperties.setProperty("inputFormat", "serialized"); serverProperties.setProperty("outputFormat", "serialized"); serverProperties.setProperty("inputSerializer", ProtobufAnnotationSerializer.class.getName()); serverProperties.setProperty("outputSerializer", ProtobufAnnotationSerializer.class.getName()); this.propsAsJSON = PropertiesUtils.propsAsJsonString(serverProperties); // Start 'er up this.scheduler.start(); } /** * The main constructor without credentials. * * @see StanfordCoreNLPClient#StanfordCoreNLPClient(Properties, List, String, String) */ private StanfordCoreNLPClient(Properties properties, List<Backend> backends) { this(properties, backends, null, null); } /** * Run the client, pulling credentials from the environment. * Throws an IllegalStateException if the required environment variables aren't set. * These are: * * <ul> * <li>CORENLP_HOST</li> * <li>CORENLP_KEY</li> * <li>CORENLP_SECRET</li> * </ul> * * @throws IllegalStateException Thrown if we could not read the required environment variables. */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties) throws IllegalStateException { this(properties, Optional.ofNullable(System.getenv("CORENLP_HOST")).orElseThrow(() -> new IllegalStateException("Environment variable CORENLP_HOST not specified")), Optional.ofNullable(System.getenv("CORENLP_HOST")).map(x -> x.startsWith("http://") ? 80 : 443).orElse(443), 1, Optional.ofNullable(System.getenv("CORENLP_KEY")).orElse(null), Optional.ofNullable(System.getenv("CORENLP_SECRET")).orElse(null) ); } /** * Run on a single backend. * * @see StanfordCoreNLPClient (Properties, List) */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties, String host, int port) { this(properties, host, port, 1); } /** * Run on a single backend, with authentication * * @see StanfordCoreNLPClient (Properties, List) */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties, String host, int port, String apiKey, String apiSecret) { this(properties, host, port, 1, apiKey, apiSecret); } /** * Run on a single backend, with authentication * * @see StanfordCoreNLPClient (Properties, List) */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties, String host, String apiKey, String apiSecret) { this(properties, host, host.startsWith("http://") ? 80 : 443, 1, apiKey, apiSecret); } /** * Run on a single backend, but with k threads on each backend. * * @see StanfordCoreNLPClient (Properties, List) */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties, String host, int port, int threads) { this(properties, host, port, threads, null, null); } /** * Run on a single backend, but with k threads on each backend, and with authentication * * @see StanfordCoreNLPClient (Properties, List) */ public StanfordCoreNLPClient(Properties properties, String host, int port, int threads, String apiKey, String apiSecret) { this(properties, getBackends(host, port, threads), apiKey, apiSecret); } private static List<Backend> getBackends(String host, int port, int threads) { List<Backend> backends = new ArrayList<>(); for (int i = 0; i < threads; i++) { backends.add(new Backend(host.startsWith("http://") ? "http" : "https", host.startsWith("http://") ? host.substring("http://".length()) : (host.startsWith("https://") ? host.substring("https://".length()) : host), port)); } return backends; } public void setTimeoutMilliseconds(int timeout) { this.timeoutMilliseconds = timeout; } /** * {@inheritDoc} * * This method creates an async call to the server, and blocks until the server * has finished annotating the object. */ @Override public void annotate(Annotation annotation) { final Lock lock = new ReentrantLock(); final Condition annotationDone = lock.newCondition(); annotate(Collections.singleton(annotation), 1, (Annotation annInput) -> { try { lock.lock(); annotationDone.signal(); } finally { lock.unlock(); } }); try { lock.lock(); annotationDone.await(); // Only wait for one callback to complete; only annotating one document } catch (InterruptedException e) { log.info("Interrupt while waiting for annotation to return"); } finally { lock.unlock(); } } /** * This method fires off a request to the server. Upon returning, it calls the provided * callback method. * * @param annotations The input annotations to process * @param numThreads The number of threads to run on. IGNORED in this class. * @param callback A function to be called when an annotation finishes. */ @Override public void annotate(final Iterable<Annotation> annotations, int numThreads, final Consumer<Annotation> callback){ for (Annotation annotation : annotations) { annotate(annotation, callback); } } /** * The canonical entry point of the client annotator. * Create an HTTP request, send this annotation to the server, and await a response. * * @param annotation The annotation to annotate. * @param callback Called when the server has returned an annotated document. * The input to this callback is the same as the passed Annotation object. */ public void annotate(final Annotation annotation, final Consumer<Annotation> callback) { scheduler.schedule((Backend backend, Consumer<Backend> isFinishedCallback) -> new Thread(() -> { try { // 1. Create the input // 1.1 Create a protocol buffer ByteArrayOutputStream os = new ByteArrayOutputStream(); serializer.write(annotation, os); os.close(); byte[] message = os.toByteArray(); // 1.2 Create the query params String queryParams = String.format("properties=%s", URLEncoder.encode(StanfordCoreNLPClient.this.propsAsJSON, "utf-8")); // 2. Create a connection URL serverURL = new URL(backend.protocol, backend.host, backend.port, StanfordCoreNLPClient.this.path + '?' + queryParams); // 3. Do the annotation // This method has two contracts: // 1. It should call the two relevant callbacks // 2. It must not throw an exception doAnnotation(annotation, backend, serverURL, message); } catch (Throwable t) { log.err("Could not annotate via server!", t); if (fallbackToLocalPipeline) { log.info("Trying to annotate locally..."); StanfordCoreNLP corenlp = new StanfordCoreNLP(properties); corenlp.annotate(annotation); } else { annotation.set(CoreAnnotations.ExceptionAnnotation.class, t); } } finally { callback.accept(annotation); isFinishedCallback.accept(backend); } }).start()); } static final int MAX_TRIES=3; /** * Actually try to perform the annotation on the server side. * Tries up to 3 times if the first couple don't succeed. * * @param annotation The annotation we need to fill. * @param backend The backend we are querying against. * @param serverURL The URL of the server we are hitting. * @param message The message we are sending the server (don't need to recompute each retry). * @param tries The number of times we've tried already. */ @SuppressWarnings("unchecked") private void doAnnotation(Annotation annotation, Backend backend, URL serverURL, byte[] message) { for (int tries = 0; tries < MAX_TRIES; ++tries) { try { // 1. Set up the connection URLConnection connection = serverURL.openConnection(); // 1.1 Set authentication if (apiKey != null && apiSecret != null) { String userpass = apiKey + ':' + apiSecret; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); } // 1.2 Set some protocol-independent properties connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-protobuf"); connection.setRequestProperty("Content-Length", Integer.toString(message.length)); connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestProperty("User-Agent", StanfordCoreNLPClient.class.getName()); if (timeoutMilliseconds > 0) { connection.setConnectTimeout(timeoutMilliseconds); connection.setReadTimeout(timeoutMilliseconds); } // 1.3 Set some protocol-dependent properties switch (backend.protocol) { case "https": case "http": ((HttpURLConnection) connection).setRequestMethod("POST"); break; default: throw new IllegalStateException("Haven't implemented protocol: " + backend.protocol); } // 2. Annotate // 2.1. Fire off the request connection.connect(); connection.getOutputStream().write(message); connection.getOutputStream().flush(); // 2.2 Await a response // -- It might be possible to send more than one message, but we are not going to do that. Annotation response = serializer.read(connection.getInputStream()).first; // 2.3. Copy response over to original annotation for (Class key : response.keySet()) { annotation.set(key, response.get(key)); } //Succeeded! Can break out of the loop now return; } catch (Throwable t) { // 3. We encountered an error -- retry if (tries == MAX_TRIES - 1) { throw new RuntimeException(t); } log.warn(t); } } } /** Return true if the referenced server is alive and returns a non-error response code. * * @param serverURL The server (running CoreNLP) to check * @return true if the server is alive and returns a response code between 200 and 400 inclusive */ @SuppressWarnings("unused") public boolean checkStatus(URL serverURL) { try { // 1. Set up the connection HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection(); // 1.1 Set authentication if (apiKey != null && apiSecret != null) { String userpass = apiKey + ':' + apiSecret; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); } connection.setRequestMethod("GET"); connection.connect(); return connection.getResponseCode() >= 200 && connection.getResponseCode() <= 400; } catch (Throwable t) { throw new RuntimeException(t); } } /** * Runs the entire pipeline on the content of the given text passed in. * @param text The text to process * @return An Annotation object containing the output of all annotators */ public Annotation process(String text) { Annotation annotation = new Annotation(text); annotate(annotation); return annotation; } /** * Runs an interactive shell where input text is processed with the given pipeline. * * @param pipeline The pipeline to be used * @throws IOException If IO problem with stdin */ private static void shell(StanfordCoreNLPClient pipeline) throws IOException { log.info("Entering interactive shell. Type q RETURN or EOF to quit."); final StanfordCoreNLP.OutputFormat outputFormat = StanfordCoreNLP.OutputFormat.valueOf(pipeline.properties.getProperty("outputFormat", "text").toUpperCase(Locale.ROOT)); IOUtils.console("NLP> ", line -> { if ( ! line.isEmpty()) { Annotation anno = pipeline.process(line); try { switch (outputFormat) { case XML: new XMLOutputter().print(anno, System.out); break; case JSON: new JSONOutputter().print(anno, System.out); System.out.println(); break; case CONLL: new CoNLLOutputter().print(anno, System.out); System.out.println(); break; case TEXT: new TextOutputter().print(anno, System.out); break; case SERIALIZED: warn("You probably cannot read the serialized output, so printing in text instead"); new TextOutputter().print(anno, System.out); break; default: throw new IllegalArgumentException("Cannot output in format " + outputFormat + " from the interactive shell"); } } catch (IOException e) { throw new RuntimeIOException(e); } } }); } /** * The implementation of what to run on a command-line call of CoreNLPWebClient * * @throws IOException If any IO problem */ public void run() throws IOException { StanfordRedwoodConfiguration.minimalSetup(); StanfordCoreNLP.OutputFormat outputFormat = StanfordCoreNLP.OutputFormat.valueOf(properties.getProperty("outputFormat", "text").toUpperCase(Locale.ROOT)); // // Process one file or a directory of files // if (properties.containsKey("file") || properties.containsKey("textFile")) { String fileName = properties.getProperty("file"); if (fileName == null) { fileName = properties.getProperty("textFile"); } Collection<File> files = new FileSequentialCollection(new File(fileName), properties.getProperty("extension"), true); StanfordCoreNLP.processFiles(null, files, 1, properties, this::annotate, StanfordCoreNLP.createOutputter(properties, new AnnotationOutputter.Options()), outputFormat, false); } // // Process a list of files // else if (properties.containsKey("filelist")){ String fileName = properties.getProperty("filelist"); Collection<File> inputFiles = StanfordCoreNLP.readFileList(fileName); Collection<File> files = new ArrayList<>(inputFiles.size()); for (File file : inputFiles) { if (file.isDirectory()) { files.addAll(new FileSequentialCollection(new File(fileName), properties.getProperty("extension"), true)); } else { files.add(file); } } StanfordCoreNLP.processFiles(null, files, 1, properties, this::annotate, StanfordCoreNLP.createOutputter(properties, new AnnotationOutputter.Options()), outputFormat, false); } // // Run the interactive shell // else { shell(this); } } /** * <p> * Good practice to call after you are done with this object. * Shuts down the queue of annotations to run and the associated threads. * </p> * * <p> * If this is not called, any job which has been scheduled but not run will be * cancelled. * </p> */ public void shutdown() throws InterruptedException { scheduler.stateLock.lock(); try { while (!scheduler.queue.isEmpty() || scheduler.freeAnnotators.size() != scheduler.backends.size()) { scheduler.shouldShutdown.await(5, TimeUnit.SECONDS); } scheduler.doRun = false; scheduler.enqueued.signalAll(); // In case the thread's waiting on this condition } finally { scheduler.stateLock.unlock(); } } /** * Client that runs data through a StanfordCoreNLPServer either just for testing or for command-line text processing. * This runs the pipeline you specify on the * text in the file(s) that you specify (with -file or -filelist) and sends some results to stdout. * The current code in this main method assumes that each line of the file * is to be processed separately as a single sentence. * A site must be specified with a protocol like "https:" in front of it. * <p> * Options: * <ul> * <li>-h or -help: print a help message</li> * <li>-backends: Specify the URL of backends to use (default is: http://localhost:9000)</li> * <li>-host and -port: Legacy alternative to -backends</li> * <li>-fallbackToLocalPipeline: If processing via the server fails, try to process a text with a local pipeline</li> * </ul> * * Example usage:<br> * java -mx6g edu.stanford.nlp.pipeline.StanfordCoreNLP -props properties -backends site1:port1,site2:port2 <br> * or just -host https://foo.bar.com [-port 9000] * * @param args List of required properties * @throws java.io.IOException If IO problem */ public static void main(String[] args) throws IOException { // // process the arguments // // extract all the properties from the command line // if cmd line is empty, set the properties to null. The processor will search for the properties file in the classpath // if (args.length < 2) { // log.info("Usage: " + StanfordCoreNLPClient.class.getSimpleName() + " -host <hostname> -port <port> ..."); // System.exit(1); // } Properties props = StringUtils.argsToProperties(args); boolean hasH = props.containsKey("h"); boolean hasHelp = props.containsKey("help"); if (hasH || hasHelp) { String helpValue = hasH ? props.getProperty("h") : props.getProperty("help"); StanfordCoreNLP.printHelp(System.err, helpValue); return; } // Create the backends List<Backend> backends = new ArrayList<>(); String defaultBack = "http://localhost:9000"; String backStr = props.getProperty("backends"); if (backStr == null) { String host = props.getProperty("host"); String port = props.getProperty("port"); if (host != null) { if (port != null) { defaultBack = host + ':' + port; } else { defaultBack = host; } } } for (String spec : props.getProperty("backends", defaultBack).split(",")) { Matcher matcher = URL_PATTERN.matcher(spec.trim()); if (matcher.matches()) { String protocol = matcher.group(1); if (protocol == null) { protocol = "http"; } String host = matcher.group(2); int port = 80; String portStr = matcher.group(3); if (portStr != null) { port = Integer.parseInt(portStr); } backends.add(new Backend(protocol, host, port)); } } log.info("Using backends: " + backends); // Run the pipeline StanfordCoreNLPClient client = new StanfordCoreNLPClient(props, backends); client.fallbackToLocalPipeline = props.containsKey("fallbackToLocalPipeline"); client.run(); try { client.shutdown(); // In case anything is pending on the server } catch (InterruptedException ignored) { } } // end main() }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/pipeline/StanfordCoreNLPClient.java
7,284
// 1.2 Set some protocol-independent properties
line_comment
nl
package edu.stanford.nlp.pipeline; import edu.stanford.nlp.io.FileSequentialCollection; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.io.RuntimeIOException; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.util.PropertiesUtils; import edu.stanford.nlp.util.StringUtils; import edu.stanford.nlp.util.logging.Redwood; import edu.stanford.nlp.util.logging.StanfordRedwoodConfiguration; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static edu.stanford.nlp.util.logging.Redwood.Util.*; /** * An annotation pipeline in spirit identical to {@link StanfordCoreNLP}, but * with the backend supported by a web server. * * @author Gabor Angeli */ @SuppressWarnings("FieldCanBeLocal") public class StanfordCoreNLPClient extends AnnotationPipeline { /** A logger for this class */ private static final Redwood.RedwoodChannels log = Redwood.channels(StanfordCoreNLPClient.class); /** A simple URL spec, for parsing backend URLs */ private static final Pattern URL_PATTERN = Pattern.compile("(?:(https?)://)?([^:]+)(?::([0-9]+))?"); /** * Information on how to connect to a backend. * The semantics of one of these objects is as follows: * * <ul> * <li>It should define a hostname and port to connect to.</li> * <li>This represents ONE thread on the remote server. The client should * treat it as such.</li> * <li>Two backends that are .equals() point to the same endpoint, but there can be * multiple of them if we want to run multiple threads on that endpoint.</li> * </ul> */ private static class Backend { /** The protocol to connect to the server with. */ public final String protocol; /** The hostname of the server running the CoreNLP annotators */ public final String host; /** The port of the server running the CoreNLP annotators */ public final int port; public Backend(String protocol, String host, int port) { this.protocol = protocol; this.host = host; this.port = port; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Backend)) return false; Backend backend = (Backend) o; return port == backend.port && protocol.equals(backend.protocol) && host.equals(backend.host); } @Override public int hashCode() { throw new IllegalStateException("Hashing backends is dangerous!"); } @Override public String toString() { return protocol + "://" + host + ':' + port; } } // end static class Backend /** * A special type of {@link Thread}, which is responsible for scheduling jobs * on the backend. */ private static class BackendScheduler extends Thread { /** * The list of backends that we can schedule on. * This should not generally be called directly from anywhere */ public final List<Backend> backends; /** * The queue on requests for the scheduler to handle. * Each element of this queue is a function: calling the function signals * that this backend is available to perform a task on the passed backend. * It is then obligated to call the passed Consumer to signal that it has * released control of the backend, and it can be used for other things. * Remember to lock access to this object with {@link BackendScheduler#stateLock}. */ private final Queue<BiConsumer<Backend, Consumer<Backend>>> queue; /** * The lock on access to {@link BackendScheduler#queue}. */ private final Lock stateLock = new ReentrantLock(); /** * Represents the event that an item has been added to the work queue. * Linked to {@link BackendScheduler#stateLock}. */ private final Condition enqueued = stateLock.newCondition(); /** * Represents the event that the queue has become empty, and this schedule is no * longer needed. */ public final Condition shouldShutdown = stateLock.newCondition(); /** * The queue of annotators (backends) that are free to be run on. * Remember to lock access to this object with {@link BackendScheduler#stateLock}. */ private final Queue<Backend> freeAnnotators; /** * Represents the event that an annotator has freed up and is available for * work on the {@link BackendScheduler#freeAnnotators} queue. * Linked to {@link BackendScheduler#stateLock}. */ private final Condition newlyFree = stateLock.newCondition(); /** * While this is true, continue running the scheduler. */ private boolean doRun = true; /** * Create a new scheduler from a list of backends. * These can contain duplicates -- in that case, that many concurrent * calls can be made to that backend. */ public BackendScheduler(List<Backend> backends) { super(); setDaemon(true); this.backends = backends; this.freeAnnotators = new LinkedList<>(backends); this.queue = new LinkedList<>(); } /** {@inheritDoc} */ @Override public void run() { try { while (doRun) { // Wait for a request BiConsumer<Backend, Consumer<Backend>> request; Backend annotator; stateLock.lock(); try { while (queue.isEmpty()) { enqueued.await(); if (!doRun) { return; } } // Get the actual request request = queue.poll(); // We have a request // Find a free annotator while (freeAnnotators.isEmpty()) { newlyFree.await(); } annotator = freeAnnotators.poll(); } finally { stateLock.unlock(); } // We have an annotator // Run the annotation request.accept(annotator, freedAnnotator -> { // ASYNC: we've freed this annotator // add it back to the queue and register it as available stateLock.lock(); try { freeAnnotators.add(freedAnnotator); // If the queue is empty, and all the annotators have returned, we're done if (queue.isEmpty() && freeAnnotators.size() == backends.size()) { log.debug("All annotations completed. Signaling for shutdown"); shouldShutdown.signalAll(); } newlyFree.signal(); } finally { stateLock.unlock(); } }); // Annotator is running (in parallel, most likely) } } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * Schedule a new job on the backend * @param annotate A callback, which will be called when a backend is free * to do some processing. The implementation of this callback * MUST CALL the second argument when it is done processing, * to register the backend as free for further work. */ public void schedule(BiConsumer<Backend, Consumer<Backend>> annotate) { stateLock.lock(); try { queue.add(annotate); enqueued.signal(); } finally { stateLock.unlock(); } } } // end static class BackEndScheduler /** The path on the server to connect to. */ private final String path = ""; /** The Properties file to annotate with. */ private final Properties properties; /** The Properties file to send to the server, serialized as JSON. */ private final String propsAsJSON; /** The API key to authenticate with, or null */ private final String apiKey; /** The API secret to authenticate with, or null */ private final String apiSecret; /** The scheduler to use when running on multiple backends at a time */ private final BackendScheduler scheduler; /** * The annotation serializer responsible for translating between the wire format * (protocol buffers) and the {@link Annotation} classes. */ private final ProtobufAnnotationSerializer serializer = new ProtobufAnnotationSerializer(true); private boolean fallbackToLocalPipeline; private int timeoutMilliseconds=0; /** * The main constructor. Create a client from a properties file and a list of backends. * Note that this creates at least one Daemon thread. * * @param properties The properties file, as would be passed to {@link StanfordCoreNLP}. * @param backends The backends to run on. * @param apiKey The key to authenticate with as a username * @param apiSecret The key to authenticate with as a password */ private StanfordCoreNLPClient(Properties properties, List<Backend> backends, String apiKey, String apiSecret) { // Save the constructor variables this.properties = properties; Properties serverProperties = new Properties(); for (String key : properties.stringPropertyNames()) { serverProperties.setProperty(key, properties.getProperty(key)); } Collections.shuffle(backends, new Random(System.currentTimeMillis())); this.scheduler = new BackendScheduler(backends); this.apiKey = apiKey; this.apiSecret = apiSecret; // Set required serverProperties serverProperties.setProperty("inputFormat", "serialized"); serverProperties.setProperty("outputFormat", "serialized"); serverProperties.setProperty("inputSerializer", ProtobufAnnotationSerializer.class.getName()); serverProperties.setProperty("outputSerializer", ProtobufAnnotationSerializer.class.getName()); this.propsAsJSON = PropertiesUtils.propsAsJsonString(serverProperties); // Start 'er up this.scheduler.start(); } /** * The main constructor without credentials. * * @see StanfordCoreNLPClient#StanfordCoreNLPClient(Properties, List, String, String) */ private StanfordCoreNLPClient(Properties properties, List<Backend> backends) { this(properties, backends, null, null); } /** * Run the client, pulling credentials from the environment. * Throws an IllegalStateException if the required environment variables aren't set. * These are: * * <ul> * <li>CORENLP_HOST</li> * <li>CORENLP_KEY</li> * <li>CORENLP_SECRET</li> * </ul> * * @throws IllegalStateException Thrown if we could not read the required environment variables. */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties) throws IllegalStateException { this(properties, Optional.ofNullable(System.getenv("CORENLP_HOST")).orElseThrow(() -> new IllegalStateException("Environment variable CORENLP_HOST not specified")), Optional.ofNullable(System.getenv("CORENLP_HOST")).map(x -> x.startsWith("http://") ? 80 : 443).orElse(443), 1, Optional.ofNullable(System.getenv("CORENLP_KEY")).orElse(null), Optional.ofNullable(System.getenv("CORENLP_SECRET")).orElse(null) ); } /** * Run on a single backend. * * @see StanfordCoreNLPClient (Properties, List) */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties, String host, int port) { this(properties, host, port, 1); } /** * Run on a single backend, with authentication * * @see StanfordCoreNLPClient (Properties, List) */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties, String host, int port, String apiKey, String apiSecret) { this(properties, host, port, 1, apiKey, apiSecret); } /** * Run on a single backend, with authentication * * @see StanfordCoreNLPClient (Properties, List) */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties, String host, String apiKey, String apiSecret) { this(properties, host, host.startsWith("http://") ? 80 : 443, 1, apiKey, apiSecret); } /** * Run on a single backend, but with k threads on each backend. * * @see StanfordCoreNLPClient (Properties, List) */ @SuppressWarnings("unused") public StanfordCoreNLPClient(Properties properties, String host, int port, int threads) { this(properties, host, port, threads, null, null); } /** * Run on a single backend, but with k threads on each backend, and with authentication * * @see StanfordCoreNLPClient (Properties, List) */ public StanfordCoreNLPClient(Properties properties, String host, int port, int threads, String apiKey, String apiSecret) { this(properties, getBackends(host, port, threads), apiKey, apiSecret); } private static List<Backend> getBackends(String host, int port, int threads) { List<Backend> backends = new ArrayList<>(); for (int i = 0; i < threads; i++) { backends.add(new Backend(host.startsWith("http://") ? "http" : "https", host.startsWith("http://") ? host.substring("http://".length()) : (host.startsWith("https://") ? host.substring("https://".length()) : host), port)); } return backends; } public void setTimeoutMilliseconds(int timeout) { this.timeoutMilliseconds = timeout; } /** * {@inheritDoc} * * This method creates an async call to the server, and blocks until the server * has finished annotating the object. */ @Override public void annotate(Annotation annotation) { final Lock lock = new ReentrantLock(); final Condition annotationDone = lock.newCondition(); annotate(Collections.singleton(annotation), 1, (Annotation annInput) -> { try { lock.lock(); annotationDone.signal(); } finally { lock.unlock(); } }); try { lock.lock(); annotationDone.await(); // Only wait for one callback to complete; only annotating one document } catch (InterruptedException e) { log.info("Interrupt while waiting for annotation to return"); } finally { lock.unlock(); } } /** * This method fires off a request to the server. Upon returning, it calls the provided * callback method. * * @param annotations The input annotations to process * @param numThreads The number of threads to run on. IGNORED in this class. * @param callback A function to be called when an annotation finishes. */ @Override public void annotate(final Iterable<Annotation> annotations, int numThreads, final Consumer<Annotation> callback){ for (Annotation annotation : annotations) { annotate(annotation, callback); } } /** * The canonical entry point of the client annotator. * Create an HTTP request, send this annotation to the server, and await a response. * * @param annotation The annotation to annotate. * @param callback Called when the server has returned an annotated document. * The input to this callback is the same as the passed Annotation object. */ public void annotate(final Annotation annotation, final Consumer<Annotation> callback) { scheduler.schedule((Backend backend, Consumer<Backend> isFinishedCallback) -> new Thread(() -> { try { // 1. Create the input // 1.1 Create a protocol buffer ByteArrayOutputStream os = new ByteArrayOutputStream(); serializer.write(annotation, os); os.close(); byte[] message = os.toByteArray(); // 1.2 Create the query params String queryParams = String.format("properties=%s", URLEncoder.encode(StanfordCoreNLPClient.this.propsAsJSON, "utf-8")); // 2. Create a connection URL serverURL = new URL(backend.protocol, backend.host, backend.port, StanfordCoreNLPClient.this.path + '?' + queryParams); // 3. Do the annotation // This method has two contracts: // 1. It should call the two relevant callbacks // 2. It must not throw an exception doAnnotation(annotation, backend, serverURL, message); } catch (Throwable t) { log.err("Could not annotate via server!", t); if (fallbackToLocalPipeline) { log.info("Trying to annotate locally..."); StanfordCoreNLP corenlp = new StanfordCoreNLP(properties); corenlp.annotate(annotation); } else { annotation.set(CoreAnnotations.ExceptionAnnotation.class, t); } } finally { callback.accept(annotation); isFinishedCallback.accept(backend); } }).start()); } static final int MAX_TRIES=3; /** * Actually try to perform the annotation on the server side. * Tries up to 3 times if the first couple don't succeed. * * @param annotation The annotation we need to fill. * @param backend The backend we are querying against. * @param serverURL The URL of the server we are hitting. * @param message The message we are sending the server (don't need to recompute each retry). * @param tries The number of times we've tried already. */ @SuppressWarnings("unchecked") private void doAnnotation(Annotation annotation, Backend backend, URL serverURL, byte[] message) { for (int tries = 0; tries < MAX_TRIES; ++tries) { try { // 1. Set up the connection URLConnection connection = serverURL.openConnection(); // 1.1 Set authentication if (apiKey != null && apiSecret != null) { String userpass = apiKey + ':' + apiSecret; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); } // 1.2 Set<SUF> connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-protobuf"); connection.setRequestProperty("Content-Length", Integer.toString(message.length)); connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestProperty("User-Agent", StanfordCoreNLPClient.class.getName()); if (timeoutMilliseconds > 0) { connection.setConnectTimeout(timeoutMilliseconds); connection.setReadTimeout(timeoutMilliseconds); } // 1.3 Set some protocol-dependent properties switch (backend.protocol) { case "https": case "http": ((HttpURLConnection) connection).setRequestMethod("POST"); break; default: throw new IllegalStateException("Haven't implemented protocol: " + backend.protocol); } // 2. Annotate // 2.1. Fire off the request connection.connect(); connection.getOutputStream().write(message); connection.getOutputStream().flush(); // 2.2 Await a response // -- It might be possible to send more than one message, but we are not going to do that. Annotation response = serializer.read(connection.getInputStream()).first; // 2.3. Copy response over to original annotation for (Class key : response.keySet()) { annotation.set(key, response.get(key)); } //Succeeded! Can break out of the loop now return; } catch (Throwable t) { // 3. We encountered an error -- retry if (tries == MAX_TRIES - 1) { throw new RuntimeException(t); } log.warn(t); } } } /** Return true if the referenced server is alive and returns a non-error response code. * * @param serverURL The server (running CoreNLP) to check * @return true if the server is alive and returns a response code between 200 and 400 inclusive */ @SuppressWarnings("unused") public boolean checkStatus(URL serverURL) { try { // 1. Set up the connection HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection(); // 1.1 Set authentication if (apiKey != null && apiSecret != null) { String userpass = apiKey + ':' + apiSecret; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); } connection.setRequestMethod("GET"); connection.connect(); return connection.getResponseCode() >= 200 && connection.getResponseCode() <= 400; } catch (Throwable t) { throw new RuntimeException(t); } } /** * Runs the entire pipeline on the content of the given text passed in. * @param text The text to process * @return An Annotation object containing the output of all annotators */ public Annotation process(String text) { Annotation annotation = new Annotation(text); annotate(annotation); return annotation; } /** * Runs an interactive shell where input text is processed with the given pipeline. * * @param pipeline The pipeline to be used * @throws IOException If IO problem with stdin */ private static void shell(StanfordCoreNLPClient pipeline) throws IOException { log.info("Entering interactive shell. Type q RETURN or EOF to quit."); final StanfordCoreNLP.OutputFormat outputFormat = StanfordCoreNLP.OutputFormat.valueOf(pipeline.properties.getProperty("outputFormat", "text").toUpperCase(Locale.ROOT)); IOUtils.console("NLP> ", line -> { if ( ! line.isEmpty()) { Annotation anno = pipeline.process(line); try { switch (outputFormat) { case XML: new XMLOutputter().print(anno, System.out); break; case JSON: new JSONOutputter().print(anno, System.out); System.out.println(); break; case CONLL: new CoNLLOutputter().print(anno, System.out); System.out.println(); break; case TEXT: new TextOutputter().print(anno, System.out); break; case SERIALIZED: warn("You probably cannot read the serialized output, so printing in text instead"); new TextOutputter().print(anno, System.out); break; default: throw new IllegalArgumentException("Cannot output in format " + outputFormat + " from the interactive shell"); } } catch (IOException e) { throw new RuntimeIOException(e); } } }); } /** * The implementation of what to run on a command-line call of CoreNLPWebClient * * @throws IOException If any IO problem */ public void run() throws IOException { StanfordRedwoodConfiguration.minimalSetup(); StanfordCoreNLP.OutputFormat outputFormat = StanfordCoreNLP.OutputFormat.valueOf(properties.getProperty("outputFormat", "text").toUpperCase(Locale.ROOT)); // // Process one file or a directory of files // if (properties.containsKey("file") || properties.containsKey("textFile")) { String fileName = properties.getProperty("file"); if (fileName == null) { fileName = properties.getProperty("textFile"); } Collection<File> files = new FileSequentialCollection(new File(fileName), properties.getProperty("extension"), true); StanfordCoreNLP.processFiles(null, files, 1, properties, this::annotate, StanfordCoreNLP.createOutputter(properties, new AnnotationOutputter.Options()), outputFormat, false); } // // Process a list of files // else if (properties.containsKey("filelist")){ String fileName = properties.getProperty("filelist"); Collection<File> inputFiles = StanfordCoreNLP.readFileList(fileName); Collection<File> files = new ArrayList<>(inputFiles.size()); for (File file : inputFiles) { if (file.isDirectory()) { files.addAll(new FileSequentialCollection(new File(fileName), properties.getProperty("extension"), true)); } else { files.add(file); } } StanfordCoreNLP.processFiles(null, files, 1, properties, this::annotate, StanfordCoreNLP.createOutputter(properties, new AnnotationOutputter.Options()), outputFormat, false); } // // Run the interactive shell // else { shell(this); } } /** * <p> * Good practice to call after you are done with this object. * Shuts down the queue of annotations to run and the associated threads. * </p> * * <p> * If this is not called, any job which has been scheduled but not run will be * cancelled. * </p> */ public void shutdown() throws InterruptedException { scheduler.stateLock.lock(); try { while (!scheduler.queue.isEmpty() || scheduler.freeAnnotators.size() != scheduler.backends.size()) { scheduler.shouldShutdown.await(5, TimeUnit.SECONDS); } scheduler.doRun = false; scheduler.enqueued.signalAll(); // In case the thread's waiting on this condition } finally { scheduler.stateLock.unlock(); } } /** * Client that runs data through a StanfordCoreNLPServer either just for testing or for command-line text processing. * This runs the pipeline you specify on the * text in the file(s) that you specify (with -file or -filelist) and sends some results to stdout. * The current code in this main method assumes that each line of the file * is to be processed separately as a single sentence. * A site must be specified with a protocol like "https:" in front of it. * <p> * Options: * <ul> * <li>-h or -help: print a help message</li> * <li>-backends: Specify the URL of backends to use (default is: http://localhost:9000)</li> * <li>-host and -port: Legacy alternative to -backends</li> * <li>-fallbackToLocalPipeline: If processing via the server fails, try to process a text with a local pipeline</li> * </ul> * * Example usage:<br> * java -mx6g edu.stanford.nlp.pipeline.StanfordCoreNLP -props properties -backends site1:port1,site2:port2 <br> * or just -host https://foo.bar.com [-port 9000] * * @param args List of required properties * @throws java.io.IOException If IO problem */ public static void main(String[] args) throws IOException { // // process the arguments // // extract all the properties from the command line // if cmd line is empty, set the properties to null. The processor will search for the properties file in the classpath // if (args.length < 2) { // log.info("Usage: " + StanfordCoreNLPClient.class.getSimpleName() + " -host <hostname> -port <port> ..."); // System.exit(1); // } Properties props = StringUtils.argsToProperties(args); boolean hasH = props.containsKey("h"); boolean hasHelp = props.containsKey("help"); if (hasH || hasHelp) { String helpValue = hasH ? props.getProperty("h") : props.getProperty("help"); StanfordCoreNLP.printHelp(System.err, helpValue); return; } // Create the backends List<Backend> backends = new ArrayList<>(); String defaultBack = "http://localhost:9000"; String backStr = props.getProperty("backends"); if (backStr == null) { String host = props.getProperty("host"); String port = props.getProperty("port"); if (host != null) { if (port != null) { defaultBack = host + ':' + port; } else { defaultBack = host; } } } for (String spec : props.getProperty("backends", defaultBack).split(",")) { Matcher matcher = URL_PATTERN.matcher(spec.trim()); if (matcher.matches()) { String protocol = matcher.group(1); if (protocol == null) { protocol = "http"; } String host = matcher.group(2); int port = 80; String portStr = matcher.group(3); if (portStr != null) { port = Integer.parseInt(portStr); } backends.add(new Backend(protocol, host, port)); } } log.info("Using backends: " + backends); // Run the pipeline StanfordCoreNLPClient client = new StanfordCoreNLPClient(props, backends); client.fallbackToLocalPipeline = props.containsKey("fallbackToLocalPipeline"); client.run(); try { client.shutdown(); // In case anything is pending on the server } catch (InterruptedException ignored) { } } // end main() }
213049_4
/* fEMR - fast Electronic Medical Records Copyright (C) 2014 Team fEMR fEMR is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. fEMR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with fEMR. If not, see <http://www.gnu.org/licenses/>. If you have any questions, contact <[email protected]>. */ package femr.ui.models.triage; import java.util.Date; public class IndexViewModelPost { //begin patient private String firstName; private String lastName; private String phoneNumber; private String address; private String city; private Date age; private String ageClassification; private String sex; public Boolean deletePhoto; //flag to determine if user would like to delete image file //begin vitals private Integer bloodPressureSystolic; private Integer bloodPressureDiastolic; private Integer heartRate; private Float temperature; private Integer respiratoryRate; private Float oxygenSaturation; private Integer heightFeet; private Integer heightInches; private Float weight; private Integer glucose; //begin encounter private String chiefComplaint; private Integer weeksPregnant; //Osman private Integer smoker; private Integer diabetic; private Integer alcohol; private Integer cholesterol; private Integer hypertension; //multiple chief complaints if they exist private String chiefComplaintsJSON; //indicates if the "yes" button was clicked for the diabetes screening prompt private String isDiabetesScreenPerformed; private String patientPhotoCropped; public String getPatientPhotoCropped() { return patientPhotoCropped; } public void setPatientPhotoCropped(String patientPhotoCropped) { this.patientPhotoCropped = patientPhotoCropped; } public Boolean getDeletePhoto() { return deletePhoto; } //begin general info public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Date getAge() { return age; } public void setAge(Date age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } //begin vitals public Integer getBloodPressureSystolic() { return bloodPressureSystolic; } public void setBloodPressureSystolic(Integer bloodPressureSystolic) { this.bloodPressureSystolic = bloodPressureSystolic; } public Integer getBloodPressureDiastolic() { return bloodPressureDiastolic; } public void setBloodPressureDiastolic(Integer bloodPressureDiastolic) { this.bloodPressureDiastolic = bloodPressureDiastolic; } public Integer getHeartRate() { return heartRate; } public void setHeartRate(Integer heartRate) { this.heartRate = heartRate; } public Float getTemperature() { return temperature; } public void setTemperature(Float temperature) { this.temperature = temperature; } public Integer getHeightFeet() { return heightFeet; } public void setHeightFeet(Integer heightFeet) { this.heightFeet = heightFeet; } public Integer getHeightInches() { return heightInches; } public void setHeightInches(Integer heightInches) { this.heightInches = heightInches; } public Float getWeight() { return weight; } public void setWeight(Float weight) { this.weight = weight; } public String getChiefComplaint() { return chiefComplaint; } public void setChiefComplaint(String chiefComplaint) { this.chiefComplaint = chiefComplaint; } public Integer getRespiratoryRate() { return respiratoryRate; } public void setRespiratoryRate(Integer respiratoryRate) { this.respiratoryRate = respiratoryRate; } public Float getOxygenSaturation() { return oxygenSaturation; } public void setOxygenSaturation(Float oxygenSaturation) { this.oxygenSaturation = oxygenSaturation; } public Integer getWeeksPregnant() { return weeksPregnant; } public void setWeeksPregnant(Integer weeksPregnant) { this.weeksPregnant = weeksPregnant; } public Integer getGlucose() { return glucose; } public void setGlucose(Integer glucose) { this.glucose = glucose; } public String getChiefComplaintsJSON() { return chiefComplaintsJSON; } public void setChiefComplaintsJSON(String chiefComplaintsJSON) { this.chiefComplaintsJSON = chiefComplaintsJSON; } public String getAgeClassification() { return ageClassification; } public void setAgeClassification(String ageClassification) { this.ageClassification = ageClassification; } public String getIsDiabetesScreenPerformed() { return isDiabetesScreenPerformed; } public Integer getSmoker() {return smoker;} public void setSmoker(Integer smoker){this.smoker = smoker;} public Integer getDiabetes() {return diabetic;} public void setDiabetic(Integer diabetes){this.diabetic = diabetes;} public Integer getAlcohol() {return alcohol;} public void setAlcohol(Integer alcohol){this.alcohol = alcohol;} public Integer getCholesterol() {return cholesterol;} public void setCholesterol(Integer cholesterol){this.cholesterol = cholesterol;} public Integer getHypertension() {return hypertension;} public void setHypertension(Integer hypertension){this.hypertension = hypertension;} public void setIsDiabetesScreenPerformed(String isDiabetesScreenPerformed) { this.isDiabetesScreenPerformed = isDiabetesScreenPerformed; } }
FEMR/femr
app/femr/ui/models/triage/IndexViewModelPost.java
1,666
//begin general info
line_comment
nl
/* fEMR - fast Electronic Medical Records Copyright (C) 2014 Team fEMR fEMR is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. fEMR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with fEMR. If not, see <http://www.gnu.org/licenses/>. If you have any questions, contact <[email protected]>. */ package femr.ui.models.triage; import java.util.Date; public class IndexViewModelPost { //begin patient private String firstName; private String lastName; private String phoneNumber; private String address; private String city; private Date age; private String ageClassification; private String sex; public Boolean deletePhoto; //flag to determine if user would like to delete image file //begin vitals private Integer bloodPressureSystolic; private Integer bloodPressureDiastolic; private Integer heartRate; private Float temperature; private Integer respiratoryRate; private Float oxygenSaturation; private Integer heightFeet; private Integer heightInches; private Float weight; private Integer glucose; //begin encounter private String chiefComplaint; private Integer weeksPregnant; //Osman private Integer smoker; private Integer diabetic; private Integer alcohol; private Integer cholesterol; private Integer hypertension; //multiple chief complaints if they exist private String chiefComplaintsJSON; //indicates if the "yes" button was clicked for the diabetes screening prompt private String isDiabetesScreenPerformed; private String patientPhotoCropped; public String getPatientPhotoCropped() { return patientPhotoCropped; } public void setPatientPhotoCropped(String patientPhotoCropped) { this.patientPhotoCropped = patientPhotoCropped; } public Boolean getDeletePhoto() { return deletePhoto; } //begin general<SUF> public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Date getAge() { return age; } public void setAge(Date age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } //begin vitals public Integer getBloodPressureSystolic() { return bloodPressureSystolic; } public void setBloodPressureSystolic(Integer bloodPressureSystolic) { this.bloodPressureSystolic = bloodPressureSystolic; } public Integer getBloodPressureDiastolic() { return bloodPressureDiastolic; } public void setBloodPressureDiastolic(Integer bloodPressureDiastolic) { this.bloodPressureDiastolic = bloodPressureDiastolic; } public Integer getHeartRate() { return heartRate; } public void setHeartRate(Integer heartRate) { this.heartRate = heartRate; } public Float getTemperature() { return temperature; } public void setTemperature(Float temperature) { this.temperature = temperature; } public Integer getHeightFeet() { return heightFeet; } public void setHeightFeet(Integer heightFeet) { this.heightFeet = heightFeet; } public Integer getHeightInches() { return heightInches; } public void setHeightInches(Integer heightInches) { this.heightInches = heightInches; } public Float getWeight() { return weight; } public void setWeight(Float weight) { this.weight = weight; } public String getChiefComplaint() { return chiefComplaint; } public void setChiefComplaint(String chiefComplaint) { this.chiefComplaint = chiefComplaint; } public Integer getRespiratoryRate() { return respiratoryRate; } public void setRespiratoryRate(Integer respiratoryRate) { this.respiratoryRate = respiratoryRate; } public Float getOxygenSaturation() { return oxygenSaturation; } public void setOxygenSaturation(Float oxygenSaturation) { this.oxygenSaturation = oxygenSaturation; } public Integer getWeeksPregnant() { return weeksPregnant; } public void setWeeksPregnant(Integer weeksPregnant) { this.weeksPregnant = weeksPregnant; } public Integer getGlucose() { return glucose; } public void setGlucose(Integer glucose) { this.glucose = glucose; } public String getChiefComplaintsJSON() { return chiefComplaintsJSON; } public void setChiefComplaintsJSON(String chiefComplaintsJSON) { this.chiefComplaintsJSON = chiefComplaintsJSON; } public String getAgeClassification() { return ageClassification; } public void setAgeClassification(String ageClassification) { this.ageClassification = ageClassification; } public String getIsDiabetesScreenPerformed() { return isDiabetesScreenPerformed; } public Integer getSmoker() {return smoker;} public void setSmoker(Integer smoker){this.smoker = smoker;} public Integer getDiabetes() {return diabetic;} public void setDiabetic(Integer diabetes){this.diabetic = diabetes;} public Integer getAlcohol() {return alcohol;} public void setAlcohol(Integer alcohol){this.alcohol = alcohol;} public Integer getCholesterol() {return cholesterol;} public void setCholesterol(Integer cholesterol){this.cholesterol = cholesterol;} public Integer getHypertension() {return hypertension;} public void setHypertension(Integer hypertension){this.hypertension = hypertension;} public void setIsDiabetesScreenPerformed(String isDiabetesScreenPerformed) { this.isDiabetesScreenPerformed = isDiabetesScreenPerformed; } }
213107_0
package nl.topicus.cobra.hibernate.id; import org.hibernate.cfg.Configuration; public class AbstractConfigurableId { // We ondersteunen de volgende soorten database. public enum DatabaseType { SQLServer, Oracle; } // Het soort database, standaard Oracle. private DatabaseType databaseType = DatabaseType.Oracle; /** * * Constructor. Bepaalt in welke modus de class moet staan. Wordt bepaalt door de * parameter hibernate.connection.type op te halen uit de properties. */ public AbstractConfigurableId() { String sType = new Configuration().getProperty("hibernate.connection.type"); if (sType != null && sType.equals("SQLServer")) { setDatabaseType(DatabaseType.SQLServer); } else { setDatabaseType(DatabaseType.Oracle); } } /** * Zet de database type. * * @param databaseType * De type database. */ public void setDatabaseType(DatabaseType databaseType) { this.databaseType = databaseType; } /** * Get het database type. * * @return De database type. */ public DatabaseType getDatabaseType() { return databaseType; } }
topicusonderwijs/tribe-krd-opensource
cobra/hibernate/src/main/java/nl/topicus/cobra/hibernate/id/AbstractConfigurableId.java
351
// We ondersteunen de volgende soorten database.
line_comment
nl
package nl.topicus.cobra.hibernate.id; import org.hibernate.cfg.Configuration; public class AbstractConfigurableId { // We ondersteunen<SUF> public enum DatabaseType { SQLServer, Oracle; } // Het soort database, standaard Oracle. private DatabaseType databaseType = DatabaseType.Oracle; /** * * Constructor. Bepaalt in welke modus de class moet staan. Wordt bepaalt door de * parameter hibernate.connection.type op te halen uit de properties. */ public AbstractConfigurableId() { String sType = new Configuration().getProperty("hibernate.connection.type"); if (sType != null && sType.equals("SQLServer")) { setDatabaseType(DatabaseType.SQLServer); } else { setDatabaseType(DatabaseType.Oracle); } } /** * Zet de database type. * * @param databaseType * De type database. */ public void setDatabaseType(DatabaseType databaseType) { this.databaseType = databaseType; } /** * Get het database type. * * @return De database type. */ public DatabaseType getDatabaseType() { return databaseType; } }
213107_1
package nl.topicus.cobra.hibernate.id; import org.hibernate.cfg.Configuration; public class AbstractConfigurableId { // We ondersteunen de volgende soorten database. public enum DatabaseType { SQLServer, Oracle; } // Het soort database, standaard Oracle. private DatabaseType databaseType = DatabaseType.Oracle; /** * * Constructor. Bepaalt in welke modus de class moet staan. Wordt bepaalt door de * parameter hibernate.connection.type op te halen uit de properties. */ public AbstractConfigurableId() { String sType = new Configuration().getProperty("hibernate.connection.type"); if (sType != null && sType.equals("SQLServer")) { setDatabaseType(DatabaseType.SQLServer); } else { setDatabaseType(DatabaseType.Oracle); } } /** * Zet de database type. * * @param databaseType * De type database. */ public void setDatabaseType(DatabaseType databaseType) { this.databaseType = databaseType; } /** * Get het database type. * * @return De database type. */ public DatabaseType getDatabaseType() { return databaseType; } }
topicusonderwijs/tribe-krd-opensource
cobra/hibernate/src/main/java/nl/topicus/cobra/hibernate/id/AbstractConfigurableId.java
351
// Het soort database, standaard Oracle.
line_comment
nl
package nl.topicus.cobra.hibernate.id; import org.hibernate.cfg.Configuration; public class AbstractConfigurableId { // We ondersteunen de volgende soorten database. public enum DatabaseType { SQLServer, Oracle; } // Het soort<SUF> private DatabaseType databaseType = DatabaseType.Oracle; /** * * Constructor. Bepaalt in welke modus de class moet staan. Wordt bepaalt door de * parameter hibernate.connection.type op te halen uit de properties. */ public AbstractConfigurableId() { String sType = new Configuration().getProperty("hibernate.connection.type"); if (sType != null && sType.equals("SQLServer")) { setDatabaseType(DatabaseType.SQLServer); } else { setDatabaseType(DatabaseType.Oracle); } } /** * Zet de database type. * * @param databaseType * De type database. */ public void setDatabaseType(DatabaseType databaseType) { this.databaseType = databaseType; } /** * Get het database type. * * @return De database type. */ public DatabaseType getDatabaseType() { return databaseType; } }
213107_2
package nl.topicus.cobra.hibernate.id; import org.hibernate.cfg.Configuration; public class AbstractConfigurableId { // We ondersteunen de volgende soorten database. public enum DatabaseType { SQLServer, Oracle; } // Het soort database, standaard Oracle. private DatabaseType databaseType = DatabaseType.Oracle; /** * * Constructor. Bepaalt in welke modus de class moet staan. Wordt bepaalt door de * parameter hibernate.connection.type op te halen uit de properties. */ public AbstractConfigurableId() { String sType = new Configuration().getProperty("hibernate.connection.type"); if (sType != null && sType.equals("SQLServer")) { setDatabaseType(DatabaseType.SQLServer); } else { setDatabaseType(DatabaseType.Oracle); } } /** * Zet de database type. * * @param databaseType * De type database. */ public void setDatabaseType(DatabaseType databaseType) { this.databaseType = databaseType; } /** * Get het database type. * * @return De database type. */ public DatabaseType getDatabaseType() { return databaseType; } }
topicusonderwijs/tribe-krd-opensource
cobra/hibernate/src/main/java/nl/topicus/cobra/hibernate/id/AbstractConfigurableId.java
351
/** * * Constructor. Bepaalt in welke modus de class moet staan. Wordt bepaalt door de * parameter hibernate.connection.type op te halen uit de properties. */
block_comment
nl
package nl.topicus.cobra.hibernate.id; import org.hibernate.cfg.Configuration; public class AbstractConfigurableId { // We ondersteunen de volgende soorten database. public enum DatabaseType { SQLServer, Oracle; } // Het soort database, standaard Oracle. private DatabaseType databaseType = DatabaseType.Oracle; /** * * Constructor. Bepaalt in<SUF>*/ public AbstractConfigurableId() { String sType = new Configuration().getProperty("hibernate.connection.type"); if (sType != null && sType.equals("SQLServer")) { setDatabaseType(DatabaseType.SQLServer); } else { setDatabaseType(DatabaseType.Oracle); } } /** * Zet de database type. * * @param databaseType * De type database. */ public void setDatabaseType(DatabaseType databaseType) { this.databaseType = databaseType; } /** * Get het database type. * * @return De database type. */ public DatabaseType getDatabaseType() { return databaseType; } }
213113_0
/** * Vincent Verboven * 14/11/2022 */ public enum Soort { GEWOON,STEUNEND,ERELID }
Meastro85/OOPROG-Java1
P2W1/P2W1/Voetbalclub/src/Soort.java
44
/** * Vincent Verboven * 14/11/2022 */
block_comment
nl
/** * Vincent Verboven <SUF>*/ public enum Soort { GEWOON,STEUNEND,ERELID }
213116_0
package nl.topicus.onderwijs.uwlr.v2.client; import nl.topicus.onderwijs.generated.uwlr.v2_2.LeerlinggegevensVerzoek; public class UwlrRequestBuilder { private String schooljaar; private String xsdversie; private String brincode; private String dependancecode; private String schoolkey; /** De velden gegevenssetid en laatstontvangengegevens ondersteunen we verder niet. */ public UwlrRequestBuilder() {} public UwlrRequestBuilder schooljaar(String schooljaar) { this.schooljaar = schooljaar; return this; } public UwlrRequestBuilder xsdversie(String xsdversie) { this.xsdversie = xsdversie; return this; } public UwlrRequestBuilder brincode(String brincode) { this.brincode = brincode; return this; } public UwlrRequestBuilder dependancecode(String dependancecode) { this.dependancecode = dependancecode; return this; } public LeerlinggegevensVerzoek build() { LeerlinggegevensVerzoek request = new LeerlinggegevensVerzoek(); request.setSchooljaar(schooljaar); request.setXsdversie(xsdversie); request.setBrincode(brincode); request.setDependancecode(dependancecode); request.setSchoolkey(schoolkey); return request; } }
takirchjunger/uwlr-client-server
src/main/java/nl/topicus/onderwijs/uwlr/v2/client/UwlrRequestBuilder.java
356
/** De velden gegevenssetid en laatstontvangengegevens ondersteunen we verder niet. */
block_comment
nl
package nl.topicus.onderwijs.uwlr.v2.client; import nl.topicus.onderwijs.generated.uwlr.v2_2.LeerlinggegevensVerzoek; public class UwlrRequestBuilder { private String schooljaar; private String xsdversie; private String brincode; private String dependancecode; private String schoolkey; /** De velden gegevenssetid<SUF>*/ public UwlrRequestBuilder() {} public UwlrRequestBuilder schooljaar(String schooljaar) { this.schooljaar = schooljaar; return this; } public UwlrRequestBuilder xsdversie(String xsdversie) { this.xsdversie = xsdversie; return this; } public UwlrRequestBuilder brincode(String brincode) { this.brincode = brincode; return this; } public UwlrRequestBuilder dependancecode(String dependancecode) { this.dependancecode = dependancecode; return this; } public LeerlinggegevensVerzoek build() { LeerlinggegevensVerzoek request = new LeerlinggegevensVerzoek(); request.setSchooljaar(schooljaar); request.setXsdversie(xsdversie); request.setBrincode(brincode); request.setDependancecode(dependancecode); request.setSchoolkey(schoolkey); return request; } }
213119_2
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ package nl.bzk.algemeenbrp.dal.domein.brp.annotatie; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotatie om repeating annotations te kunnen ondersteunen. */ @Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Bedrijfsregels { /** * De value van deze annotatie bestaat uit een lijst van {@link Bedrijfsregel}. * @return lijst van {@link Bedrijfsregel} */ Bedrijfsregel[] value(); }
DDDNL/OperatieBRP
Broncode/operatiebrp-code-145.3/algemeen/alg-dal-enumerations/src/main/java/nl/bzk/algemeenbrp/dal/domein/brp/annotatie/Bedrijfsregels.java
258
/** * De value van deze annotatie bestaat uit een lijst van {@link Bedrijfsregel}. * @return lijst van {@link Bedrijfsregel} */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ package nl.bzk.algemeenbrp.dal.domein.brp.annotatie; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotatie om repeating annotations te kunnen ondersteunen. */ @Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Bedrijfsregels { /** * De value van<SUF>*/ Bedrijfsregel[] value(); }
213122_25
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // To be removed in 2.0 @Deprecated Coordinate coorRasterTiff_tiepointLT; @Deprecated Coordinate coorModel_tiepointLT; // AreaOrPoint=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // AreaOrPoint=POINT means that image coordinates refer to // the center of the upper left pixel public enum AreaOrPoint {AREA,POINT} AreaOrPoint areaOrPoint = AreaOrPoint.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double dblModelUnitsPerRasterUnit_X; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double dblModelUnitsPerRasterUnit_Y; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } dblModelUnitsPerRasterUnit_X = fieldModelPixelScale.getAsDouble(0); dblModelUnitsPerRasterUnit_Y = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) dblModelUnitsPerRasterUnit_Y = - Math.abs(dblModelUnitsPerRasterUnit_Y); Logger.debug("gtiff scale : scalex=" + dblModelUnitsPerRasterUnit_X + ", scaley=" + dblModelUnitsPerRasterUnit_Y); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - dblModelUnitsPerRasterUnit_X * imageCoord.x; double ty = modelCoord.y - dblModelUnitsPerRasterUnit_Y * imageCoord.y; // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (areaOrPoint == AreaOrPoint.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getDblModelUnitsPerRasterUnit_X() * rasterULPixelCenter.x + tx, getDblModelUnitsPerRasterUnit_Y() * rasterULPixelCenter.y + ty); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); dblModelUnitsPerRasterUnit_X = transform.getScaleX(); dblModelUnitsPerRasterUnit_Y = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (areaOrPoint == AreaOrPoint.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } ///** // * @param coordinate // */ //@Deprecated //private void setCoorModel_tiepointLT(Coordinate coordinate) { // coorModel_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param coordinate // */ //private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { // coorRasterTiff_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_X(double d) { // dblModelUnitsPerRasterUnit_X = d; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_Y(double d) { // dblModelUnitsPerRasterUnit_Y = d; // // setEnvelope(); //} /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { //return coorModel_tiepointLT; return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); dblModelUnitsPerRasterUnit_X = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) dblModelUnitsPerRasterUnit_Y = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
Xeograph/openjump
src/com/vividsolutions/jump/workbench/imagery/geoimg/GeoReferencedRaster.java
5,559
// int numModelTiePoints = fieldModelTiePoints.getCount() / 6;
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // To be removed in 2.0 @Deprecated Coordinate coorRasterTiff_tiepointLT; @Deprecated Coordinate coorModel_tiepointLT; // AreaOrPoint=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // AreaOrPoint=POINT means that image coordinates refer to // the center of the upper left pixel public enum AreaOrPoint {AREA,POINT} AreaOrPoint areaOrPoint = AreaOrPoint.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double dblModelUnitsPerRasterUnit_X; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double dblModelUnitsPerRasterUnit_Y; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints<SUF> // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } dblModelUnitsPerRasterUnit_X = fieldModelPixelScale.getAsDouble(0); dblModelUnitsPerRasterUnit_Y = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) dblModelUnitsPerRasterUnit_Y = - Math.abs(dblModelUnitsPerRasterUnit_Y); Logger.debug("gtiff scale : scalex=" + dblModelUnitsPerRasterUnit_X + ", scaley=" + dblModelUnitsPerRasterUnit_Y); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - dblModelUnitsPerRasterUnit_X * imageCoord.x; double ty = modelCoord.y - dblModelUnitsPerRasterUnit_Y * imageCoord.y; // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (areaOrPoint == AreaOrPoint.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getDblModelUnitsPerRasterUnit_X() * rasterULPixelCenter.x + tx, getDblModelUnitsPerRasterUnit_Y() * rasterULPixelCenter.y + ty); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); dblModelUnitsPerRasterUnit_X = transform.getScaleX(); dblModelUnitsPerRasterUnit_Y = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (areaOrPoint == AreaOrPoint.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } ///** // * @param coordinate // */ //@Deprecated //private void setCoorModel_tiepointLT(Coordinate coordinate) { // coorModel_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param coordinate // */ //private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { // coorRasterTiff_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_X(double d) { // dblModelUnitsPerRasterUnit_X = d; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_Y(double d) { // dblModelUnitsPerRasterUnit_Y = d; // // setEnvelope(); //} /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { //return coorModel_tiepointLT; return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); dblModelUnitsPerRasterUnit_X = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) dblModelUnitsPerRasterUnit_Y = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
213122_26
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // To be removed in 2.0 @Deprecated Coordinate coorRasterTiff_tiepointLT; @Deprecated Coordinate coorModel_tiepointLT; // AreaOrPoint=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // AreaOrPoint=POINT means that image coordinates refer to // the center of the upper left pixel public enum AreaOrPoint {AREA,POINT} AreaOrPoint areaOrPoint = AreaOrPoint.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double dblModelUnitsPerRasterUnit_X; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double dblModelUnitsPerRasterUnit_Y; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } dblModelUnitsPerRasterUnit_X = fieldModelPixelScale.getAsDouble(0); dblModelUnitsPerRasterUnit_Y = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) dblModelUnitsPerRasterUnit_Y = - Math.abs(dblModelUnitsPerRasterUnit_Y); Logger.debug("gtiff scale : scalex=" + dblModelUnitsPerRasterUnit_X + ", scaley=" + dblModelUnitsPerRasterUnit_Y); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - dblModelUnitsPerRasterUnit_X * imageCoord.x; double ty = modelCoord.y - dblModelUnitsPerRasterUnit_Y * imageCoord.y; // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (areaOrPoint == AreaOrPoint.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getDblModelUnitsPerRasterUnit_X() * rasterULPixelCenter.x + tx, getDblModelUnitsPerRasterUnit_Y() * rasterULPixelCenter.y + ty); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); dblModelUnitsPerRasterUnit_X = transform.getScaleX(); dblModelUnitsPerRasterUnit_Y = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (areaOrPoint == AreaOrPoint.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } ///** // * @param coordinate // */ //@Deprecated //private void setCoorModel_tiepointLT(Coordinate coordinate) { // coorModel_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param coordinate // */ //private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { // coorRasterTiff_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_X(double d) { // dblModelUnitsPerRasterUnit_X = d; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_Y(double d) { // dblModelUnitsPerRasterUnit_Y = d; // // setEnvelope(); //} /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { //return coorModel_tiepointLT; return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); dblModelUnitsPerRasterUnit_X = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) dblModelUnitsPerRasterUnit_Y = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
Xeograph/openjump
src/com/vividsolutions/jump/workbench/imagery/geoimg/GeoReferencedRaster.java
5,559
// ToDo: alleen numModelTiePoints == 1 ondersteunen.
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // To be removed in 2.0 @Deprecated Coordinate coorRasterTiff_tiepointLT; @Deprecated Coordinate coorModel_tiepointLT; // AreaOrPoint=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // AreaOrPoint=POINT means that image coordinates refer to // the center of the upper left pixel public enum AreaOrPoint {AREA,POINT} AreaOrPoint areaOrPoint = AreaOrPoint.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double dblModelUnitsPerRasterUnit_X; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double dblModelUnitsPerRasterUnit_Y; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen<SUF> // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } dblModelUnitsPerRasterUnit_X = fieldModelPixelScale.getAsDouble(0); dblModelUnitsPerRasterUnit_Y = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) dblModelUnitsPerRasterUnit_Y = - Math.abs(dblModelUnitsPerRasterUnit_Y); Logger.debug("gtiff scale : scalex=" + dblModelUnitsPerRasterUnit_X + ", scaley=" + dblModelUnitsPerRasterUnit_Y); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - dblModelUnitsPerRasterUnit_X * imageCoord.x; double ty = modelCoord.y - dblModelUnitsPerRasterUnit_Y * imageCoord.y; // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (areaOrPoint == AreaOrPoint.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getDblModelUnitsPerRasterUnit_X() * rasterULPixelCenter.x + tx, getDblModelUnitsPerRasterUnit_Y() * rasterULPixelCenter.y + ty); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); dblModelUnitsPerRasterUnit_X = transform.getScaleX(); dblModelUnitsPerRasterUnit_Y = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (areaOrPoint == AreaOrPoint.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } ///** // * @param coordinate // */ //@Deprecated //private void setCoorModel_tiepointLT(Coordinate coordinate) { // coorModel_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param coordinate // */ //private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { // coorRasterTiff_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_X(double d) { // dblModelUnitsPerRasterUnit_X = d; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_Y(double d) { // dblModelUnitsPerRasterUnit_Y = d; // // setEnvelope(); //} /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { //return coorModel_tiepointLT; return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); dblModelUnitsPerRasterUnit_X = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) dblModelUnitsPerRasterUnit_Y = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
213122_90
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // To be removed in 2.0 @Deprecated Coordinate coorRasterTiff_tiepointLT; @Deprecated Coordinate coorModel_tiepointLT; // AreaOrPoint=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // AreaOrPoint=POINT means that image coordinates refer to // the center of the upper left pixel public enum AreaOrPoint {AREA,POINT} AreaOrPoint areaOrPoint = AreaOrPoint.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double dblModelUnitsPerRasterUnit_X; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double dblModelUnitsPerRasterUnit_Y; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } dblModelUnitsPerRasterUnit_X = fieldModelPixelScale.getAsDouble(0); dblModelUnitsPerRasterUnit_Y = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) dblModelUnitsPerRasterUnit_Y = - Math.abs(dblModelUnitsPerRasterUnit_Y); Logger.debug("gtiff scale : scalex=" + dblModelUnitsPerRasterUnit_X + ", scaley=" + dblModelUnitsPerRasterUnit_Y); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - dblModelUnitsPerRasterUnit_X * imageCoord.x; double ty = modelCoord.y - dblModelUnitsPerRasterUnit_Y * imageCoord.y; // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (areaOrPoint == AreaOrPoint.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getDblModelUnitsPerRasterUnit_X() * rasterULPixelCenter.x + tx, getDblModelUnitsPerRasterUnit_Y() * rasterULPixelCenter.y + ty); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); dblModelUnitsPerRasterUnit_X = transform.getScaleX(); dblModelUnitsPerRasterUnit_Y = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (areaOrPoint == AreaOrPoint.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } ///** // * @param coordinate // */ //@Deprecated //private void setCoorModel_tiepointLT(Coordinate coordinate) { // coorModel_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param coordinate // */ //private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { // coorRasterTiff_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_X(double d) { // dblModelUnitsPerRasterUnit_X = d; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_Y(double d) { // dblModelUnitsPerRasterUnit_Y = d; // // setEnvelope(); //} /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { //return coorModel_tiepointLT; return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); dblModelUnitsPerRasterUnit_X = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) dblModelUnitsPerRasterUnit_Y = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
Xeograph/openjump
src/com/vividsolutions/jump/workbench/imagery/geoimg/GeoReferencedRaster.java
5,559
//private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) {
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // To be removed in 2.0 @Deprecated Coordinate coorRasterTiff_tiepointLT; @Deprecated Coordinate coorModel_tiepointLT; // AreaOrPoint=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // AreaOrPoint=POINT means that image coordinates refer to // the center of the upper left pixel public enum AreaOrPoint {AREA,POINT} AreaOrPoint areaOrPoint = AreaOrPoint.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double dblModelUnitsPerRasterUnit_X; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double dblModelUnitsPerRasterUnit_Y; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } dblModelUnitsPerRasterUnit_X = fieldModelPixelScale.getAsDouble(0); dblModelUnitsPerRasterUnit_Y = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) dblModelUnitsPerRasterUnit_Y = - Math.abs(dblModelUnitsPerRasterUnit_Y); Logger.debug("gtiff scale : scalex=" + dblModelUnitsPerRasterUnit_X + ", scaley=" + dblModelUnitsPerRasterUnit_Y); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - dblModelUnitsPerRasterUnit_X * imageCoord.x; double ty = modelCoord.y - dblModelUnitsPerRasterUnit_Y * imageCoord.y; // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (areaOrPoint == AreaOrPoint.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getDblModelUnitsPerRasterUnit_X() * rasterULPixelCenter.x + tx, getDblModelUnitsPerRasterUnit_Y() * rasterULPixelCenter.y + ty); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); dblModelUnitsPerRasterUnit_X = transform.getScaleX(); dblModelUnitsPerRasterUnit_Y = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (areaOrPoint == AreaOrPoint.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } ///** // * @param coordinate // */ //@Deprecated //private void setCoorModel_tiepointLT(Coordinate coordinate) { // coorModel_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param coordinate // */ //private void<SUF> // coorRasterTiff_tiepointLT = coordinate; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_X(double d) { // dblModelUnitsPerRasterUnit_X = d; // // setEnvelope(); //} ///** // * @param d // */ //private void setDblModelUnitsPerRasterUnit_Y(double d) { // dblModelUnitsPerRasterUnit_Y = d; // // setEnvelope(); //} /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { //return coorModel_tiepointLT; return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); dblModelUnitsPerRasterUnit_X = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) dblModelUnitsPerRasterUnit_Y = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
213131_5
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL); // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0) ); setCoorModel_tiepointLT(new Coordinate(0, 0) ); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src .getProperty("tiff.directory"); if (dir == null) throw new Exception("This is not a (geo)tiff file."); try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception( "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
hastebrot/openjump-core-rels
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,414
// int numModelTiePoints = fieldModelTiePoints.getCount() / 6;
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL); // Get the number of modeltiepoints // int numModelTiePoints<SUF> // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0) ); setCoorModel_tiepointLT(new Coordinate(0, 0) ); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src .getProperty("tiff.directory"); if (dir == null) throw new Exception("This is not a (geo)tiff file."); try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception( "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
213131_6
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL); // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0) ); setCoorModel_tiepointLT(new Coordinate(0, 0) ); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src .getProperty("tiff.directory"); if (dir == null) throw new Exception("This is not a (geo)tiff file."); try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception( "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
hastebrot/openjump-core-rels
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,414
// ToDo: alleen numModelTiePoints == 1 ondersteunen.
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL); // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen<SUF> // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0) ); setCoorModel_tiepointLT(new Coordinate(0, 0) ); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src .getProperty("tiff.directory"); if (dir == null) throw new Exception("This is not a (geo)tiff file."); try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception( "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
213132_16
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } // setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
openjump-gis/openjump-migration
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,930
// setCoorModel_tiepointLT(new Coordinate(0, 0));
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0,<SUF> // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } // setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
213132_18
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } // setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
openjump-gis/openjump-migration
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,930
// int numModelTiePoints = fieldModelTiePoints.getCount() / 6;
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints<SUF> // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } // setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
213132_19
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } // setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
openjump-gis/openjump-migration
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,930
// ToDo: alleen numModelTiePoints == 1 ondersteunen.
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen<SUF> // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } // setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
213132_30
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } // setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
openjump-gis/openjump-migration
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,930
// setCoorModel_tiepointLT(new Coordinate(0, 0));
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } // setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); // setCoorModel_tiepointLT(new Coordinate(0,<SUF> // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
213133_16
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src.getProperty("tiff.directory"); if (dir == null) { throw new Exception("This is not a (geo)tiff file."); } try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception("Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
julienperret/OpenJUMP
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,777
// int numModelTiePoints = fieldModelTiePoints.getCount() / 6;
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } else { // Get the number of modeltiepoints // int numModelTiePoints<SUF> // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src.getProperty("tiff.directory"); if (dir == null) { throw new Exception("This is not a (geo)tiff file."); } try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception("Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
213133_17
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src.getProperty("tiff.directory"); if (dir == null) { throw new Exception("This is not a (geo)tiff file."); } try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception("Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
julienperret/OpenJUMP
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,777
// ToDo: alleen numModelTiePoints == 1 ondersteunen.
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen<SUF> // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws Exception { // Get the name of the tiff worldfile. String name = worldFileName(); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(name); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } setCoorRasterTiff_tiepointLT(new Coordinate(0, 0)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { // ImageCodec originalCodec = ImageCodec.getCodec("tiff"); super.readRasterfile(); // Get access to the tags and geokeys. // First, get the TIFF directory GeoTIFFDirectory dir = (GeoTIFFDirectory) src.getProperty("tiff.directory"); if (dir == null) { throw new Exception("This is not a (geo)tiff file."); } try { // Try to parse any embedded geotiff tags. parseGeoTIFFDirectory(dir); } catch (Exception E) { // Embedded geotiff tags have not been found. Try // to use a geotiff world file. try { parseWorldFile(); } catch (Exception e) { throw new Exception("Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL); } } } }
213137_15
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; Envelope envModel_image; Envelope envModel_image_backup; Coordinate coorRasterTiff_tiepointLT; Coordinate coorModel_tiepointLT; private double dblModelUnitsPerRasterUnit_X; private double dblModelUnitsPerRasterUnit_Y; // boolean hoPatch = false; /** * Called by Java2XML * * @throws ReferencedImageException */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); fileName = imageFileLocation; readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem acessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new // Coordinate(-0.5, // -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); Logger.debug("gtiff trans: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } Logger.debug("gtiff tiepoints found."); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { // if (!GDALUtilities.isGDALAvailable()) // throw new // ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper // left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper // left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("wf: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri; try { uri = new URI(imageFileLocation); } catch (URISyntaxException e) { throw new ReferencedImageException(e); } // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } //if (false) try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } double[] tags = new double[6]; tags[0] = 1; // pixel size in x // direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the // y-direction tags[4] = 0; // x-coordinate of the // center of the upper // left pixel tags[5] = 0; // y-coordinate of the // center of the upper // left pixel setEnvelope(tags); Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(this.getClass().getName() + ".no-geo-reference-found"); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); AffineTransform transform = new AffineTransform(tags); double scaleX = Math.abs(transform.getScaleX()); double scaleY = Math.abs(transform.getScaleY()); setDblModelUnitsPerRasterUnit_X(scaleX); setDblModelUnitsPerRasterUnit_Y(scaleY); Point2D rasterLT = new Point2D.Double(src.getMinX(), src.getMinY()); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); setCoorRasterTiff_tiepointLT(new Coordinate(rasterLT.getX(), rasterLT.getY())); setCoorModel_tiepointLT(new Coordinate(modelLT.getX(), modelLT.getY())); setEnvelope(); } void setEnvelope() { Coordinate coorRaster_imageLB = new Coordinate(coorRasterTiff_tiepointLT.x, src.getHeight(), 0); Coordinate coorRaster_imageRT = new Coordinate(src.getWidth(), 0, 0); Coordinate coorModel_imageLB = rasterToModelSpace(coorRaster_imageLB); Coordinate coorModel_imageRT = rasterToModelSpace(coorRaster_imageRT); envModel_image = new Envelope(coorModel_imageLB, coorModel_imageRT); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = coorModel_tiepointLT.x + (coorRaster.x - coorRasterTiff_tiepointLT.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = coorModel_tiepointLT.y - (coorRaster.y + coorRasterTiff_tiepointLT.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @param coordinate */ private void setCoorModel_tiepointLT(Coordinate coordinate) { coorModel_tiepointLT = coordinate; // setEnvelope(); } /** * @param coordinate */ private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { coorRasterTiff_tiepointLT = coordinate; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_X(double d) { dblModelUnitsPerRasterUnit_X = d; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_Y(double d) { dblModelUnitsPerRasterUnit_Y = d; // setEnvelope(); } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { return coorModel_tiepointLT; } /** * @return coordinate of left-top corner in the raster coordinate system */ public Coordinate getCoorRasterTiff_tiepointLT() { return coorRasterTiff_tiepointLT; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); setDblModelUnitsPerRasterUnit_X(xUnit); double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); setDblModelUnitsPerRasterUnit_Y(yUnit); // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
openjump-gis/openjump-migration
src/com/vividsolutions/jump/workbench/imagery/geoimg/GeoReferencedRaster.java
4,758
// setCoorModel_tiepointLT(new Coordinate(0, 0));
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; Envelope envModel_image; Envelope envModel_image_backup; Coordinate coorRasterTiff_tiepointLT; Coordinate coorModel_tiepointLT; private double dblModelUnitsPerRasterUnit_X; private double dblModelUnitsPerRasterUnit_Y; // boolean hoPatch = false; /** * Called by Java2XML * * @throws ReferencedImageException */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); fileName = imageFileLocation; readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem acessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new // Coordinate(-0.5, // -0,5)); // setCoorModel_tiepointLT(new Coordinate(0,<SUF> // setAffineTransformation(new AffineTransform(tags)); Logger.debug("gtiff trans: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } Logger.debug("gtiff tiepoints found."); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { // if (!GDALUtilities.isGDALAvailable()) // throw new // ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper // left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper // left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("wf: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri; try { uri = new URI(imageFileLocation); } catch (URISyntaxException e) { throw new ReferencedImageException(e); } // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } //if (false) try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } double[] tags = new double[6]; tags[0] = 1; // pixel size in x // direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the // y-direction tags[4] = 0; // x-coordinate of the // center of the upper // left pixel tags[5] = 0; // y-coordinate of the // center of the upper // left pixel setEnvelope(tags); Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(this.getClass().getName() + ".no-geo-reference-found"); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); AffineTransform transform = new AffineTransform(tags); double scaleX = Math.abs(transform.getScaleX()); double scaleY = Math.abs(transform.getScaleY()); setDblModelUnitsPerRasterUnit_X(scaleX); setDblModelUnitsPerRasterUnit_Y(scaleY); Point2D rasterLT = new Point2D.Double(src.getMinX(), src.getMinY()); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); setCoorRasterTiff_tiepointLT(new Coordinate(rasterLT.getX(), rasterLT.getY())); setCoorModel_tiepointLT(new Coordinate(modelLT.getX(), modelLT.getY())); setEnvelope(); } void setEnvelope() { Coordinate coorRaster_imageLB = new Coordinate(coorRasterTiff_tiepointLT.x, src.getHeight(), 0); Coordinate coorRaster_imageRT = new Coordinate(src.getWidth(), 0, 0); Coordinate coorModel_imageLB = rasterToModelSpace(coorRaster_imageLB); Coordinate coorModel_imageRT = rasterToModelSpace(coorRaster_imageRT); envModel_image = new Envelope(coorModel_imageLB, coorModel_imageRT); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = coorModel_tiepointLT.x + (coorRaster.x - coorRasterTiff_tiepointLT.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = coorModel_tiepointLT.y - (coorRaster.y + coorRasterTiff_tiepointLT.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @param coordinate */ private void setCoorModel_tiepointLT(Coordinate coordinate) { coorModel_tiepointLT = coordinate; // setEnvelope(); } /** * @param coordinate */ private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { coorRasterTiff_tiepointLT = coordinate; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_X(double d) { dblModelUnitsPerRasterUnit_X = d; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_Y(double d) { dblModelUnitsPerRasterUnit_Y = d; // setEnvelope(); } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { return coorModel_tiepointLT; } /** * @return coordinate of left-top corner in the raster coordinate system */ public Coordinate getCoorRasterTiff_tiepointLT() { return coorRasterTiff_tiepointLT; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); setDblModelUnitsPerRasterUnit_X(xUnit); double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); setDblModelUnitsPerRasterUnit_Y(yUnit); // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
213137_18
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; Envelope envModel_image; Envelope envModel_image_backup; Coordinate coorRasterTiff_tiepointLT; Coordinate coorModel_tiepointLT; private double dblModelUnitsPerRasterUnit_X; private double dblModelUnitsPerRasterUnit_Y; // boolean hoPatch = false; /** * Called by Java2XML * * @throws ReferencedImageException */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); fileName = imageFileLocation; readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem acessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new // Coordinate(-0.5, // -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); Logger.debug("gtiff trans: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } Logger.debug("gtiff tiepoints found."); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { // if (!GDALUtilities.isGDALAvailable()) // throw new // ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper // left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper // left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("wf: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri; try { uri = new URI(imageFileLocation); } catch (URISyntaxException e) { throw new ReferencedImageException(e); } // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } //if (false) try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } double[] tags = new double[6]; tags[0] = 1; // pixel size in x // direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the // y-direction tags[4] = 0; // x-coordinate of the // center of the upper // left pixel tags[5] = 0; // y-coordinate of the // center of the upper // left pixel setEnvelope(tags); Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(this.getClass().getName() + ".no-geo-reference-found"); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); AffineTransform transform = new AffineTransform(tags); double scaleX = Math.abs(transform.getScaleX()); double scaleY = Math.abs(transform.getScaleY()); setDblModelUnitsPerRasterUnit_X(scaleX); setDblModelUnitsPerRasterUnit_Y(scaleY); Point2D rasterLT = new Point2D.Double(src.getMinX(), src.getMinY()); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); setCoorRasterTiff_tiepointLT(new Coordinate(rasterLT.getX(), rasterLT.getY())); setCoorModel_tiepointLT(new Coordinate(modelLT.getX(), modelLT.getY())); setEnvelope(); } void setEnvelope() { Coordinate coorRaster_imageLB = new Coordinate(coorRasterTiff_tiepointLT.x, src.getHeight(), 0); Coordinate coorRaster_imageRT = new Coordinate(src.getWidth(), 0, 0); Coordinate coorModel_imageLB = rasterToModelSpace(coorRaster_imageLB); Coordinate coorModel_imageRT = rasterToModelSpace(coorRaster_imageRT); envModel_image = new Envelope(coorModel_imageLB, coorModel_imageRT); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = coorModel_tiepointLT.x + (coorRaster.x - coorRasterTiff_tiepointLT.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = coorModel_tiepointLT.y - (coorRaster.y + coorRasterTiff_tiepointLT.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @param coordinate */ private void setCoorModel_tiepointLT(Coordinate coordinate) { coorModel_tiepointLT = coordinate; // setEnvelope(); } /** * @param coordinate */ private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { coorRasterTiff_tiepointLT = coordinate; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_X(double d) { dblModelUnitsPerRasterUnit_X = d; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_Y(double d) { dblModelUnitsPerRasterUnit_Y = d; // setEnvelope(); } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { return coorModel_tiepointLT; } /** * @return coordinate of left-top corner in the raster coordinate system */ public Coordinate getCoorRasterTiff_tiepointLT() { return coorRasterTiff_tiepointLT; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); setDblModelUnitsPerRasterUnit_X(xUnit); double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); setDblModelUnitsPerRasterUnit_Y(yUnit); // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
openjump-gis/openjump-migration
src/com/vividsolutions/jump/workbench/imagery/geoimg/GeoReferencedRaster.java
4,758
// int numModelTiePoints = fieldModelTiePoints.getCount() / 6;
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; Envelope envModel_image; Envelope envModel_image_backup; Coordinate coorRasterTiff_tiepointLT; Coordinate coorModel_tiepointLT; private double dblModelUnitsPerRasterUnit_X; private double dblModelUnitsPerRasterUnit_Y; // boolean hoPatch = false; /** * Called by Java2XML * * @throws ReferencedImageException */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); fileName = imageFileLocation; readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem acessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new // Coordinate(-0.5, // -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); Logger.debug("gtiff trans: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else { // Get the number of modeltiepoints // int numModelTiePoints<SUF> // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } Logger.debug("gtiff tiepoints found."); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { // if (!GDALUtilities.isGDALAvailable()) // throw new // ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper // left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper // left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("wf: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri; try { uri = new URI(imageFileLocation); } catch (URISyntaxException e) { throw new ReferencedImageException(e); } // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } //if (false) try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } double[] tags = new double[6]; tags[0] = 1; // pixel size in x // direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the // y-direction tags[4] = 0; // x-coordinate of the // center of the upper // left pixel tags[5] = 0; // y-coordinate of the // center of the upper // left pixel setEnvelope(tags); Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(this.getClass().getName() + ".no-geo-reference-found"); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); AffineTransform transform = new AffineTransform(tags); double scaleX = Math.abs(transform.getScaleX()); double scaleY = Math.abs(transform.getScaleY()); setDblModelUnitsPerRasterUnit_X(scaleX); setDblModelUnitsPerRasterUnit_Y(scaleY); Point2D rasterLT = new Point2D.Double(src.getMinX(), src.getMinY()); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); setCoorRasterTiff_tiepointLT(new Coordinate(rasterLT.getX(), rasterLT.getY())); setCoorModel_tiepointLT(new Coordinate(modelLT.getX(), modelLT.getY())); setEnvelope(); } void setEnvelope() { Coordinate coorRaster_imageLB = new Coordinate(coorRasterTiff_tiepointLT.x, src.getHeight(), 0); Coordinate coorRaster_imageRT = new Coordinate(src.getWidth(), 0, 0); Coordinate coorModel_imageLB = rasterToModelSpace(coorRaster_imageLB); Coordinate coorModel_imageRT = rasterToModelSpace(coorRaster_imageRT); envModel_image = new Envelope(coorModel_imageLB, coorModel_imageRT); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = coorModel_tiepointLT.x + (coorRaster.x - coorRasterTiff_tiepointLT.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = coorModel_tiepointLT.y - (coorRaster.y + coorRasterTiff_tiepointLT.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @param coordinate */ private void setCoorModel_tiepointLT(Coordinate coordinate) { coorModel_tiepointLT = coordinate; // setEnvelope(); } /** * @param coordinate */ private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { coorRasterTiff_tiepointLT = coordinate; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_X(double d) { dblModelUnitsPerRasterUnit_X = d; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_Y(double d) { dblModelUnitsPerRasterUnit_Y = d; // setEnvelope(); } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { return coorModel_tiepointLT; } /** * @return coordinate of left-top corner in the raster coordinate system */ public Coordinate getCoorRasterTiff_tiepointLT() { return coorRasterTiff_tiepointLT; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); setDblModelUnitsPerRasterUnit_X(xUnit); double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); setDblModelUnitsPerRasterUnit_Y(yUnit); // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
213137_19
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; Envelope envModel_image; Envelope envModel_image_backup; Coordinate coorRasterTiff_tiepointLT; Coordinate coorModel_tiepointLT; private double dblModelUnitsPerRasterUnit_X; private double dblModelUnitsPerRasterUnit_Y; // boolean hoPatch = false; /** * Called by Java2XML * * @throws ReferencedImageException */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); fileName = imageFileLocation; readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem acessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new // Coordinate(-0.5, // -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); Logger.debug("gtiff trans: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } Logger.debug("gtiff tiepoints found."); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { // if (!GDALUtilities.isGDALAvailable()) // throw new // ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper // left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper // left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("wf: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri; try { uri = new URI(imageFileLocation); } catch (URISyntaxException e) { throw new ReferencedImageException(e); } // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } //if (false) try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } double[] tags = new double[6]; tags[0] = 1; // pixel size in x // direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the // y-direction tags[4] = 0; // x-coordinate of the // center of the upper // left pixel tags[5] = 0; // y-coordinate of the // center of the upper // left pixel setEnvelope(tags); Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(this.getClass().getName() + ".no-geo-reference-found"); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); AffineTransform transform = new AffineTransform(tags); double scaleX = Math.abs(transform.getScaleX()); double scaleY = Math.abs(transform.getScaleY()); setDblModelUnitsPerRasterUnit_X(scaleX); setDblModelUnitsPerRasterUnit_Y(scaleY); Point2D rasterLT = new Point2D.Double(src.getMinX(), src.getMinY()); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); setCoorRasterTiff_tiepointLT(new Coordinate(rasterLT.getX(), rasterLT.getY())); setCoorModel_tiepointLT(new Coordinate(modelLT.getX(), modelLT.getY())); setEnvelope(); } void setEnvelope() { Coordinate coorRaster_imageLB = new Coordinate(coorRasterTiff_tiepointLT.x, src.getHeight(), 0); Coordinate coorRaster_imageRT = new Coordinate(src.getWidth(), 0, 0); Coordinate coorModel_imageLB = rasterToModelSpace(coorRaster_imageLB); Coordinate coorModel_imageRT = rasterToModelSpace(coorRaster_imageRT); envModel_image = new Envelope(coorModel_imageLB, coorModel_imageRT); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = coorModel_tiepointLT.x + (coorRaster.x - coorRasterTiff_tiepointLT.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = coorModel_tiepointLT.y - (coorRaster.y + coorRasterTiff_tiepointLT.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @param coordinate */ private void setCoorModel_tiepointLT(Coordinate coordinate) { coorModel_tiepointLT = coordinate; // setEnvelope(); } /** * @param coordinate */ private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { coorRasterTiff_tiepointLT = coordinate; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_X(double d) { dblModelUnitsPerRasterUnit_X = d; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_Y(double d) { dblModelUnitsPerRasterUnit_Y = d; // setEnvelope(); } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { return coorModel_tiepointLT; } /** * @return coordinate of left-top corner in the raster coordinate system */ public Coordinate getCoorRasterTiff_tiepointLT() { return coorRasterTiff_tiepointLT; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); setDblModelUnitsPerRasterUnit_X(xUnit); double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); setDblModelUnitsPerRasterUnit_Y(yUnit); // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
openjump-gis/openjump-migration
src/com/vividsolutions/jump/workbench/imagery/geoimg/GeoReferencedRaster.java
4,758
// ToDo: alleen numModelTiePoints == 1 ondersteunen.
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; Envelope envModel_image; Envelope envModel_image_backup; Coordinate coorRasterTiff_tiepointLT; Coordinate coorModel_tiepointLT; private double dblModelUnitsPerRasterUnit_X; private double dblModelUnitsPerRasterUnit_Y; // boolean hoPatch = false; /** * Called by Java2XML * * @throws ReferencedImageException */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); fileName = imageFileLocation; readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem acessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new // Coordinate(-0.5, // -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); Logger.debug("gtiff trans: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen<SUF> // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } Logger.debug("gtiff tiepoints found."); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { // if (!GDALUtilities.isGDALAvailable()) // throw new // ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper // left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper // left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("wf: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri; try { uri = new URI(imageFileLocation); } catch (URISyntaxException e) { throw new ReferencedImageException(e); } // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } //if (false) try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } double[] tags = new double[6]; tags[0] = 1; // pixel size in x // direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the // y-direction tags[4] = 0; // x-coordinate of the // center of the upper // left pixel tags[5] = 0; // y-coordinate of the // center of the upper // left pixel setEnvelope(tags); Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(this.getClass().getName() + ".no-geo-reference-found"); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); AffineTransform transform = new AffineTransform(tags); double scaleX = Math.abs(transform.getScaleX()); double scaleY = Math.abs(transform.getScaleY()); setDblModelUnitsPerRasterUnit_X(scaleX); setDblModelUnitsPerRasterUnit_Y(scaleY); Point2D rasterLT = new Point2D.Double(src.getMinX(), src.getMinY()); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); setCoorRasterTiff_tiepointLT(new Coordinate(rasterLT.getX(), rasterLT.getY())); setCoorModel_tiepointLT(new Coordinate(modelLT.getX(), modelLT.getY())); setEnvelope(); } void setEnvelope() { Coordinate coorRaster_imageLB = new Coordinate(coorRasterTiff_tiepointLT.x, src.getHeight(), 0); Coordinate coorRaster_imageRT = new Coordinate(src.getWidth(), 0, 0); Coordinate coorModel_imageLB = rasterToModelSpace(coorRaster_imageLB); Coordinate coorModel_imageRT = rasterToModelSpace(coorRaster_imageRT); envModel_image = new Envelope(coorModel_imageLB, coorModel_imageRT); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = coorModel_tiepointLT.x + (coorRaster.x - coorRasterTiff_tiepointLT.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = coorModel_tiepointLT.y - (coorRaster.y + coorRasterTiff_tiepointLT.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @param coordinate */ private void setCoorModel_tiepointLT(Coordinate coordinate) { coorModel_tiepointLT = coordinate; // setEnvelope(); } /** * @param coordinate */ private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { coorRasterTiff_tiepointLT = coordinate; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_X(double d) { dblModelUnitsPerRasterUnit_X = d; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_Y(double d) { dblModelUnitsPerRasterUnit_Y = d; // setEnvelope(); } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { return coorModel_tiepointLT; } /** * @return coordinate of left-top corner in the raster coordinate system */ public Coordinate getCoorRasterTiff_tiepointLT() { return coorRasterTiff_tiepointLT; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); setDblModelUnitsPerRasterUnit_X(xUnit); double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); setDblModelUnitsPerRasterUnit_Y(yUnit); // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
213143_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.bericht.model.xml; /** * Ondersteunende class om teletex strings te coderen en decoderen om ze in XML te kunnen gebruiken. Dit ivm het feit * dat in XML de meeste control characters (0x00 t/m 0x1F) niet zijn toegestaan, ook niet als entity encoding of cdata. * * De control characters worden gecodeerd als unicode characters 0x1000 t/m 0x101F. */ public final class XmlTeletexEncoding { private static final char MAX_CONTROL_CHARACTER = 0x1F; private static final char ENCODING_OFFSET = 0x1000; private static final int EXTRA_ENCODING_BUFFER = 10; private XmlTeletexEncoding() { } /** * Codeer een teletex string voor XML. * @param teletex de teletex string * @return de gecodeerde teletex string */ public static String codeer(final String teletex) { if (teletex == null) { return null; } final int lengte = teletex.length(); final StringBuilder sb = new StringBuilder(lengte + EXTRA_ENCODING_BUFFER); for (int index = 0; index < lengte; index++) { final char c = teletex.charAt(index); if (c <= MAX_CONTROL_CHARACTER) { sb.append((char) (c + ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } /** * Decodeer een teletex string uit XML. * @param encodedTeletex de gecodeerde teletex string * @return de teletex string */ public static String decodeer(final String encodedTeletex) { if (encodedTeletex == null) { return null; } final int lengte = encodedTeletex.length(); final StringBuilder sb = new StringBuilder(lengte); for (int index = 0; index < lengte; index++) { final char c = encodedTeletex.charAt(index); if (c >= ENCODING_OFFSET && c <= ENCODING_OFFSET + MAX_CONTROL_CHARACTER) { sb.append((char) (c - ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-bericht-model/src/main/java/nl/bzk/migratiebrp/bericht/model/xml/XmlTeletexEncoding.java
694
/** * Ondersteunende class om teletex strings te coderen en decoderen om ze in XML te kunnen gebruiken. Dit ivm het feit * dat in XML de meeste control characters (0x00 t/m 0x1F) niet zijn toegestaan, ook niet als entity encoding of cdata. * * De control characters worden gecodeerd als unicode characters 0x1000 t/m 0x101F. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.bericht.model.xml; /** * Ondersteunende class om<SUF>*/ public final class XmlTeletexEncoding { private static final char MAX_CONTROL_CHARACTER = 0x1F; private static final char ENCODING_OFFSET = 0x1000; private static final int EXTRA_ENCODING_BUFFER = 10; private XmlTeletexEncoding() { } /** * Codeer een teletex string voor XML. * @param teletex de teletex string * @return de gecodeerde teletex string */ public static String codeer(final String teletex) { if (teletex == null) { return null; } final int lengte = teletex.length(); final StringBuilder sb = new StringBuilder(lengte + EXTRA_ENCODING_BUFFER); for (int index = 0; index < lengte; index++) { final char c = teletex.charAt(index); if (c <= MAX_CONTROL_CHARACTER) { sb.append((char) (c + ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } /** * Decodeer een teletex string uit XML. * @param encodedTeletex de gecodeerde teletex string * @return de teletex string */ public static String decodeer(final String encodedTeletex) { if (encodedTeletex == null) { return null; } final int lengte = encodedTeletex.length(); final StringBuilder sb = new StringBuilder(lengte); for (int index = 0; index < lengte; index++) { final char c = encodedTeletex.charAt(index); if (c >= ENCODING_OFFSET && c <= ENCODING_OFFSET + MAX_CONTROL_CHARACTER) { sb.append((char) (c - ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } }
213143_2
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.bericht.model.xml; /** * Ondersteunende class om teletex strings te coderen en decoderen om ze in XML te kunnen gebruiken. Dit ivm het feit * dat in XML de meeste control characters (0x00 t/m 0x1F) niet zijn toegestaan, ook niet als entity encoding of cdata. * * De control characters worden gecodeerd als unicode characters 0x1000 t/m 0x101F. */ public final class XmlTeletexEncoding { private static final char MAX_CONTROL_CHARACTER = 0x1F; private static final char ENCODING_OFFSET = 0x1000; private static final int EXTRA_ENCODING_BUFFER = 10; private XmlTeletexEncoding() { } /** * Codeer een teletex string voor XML. * @param teletex de teletex string * @return de gecodeerde teletex string */ public static String codeer(final String teletex) { if (teletex == null) { return null; } final int lengte = teletex.length(); final StringBuilder sb = new StringBuilder(lengte + EXTRA_ENCODING_BUFFER); for (int index = 0; index < lengte; index++) { final char c = teletex.charAt(index); if (c <= MAX_CONTROL_CHARACTER) { sb.append((char) (c + ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } /** * Decodeer een teletex string uit XML. * @param encodedTeletex de gecodeerde teletex string * @return de teletex string */ public static String decodeer(final String encodedTeletex) { if (encodedTeletex == null) { return null; } final int lengte = encodedTeletex.length(); final StringBuilder sb = new StringBuilder(lengte); for (int index = 0; index < lengte; index++) { final char c = encodedTeletex.charAt(index); if (c >= ENCODING_OFFSET && c <= ENCODING_OFFSET + MAX_CONTROL_CHARACTER) { sb.append((char) (c - ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-bericht-model/src/main/java/nl/bzk/migratiebrp/bericht/model/xml/XmlTeletexEncoding.java
694
/** * Codeer een teletex string voor XML. * @param teletex de teletex string * @return de gecodeerde teletex string */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.bericht.model.xml; /** * Ondersteunende class om teletex strings te coderen en decoderen om ze in XML te kunnen gebruiken. Dit ivm het feit * dat in XML de meeste control characters (0x00 t/m 0x1F) niet zijn toegestaan, ook niet als entity encoding of cdata. * * De control characters worden gecodeerd als unicode characters 0x1000 t/m 0x101F. */ public final class XmlTeletexEncoding { private static final char MAX_CONTROL_CHARACTER = 0x1F; private static final char ENCODING_OFFSET = 0x1000; private static final int EXTRA_ENCODING_BUFFER = 10; private XmlTeletexEncoding() { } /** * Codeer een teletex<SUF>*/ public static String codeer(final String teletex) { if (teletex == null) { return null; } final int lengte = teletex.length(); final StringBuilder sb = new StringBuilder(lengte + EXTRA_ENCODING_BUFFER); for (int index = 0; index < lengte; index++) { final char c = teletex.charAt(index); if (c <= MAX_CONTROL_CHARACTER) { sb.append((char) (c + ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } /** * Decodeer een teletex string uit XML. * @param encodedTeletex de gecodeerde teletex string * @return de teletex string */ public static String decodeer(final String encodedTeletex) { if (encodedTeletex == null) { return null; } final int lengte = encodedTeletex.length(); final StringBuilder sb = new StringBuilder(lengte); for (int index = 0; index < lengte; index++) { final char c = encodedTeletex.charAt(index); if (c >= ENCODING_OFFSET && c <= ENCODING_OFFSET + MAX_CONTROL_CHARACTER) { sb.append((char) (c - ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } }
213143_3
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.bericht.model.xml; /** * Ondersteunende class om teletex strings te coderen en decoderen om ze in XML te kunnen gebruiken. Dit ivm het feit * dat in XML de meeste control characters (0x00 t/m 0x1F) niet zijn toegestaan, ook niet als entity encoding of cdata. * * De control characters worden gecodeerd als unicode characters 0x1000 t/m 0x101F. */ public final class XmlTeletexEncoding { private static final char MAX_CONTROL_CHARACTER = 0x1F; private static final char ENCODING_OFFSET = 0x1000; private static final int EXTRA_ENCODING_BUFFER = 10; private XmlTeletexEncoding() { } /** * Codeer een teletex string voor XML. * @param teletex de teletex string * @return de gecodeerde teletex string */ public static String codeer(final String teletex) { if (teletex == null) { return null; } final int lengte = teletex.length(); final StringBuilder sb = new StringBuilder(lengte + EXTRA_ENCODING_BUFFER); for (int index = 0; index < lengte; index++) { final char c = teletex.charAt(index); if (c <= MAX_CONTROL_CHARACTER) { sb.append((char) (c + ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } /** * Decodeer een teletex string uit XML. * @param encodedTeletex de gecodeerde teletex string * @return de teletex string */ public static String decodeer(final String encodedTeletex) { if (encodedTeletex == null) { return null; } final int lengte = encodedTeletex.length(); final StringBuilder sb = new StringBuilder(lengte); for (int index = 0; index < lengte; index++) { final char c = encodedTeletex.charAt(index); if (c >= ENCODING_OFFSET && c <= ENCODING_OFFSET + MAX_CONTROL_CHARACTER) { sb.append((char) (c - ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-bericht-model/src/main/java/nl/bzk/migratiebrp/bericht/model/xml/XmlTeletexEncoding.java
694
/** * Decodeer een teletex string uit XML. * @param encodedTeletex de gecodeerde teletex string * @return de teletex string */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.bericht.model.xml; /** * Ondersteunende class om teletex strings te coderen en decoderen om ze in XML te kunnen gebruiken. Dit ivm het feit * dat in XML de meeste control characters (0x00 t/m 0x1F) niet zijn toegestaan, ook niet als entity encoding of cdata. * * De control characters worden gecodeerd als unicode characters 0x1000 t/m 0x101F. */ public final class XmlTeletexEncoding { private static final char MAX_CONTROL_CHARACTER = 0x1F; private static final char ENCODING_OFFSET = 0x1000; private static final int EXTRA_ENCODING_BUFFER = 10; private XmlTeletexEncoding() { } /** * Codeer een teletex string voor XML. * @param teletex de teletex string * @return de gecodeerde teletex string */ public static String codeer(final String teletex) { if (teletex == null) { return null; } final int lengte = teletex.length(); final StringBuilder sb = new StringBuilder(lengte + EXTRA_ENCODING_BUFFER); for (int index = 0; index < lengte; index++) { final char c = teletex.charAt(index); if (c <= MAX_CONTROL_CHARACTER) { sb.append((char) (c + ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } /** * Decodeer een teletex<SUF>*/ public static String decodeer(final String encodedTeletex) { if (encodedTeletex == null) { return null; } final int lengte = encodedTeletex.length(); final StringBuilder sb = new StringBuilder(lengte); for (int index = 0; index < lengte; index++) { final char c = encodedTeletex.charAt(index); if (c >= ENCODING_OFFSET && c <= ENCODING_OFFSET + MAX_CONTROL_CHARACTER) { sb.append((char) (c - ENCODING_OFFSET)); } else { sb.append(c); } } return sb.toString(); } }
213148_25
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; /** * Most georeferencing is done from this class. * * Georeferencing may use GeoTiff tags, GDAL metadata or a worlfile like tfw, * pgw or jgw. * <p> * In geotiff, the Raster Space is defined by GTRasterTypeGeoKey and can be * RasterPixelIsArea or RasterPixelIsPoint.</p> * <p> * In RasterPixelIsArea, image coordinate (0,0) is the upper left coordinate of * the image and the first pixel value applies to the whole cell (from coordinate * (0,0) to (1,1)). This is the default value, but it is now recommended to * specify it explicitly.</p> * <p> * In RasterPixelIsPoint, we consider that the first value of the image matrix * (0,0) applies to point located at the center of the upper left pixel. This is * mostly used for elevation dataset like DTM</p> * <p> * Geotiff georeferencement may be defined as a transformation matrix or from * a tiepoint and scale factors. Georeferencement from several tiepoints is * not supported by OpenJUMP).</p> * <p> * Warning : if georeferencement is defined by a single tiepoint along with a * scalex and a scaley factor, the tiepoint may be on the upper-left corner of * the upper-left pixel, on the center of the pixel or at any place as long as * the model coordinate represent the transformation of the image coordinate * (see here after for the interpretation of image coordinate) * </p> * <p> * World file defines an affine transformation with its tx and ty translation * parameters defined relatively to the center of the upper left pixel.</p> * * javadoc added by mmichaud on 2021-05-23 */ public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // PixelType=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // PixelType=POINT means that image coordinates refer to // the center of the upper left pixel public enum PixelType {AREA,POINT} PixelType pixelType = PixelType.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double scaleX; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double scaleY; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contain other GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } scaleX = fieldModelPixelScale.getAsDouble(0); scaleY = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) scaleY = - Math.abs(scaleY); Logger.debug("gtiff scale : scalex=" + scaleX + ", scaley=" + scaleY); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - scaleX * imageCoord.x; double ty = modelCoord.y - scaleY * imageCoord.y; Logger.debug("translation " + tx + " - " + ty); // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (pixelType == PixelType.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getScaleX() * rasterULPixelCenter.x + tx, getScaleY() * rasterULPixelCenter.y + ty); Logger.debug("model UL pixel center " + modelULPixelCenter); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List<String> lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); if (pixelType == PixelType.AREA) { // For PixelType.AREA, 0,0 image coordinate refers to the UL corner of the UL pixel // not its center as for worldfile tags[4] = tags[4] - tags[0]*0.5; tags[5] = tags[5] - tags[3]*0.5; } setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.getInstance().get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); scaleX = transform.getScaleX(); scaleY = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (pixelType == PixelType.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); Logger.debug("setEnvelope " + rasterLT + " -> " + modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); Logger.debug("Image envelope " + ulx + "," + uly + "," + (ulx+src.getWidth()) + "," + (uly+src.getHeight())); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); Logger.debug("Model envelope " + modelEnvelopeBL.x + "," + modelEnvelopeTR.y + "," + modelEnvelopeTR.x + "," + modelEnvelopeBL.y); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * scaleX; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * scaleY; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getModelULPixelCenter() { return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getScaleX() { return scaleX; } /** * @return number of model units per raster unit along Y axis */ public double getScaleY() { return scaleY; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f != null && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getRenderedOp(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); scaleX = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) scaleY = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
openjump-gis/openjump
src/com/vividsolutions/jump/workbench/imagery/geoimg/GeoReferencedRaster.java
5,722
// int numModelTiePoints = fieldModelTiePoints.getCount() / 6;
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; /** * Most georeferencing is done from this class. * * Georeferencing may use GeoTiff tags, GDAL metadata or a worlfile like tfw, * pgw or jgw. * <p> * In geotiff, the Raster Space is defined by GTRasterTypeGeoKey and can be * RasterPixelIsArea or RasterPixelIsPoint.</p> * <p> * In RasterPixelIsArea, image coordinate (0,0) is the upper left coordinate of * the image and the first pixel value applies to the whole cell (from coordinate * (0,0) to (1,1)). This is the default value, but it is now recommended to * specify it explicitly.</p> * <p> * In RasterPixelIsPoint, we consider that the first value of the image matrix * (0,0) applies to point located at the center of the upper left pixel. This is * mostly used for elevation dataset like DTM</p> * <p> * Geotiff georeferencement may be defined as a transformation matrix or from * a tiepoint and scale factors. Georeferencement from several tiepoints is * not supported by OpenJUMP).</p> * <p> * Warning : if georeferencement is defined by a single tiepoint along with a * scalex and a scaley factor, the tiepoint may be on the upper-left corner of * the upper-left pixel, on the center of the pixel or at any place as long as * the model coordinate represent the transformation of the image coordinate * (see here after for the interpretation of image coordinate) * </p> * <p> * World file defines an affine transformation with its tx and ty translation * parameters defined relatively to the center of the upper left pixel.</p> * * javadoc added by mmichaud on 2021-05-23 */ public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // PixelType=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // PixelType=POINT means that image coordinates refer to // the center of the upper left pixel public enum PixelType {AREA,POINT} PixelType pixelType = PixelType.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double scaleX; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double scaleY; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints<SUF> // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contain other GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } scaleX = fieldModelPixelScale.getAsDouble(0); scaleY = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) scaleY = - Math.abs(scaleY); Logger.debug("gtiff scale : scalex=" + scaleX + ", scaley=" + scaleY); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - scaleX * imageCoord.x; double ty = modelCoord.y - scaleY * imageCoord.y; Logger.debug("translation " + tx + " - " + ty); // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (pixelType == PixelType.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getScaleX() * rasterULPixelCenter.x + tx, getScaleY() * rasterULPixelCenter.y + ty); Logger.debug("model UL pixel center " + modelULPixelCenter); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List<String> lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); if (pixelType == PixelType.AREA) { // For PixelType.AREA, 0,0 image coordinate refers to the UL corner of the UL pixel // not its center as for worldfile tags[4] = tags[4] - tags[0]*0.5; tags[5] = tags[5] - tags[3]*0.5; } setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.getInstance().get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); scaleX = transform.getScaleX(); scaleY = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (pixelType == PixelType.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); Logger.debug("setEnvelope " + rasterLT + " -> " + modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); Logger.debug("Image envelope " + ulx + "," + uly + "," + (ulx+src.getWidth()) + "," + (uly+src.getHeight())); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); Logger.debug("Model envelope " + modelEnvelopeBL.x + "," + modelEnvelopeTR.y + "," + modelEnvelopeTR.x + "," + modelEnvelopeBL.y); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * scaleX; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * scaleY; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getModelULPixelCenter() { return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getScaleX() { return scaleX; } /** * @return number of model units per raster unit along Y axis */ public double getScaleY() { return scaleY; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f != null && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getRenderedOp(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); scaleX = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) scaleY = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
213148_26
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; /** * Most georeferencing is done from this class. * * Georeferencing may use GeoTiff tags, GDAL metadata or a worlfile like tfw, * pgw or jgw. * <p> * In geotiff, the Raster Space is defined by GTRasterTypeGeoKey and can be * RasterPixelIsArea or RasterPixelIsPoint.</p> * <p> * In RasterPixelIsArea, image coordinate (0,0) is the upper left coordinate of * the image and the first pixel value applies to the whole cell (from coordinate * (0,0) to (1,1)). This is the default value, but it is now recommended to * specify it explicitly.</p> * <p> * In RasterPixelIsPoint, we consider that the first value of the image matrix * (0,0) applies to point located at the center of the upper left pixel. This is * mostly used for elevation dataset like DTM</p> * <p> * Geotiff georeferencement may be defined as a transformation matrix or from * a tiepoint and scale factors. Georeferencement from several tiepoints is * not supported by OpenJUMP).</p> * <p> * Warning : if georeferencement is defined by a single tiepoint along with a * scalex and a scaley factor, the tiepoint may be on the upper-left corner of * the upper-left pixel, on the center of the pixel or at any place as long as * the model coordinate represent the transformation of the image coordinate * (see here after for the interpretation of image coordinate) * </p> * <p> * World file defines an affine transformation with its tx and ty translation * parameters defined relatively to the center of the upper left pixel.</p> * * javadoc added by mmichaud on 2021-05-23 */ public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // PixelType=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // PixelType=POINT means that image coordinates refer to // the center of the upper left pixel public enum PixelType {AREA,POINT} PixelType pixelType = PixelType.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double scaleX; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double scaleY; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contain other GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } scaleX = fieldModelPixelScale.getAsDouble(0); scaleY = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) scaleY = - Math.abs(scaleY); Logger.debug("gtiff scale : scalex=" + scaleX + ", scaley=" + scaleY); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - scaleX * imageCoord.x; double ty = modelCoord.y - scaleY * imageCoord.y; Logger.debug("translation " + tx + " - " + ty); // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (pixelType == PixelType.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getScaleX() * rasterULPixelCenter.x + tx, getScaleY() * rasterULPixelCenter.y + ty); Logger.debug("model UL pixel center " + modelULPixelCenter); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List<String> lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); if (pixelType == PixelType.AREA) { // For PixelType.AREA, 0,0 image coordinate refers to the UL corner of the UL pixel // not its center as for worldfile tags[4] = tags[4] - tags[0]*0.5; tags[5] = tags[5] - tags[3]*0.5; } setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.getInstance().get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); scaleX = transform.getScaleX(); scaleY = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (pixelType == PixelType.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); Logger.debug("setEnvelope " + rasterLT + " -> " + modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); Logger.debug("Image envelope " + ulx + "," + uly + "," + (ulx+src.getWidth()) + "," + (uly+src.getHeight())); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); Logger.debug("Model envelope " + modelEnvelopeBL.x + "," + modelEnvelopeTR.y + "," + modelEnvelopeTR.x + "," + modelEnvelopeBL.y); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * scaleX; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * scaleY; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getModelULPixelCenter() { return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getScaleX() { return scaleX; } /** * @return number of model units per raster unit along Y axis */ public double getScaleY() { return scaleY; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f != null && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getRenderedOp(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); scaleX = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) scaleY = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
openjump-gis/openjump
src/com/vividsolutions/jump/workbench/imagery/geoimg/GeoReferencedRaster.java
5,722
// ToDo: alleen numModelTiePoints == 1 ondersteunen.
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import com.vividsolutions.jump.I18N; import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import it.geosolutions.imageio.gdalframework.GDALUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; /** * Most georeferencing is done from this class. * * Georeferencing may use GeoTiff tags, GDAL metadata or a worlfile like tfw, * pgw or jgw. * <p> * In geotiff, the Raster Space is defined by GTRasterTypeGeoKey and can be * RasterPixelIsArea or RasterPixelIsPoint.</p> * <p> * In RasterPixelIsArea, image coordinate (0,0) is the upper left coordinate of * the image and the first pixel value applies to the whole cell (from coordinate * (0,0) to (1,1)). This is the default value, but it is now recommended to * specify it explicitly.</p> * <p> * In RasterPixelIsPoint, we consider that the first value of the image matrix * (0,0) applies to point located at the center of the upper left pixel. This is * mostly used for elevation dataset like DTM</p> * <p> * Geotiff georeferencement may be defined as a transformation matrix or from * a tiepoint and scale factors. Georeferencement from several tiepoints is * not supported by OpenJUMP).</p> * <p> * Warning : if georeferencement is defined by a single tiepoint along with a * scalex and a scaley factor, the tiepoint may be on the upper-left corner of * the upper-left pixel, on the center of the pixel or at any place as long as * the model coordinate represent the transformation of the image coordinate * (see here after for the interpretation of image coordinate) * </p> * <p> * World file defines an affine transformation with its tx and ty translation * parameters defined relatively to the center of the upper left pixel.</p> * * javadoc added by mmichaud on 2021-05-23 */ public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; Envelope envModel_image; Envelope envModel_image_backup; // PixelType=AREA (default) means that image coordinates // refer to the upper left corner of the upper left angle. // PixelType=POINT means that image coordinates refer to // the center of the upper left pixel public enum PixelType {AREA,POINT} PixelType pixelType = PixelType.AREA; //https://trac.osgeo.org/gdal/ticket/4977 boolean honourNegativeScaleY = false; // Rename upper left image coordinate with more expressive names // Remarks in GeoTIFF, rasterULPixelCenter is // 0.5, 0.5 in AREA_OR_POINT=Area (default) // 0, 0 in AREA_OR_POINT=Point private Coordinate rasterULPixelCenter; private Coordinate modelULPixelCenter; private double scaleX; // [michaudm 2020-11-16] signed y-scale // to be able to handle north-south oriented or south-north oriented images private double scaleY; /** * Called by Java2XML */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem accessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; // pixel size in x direction (x-scale) tags[0] = fieldModelGeoTransform.getAsDouble(0); // rotation about y-axis tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about x-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // pixel size in the y-direction (y-scale) tags[3] = fieldModelGeoTransform.getAsDouble(5); // x-ordinate of the center of the upper left pixel tags[4] = fieldModelGeoTransform.getAsDouble(3); // y-ordinate of the center of the upper left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); Logger.debug("gtiff transform: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else if (fieldModelTiePoints.getType() == XTIFFField.TIFF_DOUBLE) { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen<SUF> // Map the modeltiepoints from raster to model space // Read the tiepoints // imageCoord has not the same meaning in AREA and in POINT mode, // but here, we don't mind, imageCoord may represent any point in // the image, important thing is that imageCoord and modelCoord // represent the same point in the image and in the model // coordinate system. Coordinate imageCoord = new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1)); Coordinate modelCoord = new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4)); Logger.debug("gtiff tiepoints found : " + Arrays.toString(fieldModelTiePoints.getAsDoubles())); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contain other GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } scaleX = fieldModelPixelScale.getAsDouble(0); scaleY = fieldModelPixelScale.getAsDouble(1); //https://trac.osgeo.org/gdal/ticket/4977 if (!honourNegativeScaleY) scaleY = - Math.abs(scaleY); Logger.debug("gtiff scale : scalex=" + scaleX + ", scaley=" + scaleY); // To compute the translation parameters of the transformation, we need // to know how a point is converted from image to model coordinate, we // don't mind where this point is. double tx = modelCoord.x - scaleX * imageCoord.x; double ty = modelCoord.y - scaleY * imageCoord.y; Logger.debug("translation " + tx + " - " + ty); // Now, we want to know the model coordinate of the point precisely // located at the center of the upper left pixel. // Coordinates of this point is not the same in AREA and in POINT modes rasterULPixelCenter = (pixelType == PixelType.AREA) ? new Coordinate(0.5,0.5) : new Coordinate(0.0,0.0); modelULPixelCenter = new Coordinate( getScaleX() * rasterULPixelCenter.x + tx, getScaleY() * rasterULPixelCenter.y + ty); Logger.debug("model UL pixel center " + modelULPixelCenter); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { if (!areGDALClassesAvailable || !GDALUtilities.isGDALAvailable()) throw new ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(getURI().toString()); // Read the tags from the tiff worldfile. List<String> lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("worldfile: " + Arrays.toString(tags)); if (pixelType == PixelType.AREA) { // For PixelType.AREA, 0,0 image coordinate refers to the UL corner of the UL pixel // not its center as for worldfile tags[4] = tags[4] - tags[0]*0.5; tags[5] = tags[5] - tags[3]*0.5; } setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } /** * initialize the img and try to parse geo infos via (in this order) * worldfile, gdal or geotiff */ protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri = getURI(); // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); if (envModel_image != null) { // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(I18N.getInstance().get(this.getClass().getName() + ".no-georeference-found")); // set up a default envelope double[] tags = new double[6]; tags[0] = 1; // pixel size in x direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the y-direction tags[4] = 0; // x-coordinate of the center of the upper left pixel tags[5] = 0; // y-coordinate of the center of the upper left pixel setEnvelope(tags); } private void setEnvelope(double[] tags) { AffineTransform transform = new AffineTransform(tags); //We should honour negative scale y, but gdal created plenty of //files where sign is not correct. //We now have to consider that the scale y sign is not significative //and offer an option to honour negative scales //https://trac.osgeo.org/gdal/ticket/4977 //double scaleX = Math.abs(transform.getScaleX()); //double scaleY = Math.abs(transform.getScaleY()); scaleX = transform.getScaleX(); scaleY = transform.getScaleY(); // To compute the envelope in AreaOrPoint.AREA mode, we need to // know that upper left pixel center is at 0.5, 0.5, not 0, 0 double offset = (pixelType == PixelType.AREA) ? 0.5 : 0.0; Point2D rasterLT = new Point2D.Double(src.getMinX()+offset, src.getMinY()+offset); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); Logger.debug("setEnvelope " + rasterLT + " -> " + modelLT); rasterULPixelCenter = new Coordinate(rasterLT.getX(), rasterLT.getY()); modelULPixelCenter = new Coordinate(modelLT.getX(), modelLT.getY()); setEnvelope(); } void setEnvelope() { // Image coordinate of the upper left corner of the envelope double ulx = rasterULPixelCenter.x-0.5; double uly = rasterULPixelCenter.y-0.5; // Bottom left coordinate of the envelope Coordinate imageEnvelopeBL = new Coordinate(ulx,uly+src.getHeight()); // Top right coordinate of the envelope Coordinate imageEnvelopeTR = new Coordinate(ulx+src.getWidth(), uly); Logger.debug("Image envelope " + ulx + "," + uly + "," + (ulx+src.getWidth()) + "," + (uly+src.getHeight())); // Transform envelope corners to the model coordinate system Coordinate modelEnvelopeBL = rasterToModelSpace(imageEnvelopeBL); Coordinate modelEnvelopeTR = rasterToModelSpace(imageEnvelopeTR); Logger.debug("Model envelope " + modelEnvelopeBL.x + "," + modelEnvelopeTR.y + "," + modelEnvelopeTR.x + "," + modelEnvelopeBL.y); envModel_image = new Envelope(modelEnvelopeBL, modelEnvelopeTR); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = modelULPixelCenter.x + (coorRaster.x - rasterULPixelCenter.x) * scaleX; coorModel.y = modelULPixelCenter.y + (coorRaster.y - rasterULPixelCenter.y) * scaleY; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getModelULPixelCenter() { return modelULPixelCenter; } /** * @return coordinate of left-top corner in the raster coordinate system */ @Deprecated public Coordinate getCoorRasterTiff_tiepointLT() { //return coorRasterTiff_tiepointLT; return rasterULPixelCenter; } /** * @return number of model units per raster unit along X axis */ public double getScaleX() { return scaleX; } /** * @return number of model units per raster unit along Y axis */ public double getScaleY() { return scaleY; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f != null && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getRenderedOp(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); scaleX = xUnit; double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); // y-scale is generally negative (won't work if model y axis is top-down) scaleY = -yUnit; // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }