answer
stringlengths
17
10.2M
package me.dreamteam.tardis; import javax.swing.*; import javax.swing.plaf.ColorUIResource; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.*; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Main Class */ public class Game extends Canvas { GProperties properties = new GProperties(); Sound sound; Database database = new Database(); public Game() { JFrame container = new JFrame(Utils.gameName + "- " + Utils.build + Utils.version); JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(500, 650)); panel.setLayout(null); panel.setBackground(Color.black); setBounds(0, 0, 500, 650); panel.add(this); setIgnoreRepaint(true); container.setResizable(false); container.pack(); while(GProperties.release == false){ try { Thread.sleep(10); } catch (Exception e) {} } container.setVisible(true); // Set up elements colours UIManager UI = new UIManager(); UI.put("OptionPane.background", new ColorUIResource(0, 0, 0)); UI.put("Panel.background", new ColorUIResource(0, 0, 0)); UI.put("OptionPane.messageForeground", new ColorUIResource(255, 255, 255)); // Window setup Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = container.getSize().width; int h = container.getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; container.setLocation(x, y); container.setBackground(Color.black); properties.sX = x; properties.sY = y; //What to do when user choose to close container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Utils.quitGame(); } }); container.addWindowListener(new WindowAdapter() { public void windowIconified(WindowEvent e) { // To be done later, minimize event } }); container.addWindowListener(new WindowAdapter() { public void windowDeiconified(WindowEvent e) { // To be done later, restore event } }); ImageIcon icon = new ImageIcon(Utils.iconURL); container.setIconImage(icon.getImage()); // create the buffering strategy for graphics createBufferStrategy(2); properties.strategy = getBufferStrategy(); Graphics2D gix = (Graphics2D) properties.strategy.getDrawGraphics(); ImageIcon splashbgicon = new ImageIcon(Utils.splashURL); properties.splashbg = splashbgicon.getImage(); gix.drawImage(properties.splashbg, 0, 0, null); gix.setColor(Color.DARK_GRAY); gix.setFont(new Font("Century Gothic", Font.BOLD + Font.ITALIC, Utils.splashFS)); gix.drawString(Utils.build + Utils.version, (1070 - gix.getFontMetrics().stringWidth(Utils.gameName)) / 2, 648); properties.strategy.show(); gix.dispose(); // Register Font try { URL fontUrl = me.dreamteam.tardis.Game.class.getResource("/fonts/Volter.ttf"); Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream()); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); gix.setFont(font); } catch (Exception e) { e.printStackTrace(); } UI.put("OptionPane.messageFont", new Font("Volter (Goldfish)", Font.BOLD, 14)); requestFocus(); // Init keys addKeyListener(new KeyInputHandler()); //initPlayer(); characterSelect(); Graphics2D gi = (Graphics2D) properties.strategy.getDrawGraphics(); gi.setColor(Color.red); gi.setFont(new Font("Volter (Goldfish)", Font.BOLD + Font.ITALIC, Utils.splashFS)); gi.drawString(Utils.txtLoad, (500 - gi.getFontMetrics().stringWidth(Utils.txtLoad)) / 2, 248); properties.strategy.show(); gi.dispose(); } /** * Create our ship */ private void initPlayer() { if (properties.shipS == 0) { properties.ship = new Player(this, "sprites/ship.png", 220, 568); properties.entities.add(properties.ship); } if (properties.shipS == 1) { properties.ship = new Player(this, "sprites/ship2.png", 220, 568); properties.entities.add(properties.ship); } if (properties.shipS == 2) { properties.ship = new Player(this, "sprites/ship3.png", 220, 568); properties.entities.add(properties.ship); } } private void updateEnt() { properties.moveSpeed = 180 + (properties.tWait * 0.7); properties.spriteLoc = properties.rSpriteLoc.nextInt(200); properties.spriteLoc2 = 200 + properties.rSpriteLoc.nextInt(250); if (properties.spriteLoc2 < properties.spriteLoc + 63) { if (properties.spriteLoc2 > properties.spriteLoc - 63) { properties.spriteLoc2 = properties.spriteLoc - 63; if (properties.spriteLoc2 > 450) properties.spriteLoc2 = properties.spriteLoc - 63; } } if (properties.usedPack == false) { if (properties.gameLives < 3) { int check = properties.rSpriteLoc.nextInt(10000); int rPackLoc = properties.rSpriteLoc.nextInt(450); if (check == 59) { properties.Pack = new Pack(this, "sprites/astronaut.png", rPackLoc, -50); properties.packList.add(properties.Pack); properties.usedPack = true; if (properties.Pack != null) { properties.Pack.setVerticalMovement(100); } } } } else { if (properties.pack == false) { Entity shipe = (Entity) properties.entities.get(0); for (int i = 0; i < properties.packList.size(); i++) { Pack packe = (Pack) properties.packList.get(1); if (shipe.collidesWith(packe)) { shipe.collidedWith(packe); packe.collidedWith(shipe); properties.packList.remove(1); } } } } if (properties.tWait != properties.gameTime) { int FinalLoc; if (properties.gameTime >= properties.tWait + 2 && properties.advanceLevel == false) { properties.tWait = properties.gameTime; for (int i = 0; i < 2; i++) { if (i == 0) { FinalLoc = properties.spriteLoc; } else { FinalLoc = properties.spriteLoc2; } Entity Enemies = new Enemy(this, "sprites/enemies/0" + properties.curSprite + ".png", FinalLoc, -50); properties.entities.add(Enemies); properties.curSprite += 1; if (properties.curSprite > 5) properties.curSprite = 1; } } else if (properties.advanceLevel == true) { if (properties.gameTime >= properties.tWait + 2 && properties.level == 2) { properties.tWait = properties.gameTime; for (int i = 0; i < 2; i++) { if (i == 0) { FinalLoc = properties.spriteLoc; } else { FinalLoc = properties.spriteLoc2; } Entity Enemies = new Enemy(this, "sprites/enemies/0" + properties.curSprite + ".png", FinalLoc, -50, (properties.tWait + (100 * 0.45) - 30)); properties.entities.add(Enemies); properties.curSprite += 1; if (properties.curSprite > 5) properties.curSprite = 1; } } else if (properties.gameTime >= properties.tWait && properties.level == 3) { properties.tWait = properties.gameTime; for (int i = 0; i < 2; i++) { if (i == 0) { FinalLoc = properties.spriteLoc; } else { FinalLoc = properties.spriteLoc2; } Entity Enemies = new Enemy(this, "sprites/enemies/0" + properties.curSprite + ".png", FinalLoc, -50, (properties.tWait + (100 * 0.45) - 30)); properties.entities.add(Enemies); properties.curSprite += 1; if (properties.curSprite > 5) properties.curSprite = 1; } } else if (properties.gameTime >= properties.tWait && properties.level == 4) { properties.tWait = properties.gameTime; for (int i = 0; i < 2; i++) { if (i == 0) { FinalLoc = properties.spriteLoc; } else { FinalLoc = properties.spriteLoc2; } Entity Enemies = new Enemy(this, "sprites/enemies/0" + properties.curSprite + ".png", FinalLoc, -50, (150 + (115 * 0.45) - 30)); properties.entities.add(Enemies); properties.curSprite += 1; if (properties.curSprite > 5) properties.curSprite = 1; } } else if (properties.gameTime >= properties.tWait && properties.level == 5) { properties.tWait = properties.gameTime; for (int i = 0; i < 2; i++) { if (i == 0) { FinalLoc = properties.spriteLoc; } else { FinalLoc = properties.spriteLoc2; } Entity Enemies = new Enemy(this, "sprites/enemies/0" + properties.curSprite + ".png", FinalLoc, -50, (115 + (100 * 0.45) - 30)); properties.entities.add(Enemies); properties.curSprite += 1; if (properties.curSprite > 5) properties.curSprite = 1; } } } } } private void startGame() { properties.entities.clear(); properties.Background = new Background(this, "sprites/background.png", 0, 0); properties.backgroundImages.add(properties.Background); properties.Background2 = new Background(this, "sprites/background.png", 0, -650); properties.backgroundImages.add(properties.Background2); properties.Pack = new Pack(this, "sprites/crate.png", 5, 628); properties.packList.add(properties.Pack); initPlayer(); // reset key presses properties.leftPressed = false; properties.rightPressed = false; //reset time properties.timeMil = 0; //reset lives GProperties.gameLives = 3; properties.level = 1; properties.gameStart = true; properties.advanceLevel = false; properties.tWait = 0; properties.gameTime = 0; properties.finalTime = 0; properties.lastLoopTime = System.currentTimeMillis(); properties.firing = false; properties.curWeapon = 1; properties.weapon = 1; GProperties.debugHits = 0; Sound.soundTheme1.play(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //get current date time with Date() Date date = new Date(); if (GProperties.debug) { System.out.println("============================================="); System.out.println("Beginning session @ " + dateFormat.format(date)); System.out.println("============================================="); } } public void characterSelect() { database.dbConnect(); ImageIcon ship1 = new ImageIcon(Utils.ship1URL); ImageIcon ship2 = new ImageIcon(Utils.ship2URL); ImageIcon ship3 = new ImageIcon(Utils.ship3URL); Utils.systemLF(); // properties.shipS = 0; startGame(); } public void gameOver() { Sound.soundTheme1.stop(); Sound.soundShoot.stop(); Sound.soundGameOver.play(); new GProperties().propertiesFile(); try { new Database().dbUpdateScore(); } catch (Exception e) { e.printStackTrace(); } try { new Database().dbUpdateAchievements(); } catch (Exception e) { e.printStackTrace(); } if (GProperties.debug) { System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("GAME OVER DISPLAYED AFTER " + properties.gameTime + " SECONDS"); System.out.println("HITS:" + GProperties.debugHits + "/3" + " | " + "LEVEL: " + properties.level); } //Game over display Graphics2D g2 = (Graphics2D) properties.strategy.getDrawGraphics(); g2.setColor(Color.RED); g2.setFont(new Font("Volter (Goldfish)", Font.BOLD, 32)); g2.drawString(Utils.txtGO, (500 - g2.getFontMetrics().stringWidth(Utils.txtGO)) / 2, 80); g2.setColor(Color.WHITE); g2.setFont(new Font("Volter (Goldfish)", Font.BOLD, 33)); g2.drawString(Utils.txtGO, (500 - g2.getFontMetrics().stringWidth(Utils.txtGO)) / 2, 80); properties.strategy.show(); g2.dispose(); ImageIcon icon = new ImageIcon(Utils.iconURL); Utils.systemLF(); Object[] options = {Utils.bPlayAgain, Utils.bHs, Utils.bQuit}; int goG = JOptionPane.showOptionDialog(null, Utils.txtTravelled + properties.gameTime + Utils.txtMetre, Utils.goDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]); if (goG != 0 && goG != 1 && goG != 2) { Utils.quitGame(); } if (goG == 1) { int openWebsite; openWebsite = JOptionPane.showConfirmDialog(null, Utils.txtHighscoreMsg, Utils.txtWebsite,JOptionPane.YES_NO_OPTION); if (openWebsite == 0) { try { String url = "http://the-dreamteam.co.uk/highscores.php"; java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); characterSelect(); } catch (java.io.IOException e) { System.out.println(e.getMessage()); } } } if (goG == 2) { System.exit(0); } if (goG == 0) { characterSelect(); } } public void pauseGame() { ImageIcon icon = new ImageIcon(Utils.iconURL); Utils.systemLF(); properties.gameStart = false; Sound.soundTheme1.stop(); Sound.soundShoot.stop(); long LoopTempTime = System.currentTimeMillis(); Object[] options = {Utils.bReturn, Utils.bRestart, Utils.bQuit}; int pauseG = JOptionPane.showOptionDialog(null, Utils.txtPS, Utils.tsDialogTitle, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]); double[] entCurYLoc = new double[properties.entities.size()]; for (int i = 0; i < properties.entities.size(); i++) { Entity entity = (Entity) properties.entities.get(i); entCurYLoc[i] = entity.getVerticalMovement(); entity.setVerticalMovement(0); } if (pauseG != 1 && pauseG != 2) { for (int i = 0; i < properties.entities.size(); i++) { Entity entity = (Entity) properties.entities.get(i); entity.setVerticalMovement(entCurYLoc[i]); } properties.finalTime = System.currentTimeMillis() - LoopTempTime; properties.gameStart = true; Sound.soundTheme1.play(); } if (pauseG == 2) { System.exit(0); } if (pauseG == 1) { properties.gameTime = 0; characterSelect(); } } public void gameLoop() { properties.lastLoopTime = System.currentTimeMillis(); long bgLoop = System.currentTimeMillis(); System.out.println("DEBUG: [INFO] USERNAME: " + properties.username); while (properties.Running) { if (properties.gameStart == true && properties.release == true) { long delta = (System.currentTimeMillis() - properties.finalTime) - properties.lastLoopTime; properties.finalTime = 0; properties.lastLoopTime = System.currentTimeMillis(); properties.lastTime = getTime(); updateTime(); // Colour in background Graphics2D g = (Graphics2D) properties.strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0, 0, 500, 650); for (int i = 0; i < properties.backgroundImages.size(); i++) { Entity entity = (Entity) properties.backgroundImages.get(i); entity.move(delta); } for (int i = 0; i < properties.entities.size(); i++) { Entity entity = (Entity) properties.entities.get(i); entity.move(delta); } for (int i = 0; i < properties.packList.size(); i++) { Entity entity = (Entity) properties.packList.get(i); entity.move(delta); } long bgLoopCheck = System.currentTimeMillis(); for (int i = 1; i < 3; i++) { if (i == 2) { properties.Background2.setVerticalMovement(10); } else { properties.Background.setVerticalMovement(10); } if ((bgLoopCheck - bgLoop) > 63000) { properties.Background = new Background(this, "sprites/background.png", 0, -650); properties.backgroundImages.add(properties.Background); bgLoop = System.currentTimeMillis(); } } //testing for collision of player and enemy for (int p = 0; p < properties.entities.size(); p++) { for (int s = p + 1; s < properties.entities.size(); s++) { Entity me = (Entity) properties.entities.get(p); Entity him = (Entity) properties.entities.get(s); if (me.collidesWith(him)) { me.collidedWith(him); him.collidedWith(me); } } } properties.entities.removeAll(properties.removeList); properties.removeList.clear(); for (int i = 0; i < properties.backgroundImages.size(); i++) { Entity entity = (Entity) properties.backgroundImages.get(i); entity.draw(g); } for (int i = 0; i < properties.entities.size(); i++) { Entity entity = (Entity) properties.entities.get(i); entity.draw(g); } for (int i = 0; i < properties.packList.size(); i++) { Entity entity = (Entity) properties.packList.get(i); entity.draw(g); } if (properties.gameTime > 59) { properties.advanceLevel = true; if (properties.gameTime < 119) { properties.level = 2; } else if (properties.gameTime < 179) { properties.level = 3; } else if (properties.gameTime < 239) { properties.level = 4; } else if (properties.gameTime >= 240) { properties.level = 5; } } /* * Game Text */ //Level g.setColor(Color.RED); g.setFont(new Font("Volter (Goldfish)", Font.BOLD, Utils.levelFS)); g.drawString(Utils.txtLevel + properties.level, (500 - g.getFontMetrics().stringWidth(Utils.txtLevel + properties.level)) / 2, 18); // Distance g.setColor(Color.WHITE); g.setFont(new Font("Volter (Goldfish)", Font.BOLD, Utils.timeFS)); g.drawString(properties.timeDisplay, (125 - g.getFontMetrics().stringWidth(properties.timeDisplay)) / 2, 18); g.drawString(Utils.txtTime, (125 - g.getFontMetrics().stringWidth(Utils.txtTime)) / 2, 18); if (properties.timeMil > 99) { properties.gameTime = properties.timeMil / 100; } String convtime = String.valueOf(properties.gameTime * 10); g.setColor(Color.ORANGE); g.setFont(new Font("Volter (Goldfish)", Font.ITALIC, Utils.timeIFS)); g.drawString(properties.timeDisplay, (275 - g.getFontMetrics().stringWidth(properties.timeDisplay)) / 2, 18); g.drawString(convtime, (275 - g.getFontMetrics().stringWidth(convtime)) / 2, 18); //Lives g.setColor(Color.WHITE); g.setFont(new Font("Volter (Goldfish)", Font.BOLD, Utils.livesFS)); g.drawString(properties.livesDisplay, (870 - g.getFontMetrics().stringWidth(properties.livesDisplay)) / 2, 18); g.drawString(Utils.txtLives, (870 - g.getFontMetrics().stringWidth(Utils.txtLives)) / 2, 18); String convlives = String.valueOf(GProperties.gameLives); g.setColor(Color.ORANGE); g.setFont(new Font("Volter (Goldfish)", Font.ITALIC, Utils.livesIFS)); g.drawString(properties.timeDisplay, (965 - g.getFontMetrics().stringWidth(properties.timeDisplay)) / 2, 18); g.drawString(convlives, (965 - g.getFontMetrics().stringWidth(convlives)) / 2, 18); //Weapon if (properties.curWeapon == 1) { g.setColor(Color.ORANGE); g.setFont(new Font("Volter (Goldfish)", Font.BOLD, Utils.weaponIFS)); g.drawString(String.valueOf(properties.weapon), (85 - g.getFontMetrics().stringWidth(String.valueOf(properties.weapon))) / 2, 647); } else { g.setColor(Color.WHITE); g.setFont(new Font("Volter (Goldfish)", Font.PLAIN, Utils.weaponIFS)); g.drawString(String.valueOf(properties.weapon), (85 - g.getFontMetrics().stringWidth(String.valueOf(properties.weapon))) / 2, 647); } // Clear Graphics g.dispose(); properties.strategy.show(); updateEnt(); if (GProperties.gameLives == 0) { gameOver(); } properties.ship.setHorizontalMovement(0); // Ship movement if ((properties.leftPressed) && (!properties.rightPressed)) { properties.ship.setHorizontalMovement(-properties.moveSpeed); } else if ((properties.rightPressed) && (!properties.leftPressed)) { properties.ship.setHorizontalMovement(properties.moveSpeed); } if (properties.firing && properties.weapon > 0) { if (properties.curWeapon == 1) { useWeapon(); properties.weaponLoopTime = System.currentTimeMillis(); properties.weapon = 0; } if (properties.curWeapon != 1) { properties.firing = false; } } else if (properties.firing && System.currentTimeMillis() < properties.weaponLoopTime + 4421) { useWeapon(); } else { if (System.currentTimeMillis() > properties.weaponLoopTime + 4421) { properties.firing = false; } } properties.weaponPressed = false; try { Thread.sleep(10); } catch (Exception e) { } } else { try { Thread.sleep(10); } catch (Exception e) { } } } } public void useWeapon() { if (properties.curWeapon == 1) { if (System.currentTimeMillis() - properties.lastFire < properties.timeBetweenShots) { return; } properties.lastFire = System.currentTimeMillis(); if (properties.shipS == 0) { Weapon shot = new Weapon(this, "sprites/Shot1.png", properties.ship.getX() + 13, properties.ship.getY() - 15); properties.entities.add(shot); Weapon shot2 = new Weapon(this, "sprites/Shot1.png", properties.ship.getX() + 23, properties.ship.getY() - 15); properties.entities.add(shot2); } else if (properties.shipS == 1) { Weapon shot = new Weapon(this, "sprites/Shot2.png", properties.ship.getX() + 0, properties.ship.getY() - -12); properties.entities.add(shot); Weapon shot2 = new Weapon(this, "sprites/Shot2.png", properties.ship.getX() + 35, properties.ship.getY() - -12); properties.entities.add(shot2); } else if (properties.shipS == 2) { Weapon shot = new Weapon(this, "sprites/Shot3.png", properties.ship.getX() + 0, properties.ship.getY() - 15); properties.entities.add(shot); Weapon shot2 = new Weapon(this, "sprites/Shot3.png", properties.ship.getX() + 37, properties.ship.getY() - 15); properties.entities.add(shot2); } Sound.soundShoot.play(); } } /** * Update the game time */ public void updateTime() { if (getTime() - properties.lastTime > 1000) { properties.timeMil = 0; //reset the timer counter properties.lastTime += 1000; //add one second } properties.timeMil++; } public long getTime() { return ((System.nanoTime() / 1000000) + 552); } public int getDelta() { long time = getTime(); int delta = (int) (time - properties.lastFrame); properties.lastFrame = time; return delta; } public void removeEntity(Entity entity) { properties.removeList.add(entity); } private class KeyInputHandler extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) { properties.leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) { properties.rightPressed = true; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { properties.firing = true; properties.weaponPressed = true; } if (e.getKeyChar() == 27 || e.getKeyCode() == KeyEvent.VK_PAUSE || e.getKeyCode() == KeyEvent.VK_P) { pauseGame(); } if (properties.debug) { if (e.getKeyCode() == KeyEvent.VK_F7) { properties.advanceLevel = true; properties.timeMil = 18000; for (int r = 0; r < properties.entities.size(); r++) { properties.removeList.add(properties.entities.get(r)); } initPlayer(); } } if (properties.debug) { if (e.getKeyCode() == KeyEvent.VK_F6) { GProperties.gameLives = 0; } } if (properties.debug) { if (e.getKeyCode() == KeyEvent.VK_F8) { database.dbReset(); } } } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) { properties.leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) { properties.rightPressed = false; } } } public static void main(String argv[]) { // Ensure that database exists, if not, create it. File f = new File("./SSA.db"); if(!f.exists() && !f.isDirectory()) { System.out.println("DEBUG: [WARNING] Database does not exist, recreating it"); InputStream stream = me.dreamteam.tardis.Game.class.getResourceAsStream("/data/SSA.db"); if (stream == null) { } OutputStream resStreamOut = null; int readBytes; byte[] buffer = new byte[4096]; try { resStreamOut = new FileOutputStream(new File("./SSA.db")); while ((readBytes = stream.read(buffer)) > 0) { resStreamOut.write(buffer, 0, readBytes); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { stream.close(); resStreamOut.close(); } catch (IOException e) { e.printStackTrace(); } } } new GUI().setVisible(true); Game g = new Game(); g.gameLoop(); } }
package me.pagar.model; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import me.pagar.util.JSONUtils; import org.joda.time.DateTime; import javax.ws.rs.HttpMethod; import java.util.Collection; public class Recipient extends PagarMeModel<String> { @Expose @SerializedName(value = "automatic_anticipation_enabled") private Boolean automaticAnticipationEnabled; @Expose @SerializedName(value = "transfer_enabled") private Boolean transferEnabled; @Expose(serialize = false) @SerializedName(value = "anticipatable_volume_percentage") private Integer anticipatableVolumePercentage; @Expose @SerializedName(value = "transfer_day") private Integer transferDay; @Expose(deserialize = false) @SerializedName(value = "bank_account_id") private Integer bankAccountId; @Expose @SerializedName(value = "bank_account") private BankAccount bankAccount; @Expose @SerializedName(value = "transfer_interval") private TransferInterval transferInterval; @Expose(serialize = false) @SerializedName(value = "lastTransfer") private DateTime lastTransfer; @Expose(serialize = false) @SerializedName("date_updated") private DateTime updatedAt; public Boolean isAutomaticAnticipationEnabled() { return automaticAnticipationEnabled; } public Boolean isTransferEnabled() { return transferEnabled; } public Integer getAnticipatableVolumePercentage() { return anticipatableVolumePercentage; } public Integer getTransferDay() { return transferDay; } public BankAccount getBankAccount() { return bankAccount; } public TransferInterval getTransferInterval() { return transferInterval; } public DateTime getLastTransfer() { return lastTransfer; } public DateTime getUpdatedAt() { return updatedAt; } public Boolean getAutomaticAnticipationEnabled() { return automaticAnticipationEnabled; } public void setAutomaticAnticipationEnabled(Boolean automaticAnticipationEnabled) { this.automaticAnticipationEnabled = automaticAnticipationEnabled; addUnsavedProperty("automatic_anticipation_enabled"); } public void setTransferEnabled(Boolean transferEnabled) { this.transferEnabled = transferEnabled; addUnsavedProperty("transferEnabled"); } public void setTransferDay(Integer transferDay) { this.transferDay = transferDay; addUnsavedProperty("transferDay"); } public void setBankAccountId(Integer bankAccountId) { this.bankAccountId = bankAccountId; addUnsavedProperty("bankAccountId"); } public void setBankAccount(BankAccount bankAccount) { this.bankAccount = bankAccount; addUnsavedProperty("bankAccount"); } public void setTransferInterval(TransferInterval transferInterval) { this.transferInterval = transferInterval; addUnsavedProperty("transferInterval"); } public Recipient save() throws PagarMeException { final Recipient saved = super.save(getClass()); copy(saved); return saved; } public Recipient find(String id) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), id)); final Recipient other = JSONUtils.getAsObject((JsonObject) request.execute(), Recipient.class); copy(other); flush(); return other; } public Collection<Recipient> findCollection(int totalPerPage, int page) throws PagarMeException { return JSONUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken<Collection<Recipient>>() { }.getType()); } public Balance balance() throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), Balance.class.getSimpleName().toLowerCase())); return JSONUtils.getAsObject((JsonObject) request.execute(), Balance.class); } public Recipient refresh() throws PagarMeException { final Recipient other = JSONUtils.getAsObject(refreshModel(), Recipient.class); copy(other); flush(); return other; } private void copy(Recipient other) { super.copy(other); this.automaticAnticipationEnabled = other.automaticAnticipationEnabled; this.transferEnabled = other.transferEnabled; this.transferDay = other.transferDay; this.anticipatableVolumePercentage = other.anticipatableVolumePercentage; this.lastTransfer = other.lastTransfer; this.transferInterval = other.transferInterval; this.updatedAt = other.updatedAt; this.bankAccount = other.bankAccount; } public enum TransferInterval { @SerializedName("daily") DAILY, @SerializedName("weekly") WEEKLY, @SerializedName("monthly") MONTHLY } }
package mjc.translate; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import com.google.common.primitives.Booleans; import mjc.analysis.AnalysisAdapter; import mjc.frame.Access; import mjc.frame.Factory; import mjc.frame.Frame; import mjc.node.AAndExpression; import mjc.node.AArrayAccessExpression; import mjc.node.AArrayAssignStatement; import mjc.node.AArrayLengthExpression; import mjc.node.AAssignStatement; import mjc.node.ABlockStatement; import mjc.node.AClassDeclaration; import mjc.node.AEqualExpression; import mjc.node.AFalseExpression; import mjc.node.AFieldDeclaration; import mjc.node.AFormalParameter; import mjc.node.AGreaterEqualThanExpression; import mjc.node.AGreaterThanExpression; import mjc.node.AIdentifierExpression; import mjc.node.AIfElseStatement; import mjc.node.AIfStatement; import mjc.node.AIntegerExpression; import mjc.node.ALessEqualThanExpression; import mjc.node.ALessThanExpression; import mjc.node.ALongExpression; import mjc.node.AMainClassDeclaration; import mjc.node.AMethodDeclaration; import mjc.node.AMethodInvocationExpression; import mjc.node.AMinusExpression; import mjc.node.ANewInstanceExpression; import mjc.node.ANewIntArrayExpression; import mjc.node.ANewLongArrayExpression; import mjc.node.ANotEqualExpression; import mjc.node.ANotExpression; import mjc.node.AOrExpression; import mjc.node.APlusExpression; import mjc.node.APrintlnStatement; import mjc.node.AProgram; import mjc.node.AThisExpression; import mjc.node.ATimesExpression; import mjc.node.ATrueExpression; import mjc.node.AVariableDeclaration; import mjc.node.AWhileStatement; import mjc.node.Node; import mjc.node.PClassDeclaration; import mjc.node.PFieldDeclaration; import mjc.node.PMethodDeclaration; import mjc.node.Start; import mjc.node.TIdentifier; import mjc.symbol.ClassInfo; import mjc.symbol.MethodInfo; import mjc.symbol.SymbolTable; import mjc.symbol.VariableInfo; import mjc.temp.Label; import mjc.tree.BINOP; import mjc.tree.CJUMP; import mjc.tree.CONST; import mjc.tree.DCONST; import mjc.tree.Exp; import mjc.tree.ExpList; import mjc.tree.LABEL; import mjc.tree.MOVE; import mjc.tree.SEQ; import mjc.tree.TEMP; import mjc.tree.View; public class Translator extends AnalysisAdapter { private SymbolTable symbolTable; private Factory factory; private ClassInfo currentClass; private MethodInfo currentMethod; private Frame currentFrame; private Translation currentTree; private List<ProcFrag> fragments; /** * Translates the given AST into IR and returns the result as a list of procedure fragments. * * @param ast Input AST. * @param symbolTable Symbol table for the input program. * @param factory Factory for constructing frames and records. * @return List of procedure fragments. */ public List<ProcFrag> translate(final Node ast, final SymbolTable symbolTable, final Factory factory) { this.symbolTable = symbolTable; this.factory = factory; fragments = new ArrayList<>(); ast.apply(this); return fragments; } /** * Translates the given AST node into IR and returns the result. * * Note: The {@link #currentTree} field will be set to null. * * @param astNode input AST node. * @return IR representation of @a astNode. */ private Translation treeOf(final Node astNode) { astNode.apply(this); final Translation result = this.currentTree; this.currentTree = null; return result; } @Override public void caseStart(final Start start) { start.getPProgram().apply(this); } @Override public void caseAProgram(final AProgram program) { program.getMainClassDeclaration().apply(this); for (PClassDeclaration classDeclaration : program.getClasses()) { classDeclaration.apply(this); } } @Override public void caseAMainClassDeclaration(final AMainClassDeclaration declaration) { currentClass = symbolTable.getClassInfo(declaration.getName().getText()); currentMethod = currentClass.getMethod(declaration.getMethodName().getText()); currentMethod.enterBlock(); currentFrame = factory.newFrame( new Label(currentClass.getName() + '$' + currentMethod.getName()), new ArrayList<Boolean>() ); final LinkedList<Node> nodes = new LinkedList<>(); nodes.addAll(declaration.getLocals()); nodes.addAll(declaration.getStatements()); Translation tree = buildStm(nodes); if (tree != null) { currentTree = tree; View viewer = new View("if-else"); viewer.addStm(currentTree.asStm()); viewer.expandTree(); fragments.add(new ProcFrag(currentFrame.procEntryExit1(currentTree.asStm()), currentFrame)); } currentFrame = null; currentMethod.leaveBlock(); currentMethod = null; currentClass = null; } @Override public void caseAClassDeclaration(final AClassDeclaration declaration) { currentClass = symbolTable.getClassInfo(declaration.getName().getText()); for (PFieldDeclaration fieldDeclaration : declaration.getFields()) { fieldDeclaration.apply(this); } for (PMethodDeclaration methodDeclaration : declaration.getMethods()) { methodDeclaration.apply(this); } currentClass = null; } @Override public void caseAMethodDeclaration(final AMethodDeclaration declaration) { currentMethod = currentClass.getMethod(declaration.getName().getText()); currentMethod.enterBlock(); currentFrame = factory.newFrame( new Label(currentClass.getName() + '$' + currentMethod.getName()), Booleans.asList(new boolean[currentMethod.getParameters().size()]) ); final LinkedList<Node> nodes = new LinkedList<>(); nodes.addAll(declaration.getFormals()); nodes.addAll(declaration.getLocals()); nodes.addAll(declaration.getStatements()); nodes.add(declaration.getReturnExpression()); Translation tree = buildStm(nodes); if (tree != null) { currentTree = tree; fragments.add(new ProcFrag(currentFrame.procEntryExit1(currentTree.asStm()), currentFrame)); } currentFrame = null; currentMethod.leaveBlock(); currentMethod = null; } @Override public void caseAFieldDeclaration(final AFieldDeclaration declaration) { // TODO currentTree = new TODO(); } @Override public void caseAFormalParameter(final AFormalParameter declaration) { final VariableInfo variableInfo = currentMethod.getLocal(declaration.getName().getText()); final Access access = currentFrame.allocLocal(false); variableInfo.setAccess(access); currentTree = new Expression(access.exp(new TEMP(currentFrame.FP()))); } @Override public void caseAVariableDeclaration(final AVariableDeclaration declaration) { final VariableInfo variableInfo = currentMethod.getLocal(declaration.getName().getText()); final Access access = currentFrame.allocLocal(false); variableInfo.setAccess(access); currentTree = new Expression(access.exp(new TEMP(currentFrame.FP()))); } @Override public void caseABlockStatement(final ABlockStatement block) { currentMethod.enterBlock(); final LinkedList<Node> nodes = new LinkedList<>(); nodes.addAll(block.getLocals()); nodes.addAll(block.getStatements()); Translation tree = buildStm(nodes); if (tree != null) currentTree = tree; currentMethod.leaveBlock(); } @Override public void caseAIfStatement(final AIfStatement statement) { currentTree = new If( treeOf(statement.getCondition()), treeOf(statement.getStatement()) ); } @Override public void caseAIfElseStatement(final AIfElseStatement statement) { currentTree = new IfElse( treeOf(statement.getCondition()), treeOf(statement.getThen()), treeOf(statement.getElse()) ); } @Override public void caseAWhileStatement(final AWhileStatement statement) { final Label test = new Label(); final Label trueLabel = new Label(); final Label falseLabel = new Label(); currentTree = new Statement( new SEQ(new LABEL(test), new SEQ(treeOf(statement.getCondition()).asCond(trueLabel, falseLabel), new SEQ(new LABEL(trueLabel), new SEQ(treeOf(statement.getStatement()).asStm(), new LABEL(falseLabel)))))); } @Override public void caseAPrintlnStatement(final APrintlnStatement statement) { currentTree = new Expression( currentFrame.externalCall("_minijavalib_println", new ExpList(treeOf(statement.getValue()).asExp()))); } @Override public void caseAAssignStatement(final AAssignStatement statement) { currentTree = new Statement( new MOVE(getVariable(statement.getName()), treeOf(statement.getValue()).asExp())); } @Override public void caseAArrayAssignStatement(final AArrayAssignStatement statement) { currentTree = new Statement( new MOVE(new BINOP( BINOP.PLUS, getVariable(statement.getName()), treeOf(statement.getIndex()).asExp()), treeOf(statement.getValue()).asExp())); } @Override public void caseAAndExpression(final AAndExpression expression) { // TODO currentTree = new TODO(); } @Override public void caseAOrExpression(final AOrExpression expression) { // TODO currentTree = new TODO(); } @Override public void caseALessThanExpression(final ALessThanExpression expression) { currentTree = new RelationalCondition( CJUMP.LT, treeOf(expression.getLeft()), treeOf(expression.getRight())); } @Override public void caseAGreaterThanExpression(final AGreaterThanExpression expression) { currentTree = new RelationalCondition( CJUMP.GT, treeOf(expression.getLeft()), treeOf(expression.getRight())); } @Override public void caseAGreaterEqualThanExpression(final AGreaterEqualThanExpression expression) { currentTree = new RelationalCondition( CJUMP.GE, treeOf(expression.getLeft()), treeOf(expression.getRight())); } @Override public void caseALessEqualThanExpression(final ALessEqualThanExpression expression) { currentTree = new RelationalCondition( CJUMP.LE, treeOf(expression.getLeft()), treeOf(expression.getRight())); } @Override public void caseAEqualExpression(final AEqualExpression expression) { currentTree = new RelationalCondition( CJUMP.EQ, treeOf(expression.getLeft()), treeOf(expression.getRight())); } @Override public void caseANotEqualExpression(final ANotEqualExpression expression) { currentTree = new RelationalCondition( CJUMP.NE, treeOf(expression.getLeft()), treeOf(expression.getRight())); } @Override public void caseAPlusExpression(final APlusExpression expression) { currentTree = new Expression(new BINOP(BINOP.PLUS, treeOf(expression.getLeft()).asExp(), treeOf(expression.getRight()).asExp())); } @Override public void caseAMinusExpression(final AMinusExpression expression) { currentTree = new Expression(new BINOP(BINOP.MINUS, treeOf(expression.getLeft()).asExp(), treeOf(expression.getRight()).asExp())); } @Override public void caseATimesExpression(final ATimesExpression expression) { currentTree = new Expression(new BINOP(BINOP.MUL, treeOf(expression.getLeft()).asExp(), treeOf(expression.getRight()).asExp())); } @Override public void caseANotExpression(final ANotExpression expression) { currentTree = new Expression(new BINOP( BINOP.MINUS, new CONST(1), treeOf(expression.getExpression()).asExp())); } @Override public void caseAMethodInvocationExpression(final AMethodInvocationExpression expression) { // TODO currentTree = new TODO(); } @Override public void caseAArrayAccessExpression(final AArrayAccessExpression expression) { // TODO currentTree = new TODO(); } @Override public void caseAArrayLengthExpression(final AArrayLengthExpression expression) { // TODO currentTree = new TODO(); } @Override public void caseANewInstanceExpression(final ANewInstanceExpression expression) { // TODO currentTree = new TODO(); } @Override public void caseANewIntArrayExpression(final ANewIntArrayExpression expression) { // TODO currentTree = new TODO(); } @Override public void caseANewLongArrayExpression(final ANewLongArrayExpression expression) { // TODO currentTree = new TODO(); } @Override public void caseAIntegerExpression(final AIntegerExpression expression) { currentTree = new Expression( new CONST(Integer.parseInt(expression.getInteger().getText()))); } @Override public void caseALongExpression(final ALongExpression expression) { final String literal = expression.getLong().getText(); currentTree = new Expression( new DCONST(Long.parseLong(literal.substring(0, literal.length() - 1)))); // Strip 'L'/'l'. } @Override public void caseATrueExpression(final ATrueExpression expression) { currentTree = new Expression(new CONST(1)); } @Override public void caseAFalseExpression(final AFalseExpression expression) { currentTree = new Expression(new CONST(0)); } @Override public void caseAIdentifierExpression(final AIdentifierExpression expression) { // TODO currentTree = new TODO(); } @Override public void caseAThisExpression(final AThisExpression expression) { // TODO currentTree = new TODO(); } private Exp getVariable(TIdentifier id) { final String name = id.getText(); final VariableInfo localInfo, paramInfo, fieldInfo; if ((localInfo = currentMethod.getLocal(name)) != null) { return localInfo.getAccess().exp(new TEMP(currentFrame.FP())); } else if ((paramInfo = currentMethod.getParameter(name)) != null) { return null; } else if ((fieldInfo = currentClass.getField(name)) != null) { return null; } else { throw new Error("No such symbol: " + name); } } private Translation buildStm(LinkedList<Node> statements) { if (statements.isEmpty()) return null; if (statements.size() == 1) return treeOf(statements.get(0)); final Iterator<Node> it = statements.iterator(); SEQ result = new SEQ(treeOf(it.next()).asStm(), null); SEQ current = result; while (it.hasNext()) { Node next = it.next(); if (it.hasNext()) { current.right = new SEQ(treeOf(next).asStm(), null); current = (SEQ) current.right; } else { current.right = treeOf(next).asStm(); } } return new Statement(result); } }
package mm.structures; import java.util.Arrays; import java.util.Random; /** * Square matrix (n x n) of m (colorCount) colors. */ public class ColorField extends Matrix { // private static final Random r = new Random("VojnaBarv".hashCode()); private int n, colorCount; private int[][] neighbourMask; private int[] neighbourLengths; private ColorPixel[] colors; private Random r; /** * Initialize mm.structures.ColorField as n x n matrix using given colors array as colors. * * @param n - Dimension of matrix. * @param colors - Colors to be used in field. */ public ColorField(int n, ColorPixel[] colors) { super(n); init(colors, true); } private ColorField(int n, ColorPixel[] colors, int[][] neighbourMask, int[] neighbourLengths) { super(n); this.neighbourMask = neighbourMask; this.neighbourLengths = neighbourLengths; init(colors, false); } /** * Initialize mm.structures.ColorField as n x n matrix using given colors array as colors. * * @param array - Array representing the field matrix. * @param colors - Colors to be used in field. */ private ColorField(int[][] array, ColorPixel[] colors) { super(array); colors = colors != null ? colors : new ColorPixel[0]; init(colors, true); } /** * * @param n * @param colors * @param r - Random generator to be used (ex.: use same seed every time) * @return */ public static ColorField GenerateField(int n, ColorPixel[] colors, Random r) { int[] probabilityVector = ColorPixel.getProbabilityArray(colors); ColorPixel.resetAllColors(colors); ColorField cf = new ColorField(n, colors); for (int i = 0; i < cf.length; i++) { int index = probabilityVector[r.nextInt(probabilityVector.length)]; cf.colors[index].addCount(); cf.setElement(i, colors[index].getCode()); } return cf; } /** * Initialize colors array and color map (array of ints representing colors). * * @param colors - Colors to be used in field. */ private void init(ColorPixel[] colors, boolean calculateNeighbourMask) { this.r = new Random(); this.n = super.n; this.colors = colors; this.colorCount = colors.length; // Set codes for each color. for (int i = 0; i < colorCount; i++) { colors[i].setCode(i); } if (calculateNeighbourMask) { // Calculate neighbourMask array in advance, used to improve performance // compared to calculating indices for every `getNeighbours` lookup. neighbourMask = new int[super.length][8]; neighbourLengths = new int[super.length]; for (int i = 0, index = 0; i < m; i++) { for (int j = 0; j < n; j++, index++) { int ind = 0; for (int ii = i - 1; ii <= i + 1; ii++) { for (int jj = j - 1; jj <= j + 1; jj++) { if ((ii != i || jj != j) && (ii >= 0 && ii < m) && (jj >= 0 && jj < n)) { neighbourMask[index][ind++] = indexOf(ii, jj); } } } neighbourMask[index] = Arrays.copyOf(neighbourMask[index], ind); neighbourLengths[index] = ind; } } } } public int getN() { return n; } public int getColorCount() { return colorCount; } public ColorPixel[] getColors() { return colors; } /** * Find values of neighbours of (i, j). * * @param i - mm.structures.Matrix row. * @param j - mm.structures.Matrix column. * @return - Vector (1xn) (n = [1, 8]) of existent neighbours. */ public int[] getNeighbours(int i, int j) { return getNeighbours(indexOf(i, j)); } public int[] getNeighbours(int i) { int[] map = neighbourMask[i]; int[] neighbours = new int[map.length]; for (int ii = 0; ii < map.length; ii++) { neighbours[ii] = a[map[ii]]; } return neighbours; } private int[] getNextNeighbours() { int[] nextNeighbours = new int[length]; for (int i = 0; i < length; i++) { nextNeighbours[i] = r.nextInt(neighbourLengths[i]); } return nextNeighbours; } public ColorField updateNeighbours() { final Random r = new Random(); final ColorField cf = new ColorField(n, colors, neighbourMask, neighbourLengths); int[] nextNeighbours = getNextNeighbours(); ColorPixel.resetAllColors(colors); for (int i = 0; i < length; i++) { int newCode = getNeighbours(i)[nextNeighbours[i]]; this.colors[newCode].addCount(); cf.setElement(i, newCode); } return cf; } }
package mods.ocminecart; public class Settings { public static final String OC_ResLoc = "opencomputers"; // Resource domain for OpenComputers public static final String OC_Namespace = "oc:"; // Namespace for OpenComputers NBT Data public static final float OC_SoundVolume = li.cil.oc.Settings.get().soundVolume(); public static int ComputerCartBaseCost; //Config Value -> basecost public static int ComputerCartComplexityCost; //Config Value -> costmultiplier public static int ComputerCartEnergyCap; //Config Value -> energystore public static double ComputerCartEnergyUse; //Config Value -> energyuse public static int ComputerCartCreateEnergy; //Config Value -> newenergy public static double ComputerCartEngineUse; //Config Value -> engineuse public static int NetRailPowerTransfer; //Config Value -> transferspeed public static void init(){ OCMinecart.config.load(); OCMinecart.config.addCustomCategoryComment("computercart", "Some Settings for the computer cart"); ComputerCartBaseCost = OCMinecart.config.get("computercart", "basecost", 50000 , "Energy cost for a ComputerCart with Complexity 0 [default: 50000]").getInt(50000); ComputerCartComplexityCost = OCMinecart.config.get("computercart", "costmultiplier", 10000 , "Energy - Complexity multiplier [default: 10000]").getInt(10000); ComputerCartEnergyCap = OCMinecart.config.get("computercart", "energystore", 20000 , "Energy a Computer cart can store [default: 20000]").getInt(20000); ComputerCartEnergyUse = OCMinecart.config.get("computercart", "energyuse", 0.25 , "Energy a Computer cart consume every tick [default: 0.25]").getDouble(0.25); ComputerCartCreateEnergy= OCMinecart.config.get("computercart", "newenergy", 20000 , "Energy new a Computer cart has stored [default: 20000]").getInt(20000); ComputerCartEngineUse= OCMinecart.config.get("computercart", "newenergy", 2 , "Energy multiplier for the Engine. Speed times Value [default: 2]").getDouble(2); OCMinecart.config.addCustomCategoryComment("networkrail", "Some Settings for the network rail"); NetRailPowerTransfer= OCMinecart.config.get("networkrail", "transferspeed",100 , "Energy that a network rail can transfer per tick [default: 100]").getInt(100); OCMinecart.config.save(); } }
package ibis.ipl.impl.messagePassing; import ibis.ipl.IbisIOException; import ibis.ipl.impl.generic.ConditionVariable; public class ReadMessage implements ibis.ipl.ReadMessage, PollClient { long sequenceNr = -1; ReceivePort port; ShadowSendPort shadowSendPort; ByteInputStream in; int msgSeqno; ibis.ipl.impl.messagePassing.ReadMessage next; ReadFragment fragmentFront; ReadFragment fragmentTail; int sleepers = 0; ReadMessage(ibis.ipl.SendPort s, ReceivePort port) { // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockOwned(); this.port = port; this.shadowSendPort = (ShadowSendPort)s; in = this.shadowSendPort.in; } void enqueue(ReadFragment f) { if (fragmentFront == null) { fragmentFront = f; } else { fragmentTail.next = f; } fragmentTail = f; wakeup(); } void clear() { ReadFragment next; for (ReadFragment f = fragmentFront; f != null; f = next) { if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println("Now clear fragment " + f + " handle " + Integer.toHexString(f.msgHandle) + "; next " + f.next); } next = f.next; f.clear(); shadowSendPort.putFragment(f); } fragmentFront = null; } /* The PollClient interface */ boolean signalled; boolean accepted; ConditionVariable cv = ibis.ipl.impl.messagePassing.Ibis.myIbis.createCV(); PollClient poll_next; PollClient poll_prev; public PollClient next() { return poll_next; } public PollClient prev() { return poll_prev; } public void setNext(PollClient c) { poll_next = c; } public void setPrev(PollClient c) { poll_prev = c; } public boolean satisfied() { return fragmentFront.next != null; } public void wakeup() { if (sleepers != 0) { // System.err.println("Readmessage signalled"); cv.cv_signal(); } } public void poll_wait(long timeout) { // System.err.println("ReadMessage poll_wait"); sleepers++; cv.cv_wait(timeout); sleepers // System.err.println("ReadMessage woke up"); } Thread me; public Thread thread() { return me; } public void setThread(Thread thread) { me = thread; } /* End of the PollClient interface */ public void nextFragment() throws IbisIOException { // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockOwned(); while (fragmentFront.next == null) { ibis.ipl.impl.messagePassing.Ibis.myIbis.waitPolling(this, 0, Poll.PREEMPTIVE); } ReadFragment prev = fragmentFront; fragmentFront = fragmentFront.next; if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println("Now set msg " + this + " the next fragment " + Integer.toHexString(fragmentFront.msgHandle)); } in.setMsgHandle(this); prev.clear(); shadowSendPort.putFragment(prev); } public void finish() { ibis.ipl.impl.messagePassing.Ibis.myIbis.lock(); clear(); port.finishMessage(); ibis.ipl.impl.messagePassing.Ibis.myIbis.unlock(); } public ibis.ipl.SendPortIdentifier origin() { return shadowSendPort.identifier(); } void setSequenceNumber(long s) { sequenceNr = s; } public long sequenceNumber() { return sequenceNr; } public boolean readBoolean() throws IbisIOException { throw new IbisIOException("Read Boolean not supported"); } public byte readByte() throws IbisIOException { throw new IbisIOException("Read Byte not supported"); } public char readChar() throws IbisIOException { throw new IbisIOException("Read Char not supported"); } public short readShort() throws IbisIOException { throw new IbisIOException("Read Short not supported"); } public int readInt() throws IbisIOException { return in.read(); } public long readLong() throws IbisIOException { throw new IbisIOException("Read Long not supported"); } public float readFloat() throws IbisIOException { throw new IbisIOException("Read Float not supported"); } public double readDouble() throws IbisIOException { throw new IbisIOException("Read Double not supported"); } public String readString() throws IbisIOException { throw new IbisIOException("Read String not supported"); } public Object readObject() throws IbisIOException { throw new IbisIOException("Read Object not supported"); } public void readArrayBoolean(boolean[] destination) throws IbisIOException { throw new IbisIOException("Read ArrayBoolean not supported"); } public void readArrayByte(byte[] destination) throws IbisIOException { in.read(destination); } public void readArrayChar(char[] destination) throws IbisIOException { throw new IbisIOException("Read ArrayChar not supported"); } public void readArrayShort(short[] destination) throws IbisIOException { throw new IbisIOException("Read ArrayShort not supported"); } public void readArrayInt(int[] destination) throws IbisIOException { throw new IbisIOException("Read ArrayInt not supported"); } public void readArrayLong(long[] destination) throws IbisIOException { throw new IbisIOException("Read ArrayLong not supported"); } public void readArrayFloat(float[] destination) throws IbisIOException { throw new IbisIOException("Read ArrayFloat not supported"); } public void readArrayDouble(double[] destination) throws IbisIOException { throw new IbisIOException("Read ArrayDouble not supported"); } public void readSubArrayBoolean(boolean[] destination, int offset, int size) throws IbisIOException { throw new IbisIOException("Read SubArrayBoolean not supported"); } public void readSubArrayByte(byte[] destination, int offset, int size) throws IbisIOException { throw new IbisIOException("Read SubArrayByte not supported"); } public void readSubArrayChar(char[] destination, int offset, int size) throws IbisIOException { throw new IbisIOException("Read SubArrayChar not supported"); } public void readSubArrayShort(short[] destination, int offset, int size) throws IbisIOException { throw new IbisIOException("Read SubArrayShort not supported"); } public void readSubArrayInt(int[] destination, int offset, int size) throws IbisIOException { throw new IbisIOException("Read SubArrayInt not supported"); } public void readSubArrayLong(long[] destination, int offset, int size) throws IbisIOException { throw new IbisIOException("Read SubArrayLong not supported"); } public void readSubArrayFloat(float[] destination, int offset, int size) throws IbisIOException { throw new IbisIOException("Read SubArrayFloat not supported"); } public void readSubArrayDouble(double[] destination, int offset, int size) throws IbisIOException { throw new IbisIOException("Read SubArrayDouble not supported"); } }
package ibis.ipl.impl.messagePassing; import java.util.Vector; import ibis.ipl.IbisIOException; import ibis.ipl.impl.generic.ConditionVariable; class ReceivePort implements ibis.ipl.ReceivePort, Protocol, Runnable, PollClient { private static final boolean DEBUG = false; private static int livingPorts = 0; private static Syncer portCounter = new Syncer(); ibis.ipl.impl.messagePassing.PortType type; ReceivePortIdentifier ident; int connectCount = 0; String name; // needed to unbind ibis.ipl.impl.messagePassing.ReadMessage queueFront; ibis.ipl.impl.messagePassing.ReadMessage queueTail; ConditionVariable messageArrived = ibis.ipl.impl.messagePassing.Ibis.myIbis.createCV(); int arrivedWaiters = 0; boolean aMessageIsAlive = false; ConditionVariable messageHandled = ibis.ipl.impl.messagePassing.Ibis.myIbis.createCV(); int liveWaiters = 0; private ibis.ipl.impl.messagePassing.ReadMessage currentMessage = null; Thread thread; ibis.ipl.Upcall upcall; volatile boolean stop = false; private ibis.ipl.ConnectUpcall connectUpcall; private boolean allowConnections = false; private AcceptThread acceptThread; private boolean allowUpcalls = false; ConditionVariable enable = ibis.ipl.impl.messagePassing.Ibis.myIbis.createCV(); private int handlingReceive = 0; Vector connections = new Vector(); ConditionVariable disconnected = ibis.ipl.impl.messagePassing.Ibis.myIbis.createCV(); private long upcall_poll; // STATISTICS private int enqueued_msgs; private int upcall_msgs; private int dequeued_msgs; static { if (DEBUG) { System.err.println("Turn on ReceivePort.DEBUG"); } } ReceivePort(ibis.ipl.impl.messagePassing.PortType type, String name) throws IbisIOException { this(type, name, null, null); } ReceivePort(ibis.ipl.impl.messagePassing.PortType type, String name, ibis.ipl.Upcall upcall, ibis.ipl.ConnectUpcall connectUpcall) throws IbisIOException { this.type = type; this.name = name; this.upcall = upcall; this.connectUpcall = connectUpcall; ident = new ReceivePortIdentifier(name, type.name()); ibis.ipl.impl.messagePassing.Ibis.myIbis.lock(); livingPorts++; ibis.ipl.impl.messagePassing.Ibis.myIbis.unlock(); } private boolean firstCall = true; public synchronized void enableConnections() { System.err.println("Enable connections on " + this + " firstCall=" + firstCall); if (firstCall) { firstCall = false; if (upcall != null) { thread = new Thread(this); thread.start(); } if (connectUpcall != null) { acceptThread = new AcceptThread(this, connectUpcall); System.err.println("And start another AcceptThread(this=" + this + ")"); acceptThread.start(); } // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockNotOwned(); // System.err.println("In enableConnections: want to bind locally RPort " + this); // synchronized (ibis.ipl.impl.messagePassing.Ibis.myIbis) { ibis.ipl.impl.messagePassing.Ibis.myIbis.lock(); ibis.ipl.impl.messagePassing.Ibis.myIbis.bindReceivePort(this, ident.port); ibis.ipl.impl.messagePassing.Ibis.myIbis.unlock(); try { // System.err.println("In enableConnections: want to bind RPort " + this); ((Registry)ibis.ipl.impl.messagePassing.Ibis.myIbis.registry()).bind(name, ident); } catch (ibis.ipl.IbisIOException e) { System.err.println("registry bind of ReceivePortName fails: " + e); System.exit(4); } } allowConnections = true; } public synchronized void disableConnections() { allowConnections = false; } public synchronized void enableUpcalls() { // synchronized (ibis.ipl.impl.messagePassing.Ibis.myIbis) { ibis.ipl.impl.messagePassing.Ibis.myIbis.lock(); allowUpcalls = true; enable.cv_signal(); ibis.ipl.impl.messagePassing.Ibis.myIbis.unlock(); } public synchronized void disableUpcalls() { allowUpcalls = false; } boolean connect(ShadowSendPort sp) { // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockOwned(); if (connectUpcall == null || acceptThread.checkAccept(sp.identifier())) { connections.add(sp); return true; } else { return false; } } void disconnect(ShadowSendPort sp) { // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockOwned(); connections.remove(sp); // System.err.println(Thread.currentThread() + "Disconnect SendPort " + sp + " from ReceivePort " + this + ", remaining connections " + connections.size()); if (connections.size() == 0) { disconnected.cv_signal(); } } private void createNewUpcallThread() { new Thread(this).start(); } private ibis.ipl.impl.messagePassing.ReadMessage locate(ShadowSendPort ssp, int msgSeqno) { if (ssp.msgSeqno > msgSeqno && ssp.msgSeqno != -1) { if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println("This is a SERIOUS BUG: the msgSeqno goes BACK!!!!!!!!!"); } ssp.msgSeqno = msgSeqno; return null; } if (currentMessage != null && currentMessage.shadowSendPort == ssp && currentMessage.msgSeqno == msgSeqno) { return currentMessage; } ibis.ipl.impl.messagePassing.ReadMessage scan; for (scan = queueFront; scan != null && (scan.shadowSendPort != ssp || scan.msgSeqno != msgSeqno); scan = scan.next) { } return scan; } void enqueue(ibis.ipl.impl.messagePassing.ReadMessage msg) { // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockOwned(); if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println(Thread.currentThread() + "Enqueue message " + msg + " in port " + this + " msgHandle " + Integer.toHexString(msg.fragmentFront.msgHandle) + " current queueFront " + queueFront); } if (queueFront == null) { queueFront = msg; } else { queueTail.next = msg; } queueTail = msg; msg.next = null; if (ibis.ipl.impl.messagePassing.Ibis.STATISTICS) { enqueued_msgs++; } if (arrivedWaiters > 0) { messageArrived.cv_signal(); } if (upcall != null) { wakeup(); if (ibis.ipl.impl.messagePassing.Ibis.STATISTICS) { upcall_msgs++; } if (handlingReceive == 0) { System.err.println("Create another UpcallThread because the previous one didn't terminate"); createNewUpcallThread(); } } } private ibis.ipl.impl.messagePassing.ReadMessage dequeue() { // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockOwned(); ibis.ipl.impl.messagePassing.ReadMessage msg = queueFront; if (msg != null) { if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println("Now dequeue msg " + msg); } queueFront = msg.next; if (ibis.ipl.impl.messagePassing.Ibis.STATISTICS) { dequeued_msgs++; } } return msg; } void finishMessage() { // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockOwned(); if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println("******* Now finish this ReceivePort message: " + currentMessage); // Thread.dumpStack(); } ShadowSendPort ssp = currentMessage.shadowSendPort; if (ssp.cachedMessage == null) { ssp.cachedMessage = currentMessage; } currentMessage = null; aMessageIsAlive = false; if (liveWaiters > 0) { messageHandled.cv_signal(); } if (queueFront != null && arrivedWaiters > 0) { messageArrived.cv_signal(); } ssp.tickReceive(); } PollClient next; PollClient prev; public boolean satisfied() { return queueFront != null || stop; } public void wakeup() { messageArrived.cv_signal(); } public void poll_wait(long timeout) { messageArrived.cv_wait(timeout); } public PollClient next() { return next; } public PollClient prev() { return prev; } public void setNext(PollClient c) { next = c; } public void setPrev(PollClient c) { prev = c; } Thread me; public Thread thread() { return me; } public void setThread(Thread thread) { me = thread; } void receiveFragment(ShadowSendPort origin, int msgHandle, int msgSize, int msgSeqno) throws IbisIOException { // checkLockOwned(); /* Let's see whether we already have an envelope for this fragment. */ ibis.ipl.impl.messagePassing.ReadMessage msg = locate(origin, msgSeqno); if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println(Thread.currentThread() + " Port " + this + " receive a fragment seqno " + msgSeqno + " size " + msgSize + " that belongs to msg " + msg + "; currentMessage = " + currentMessage + (currentMessage == null ? "" : (" .seqno " + currentMessage.msgSeqno))); } // System.err.println(Thread.currentThread() + "Enqueue message in port " + this + " id " + identifier() + " msgHandle " + Integer.toHexString(msgHandle) + " current queueFront " + queueFront); boolean lastFrag = (msgSeqno < 0); if (lastFrag) { msgSeqno = -msgSeqno; } /* Let's see whether our ShadowSendPort has a fragment cached */ ReadFragment f = origin.getFragment(); boolean firstFrag = (msg == null); if (firstFrag) { /* This must be the first fragment of a new message. * Let our ShadowSendPort create an envelope, i.e. a ReadMessage * for it. */ msg = origin.getMessage(msgSeqno); } f.msg = msg; f.lastFrag = lastFrag; f.msgHandle = msgHandle; f.msgSize = msgSize; /* Hook up the fragment in the message envelope */ msg.enqueue(f); /* Must set in.msgHandle and in.msgSize from here: cannot wait * until we do a read: * - a message may be empty and still must be able to clear it * - a Serialized stream starts reading in the constructor */ if (firstFrag && origin.checkStarted(msg)) { enqueue(msg); } } ibis.ipl.ReadMessage doReceive() throws IbisIOException { // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockOwned(); if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println(Thread.currentThread() + "******** enter ReceivePort.receive()" + this.ident); } while (aMessageIsAlive && ! stop) { liveWaiters++; if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println(Thread.currentThread() + "Hit wait in ReceivePort.receive()" + this.ident + " aMessageIsAlive is true"); } messageHandled.cv_wait(); liveWaiters } aMessageIsAlive = true; // long t = Ibis.currentTime(); // if (upcall != null) System.err.println("Hit receive() in an upcall()"); for (int i = 0; queueFront == null && i < Poll.polls_before_yield; i++) { ibis.ipl.impl.messagePassing.Ibis.myIbis.rcve_poll.poll(); } if (queueFront == null) { if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println(Thread.currentThread() + "Hit wait in ReceivePort.receive()" + this.ident + " queue " + queueFront + " " + messageArrived); } arrivedWaiters++; ibis.ipl.impl.messagePassing.Ibis.myIbis.waitPolling(this, 0, true); arrivedWaiters } if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println(Thread.currentThread() + "Past wait in ReceivePort.receive()" + this.ident); } currentMessage = dequeue(); if (currentMessage == null) { return null; } currentMessage.in.setMsgHandle(currentMessage); // ibis.ipl.impl.messagePassing.Ibis.myIbis.tReceive += Ibis.currentTime() - t; return currentMessage; } public ibis.ipl.ReadMessage receive(ibis.ipl.ReadMessage finishMe) throws IbisIOException { // synchronized (ibis.ipl.impl.messagePassing.Ibis.myIbis) { ibis.ipl.impl.messagePassing.Ibis.myIbis.lock(); try { // manta.runtime.RuntimeSystem.DebugMe(this, this); if (finishMe != null) { finishMe.finish(); } return doReceive(); } finally { ibis.ipl.impl.messagePassing.Ibis.myIbis.unlock(); } } public ibis.ipl.ReadMessage receive() throws IbisIOException { // synchronized (ibis.ipl.impl.messagePassing.Ibis.myIbis) { ibis.ipl.impl.messagePassing.Ibis.myIbis.lock(); try { // manta.runtime.RuntimeSystem.DebugMe(this, this); return doReceive(); } finally { ibis.ipl.impl.messagePassing.Ibis.myIbis.unlock(); } } public ibis.ipl.DynamicProperties properties() { return null; } public ibis.ipl.ReceivePortIdentifier identifier() { return ident; } class Shutdown implements PollClient { PollClient next; PollClient prev; public boolean satisfied() { return connections.size() == 0; } public void wakeup() { disconnected.cv_signal(); } public void poll_wait(long timeout) { disconnected.cv_wait(timeout); } public PollClient next() { return next; } public PollClient prev() { return prev; } public void setNext(PollClient c) { next = c; } public void setPrev(PollClient c) { prev = c; } Thread me; public Thread thread() { return me; } public void setThread(Thread thread) { me = thread; } } /** Asynchronous receive. Return immediately when no message is available. Also works for upcalls, then it is a normal poll. **/ public ibis.ipl.ReadMessage poll() throws IbisIOException { System.err.println("poll not implemented"); return null; } /** Asynchronous receive, as above, but free an old message. Also works for upcalls, then it is a normal poll. **/ public ibis.ipl.ReadMessage poll(ibis.ipl.ReadMessage finishMe) throws IbisIOException { System.err.println("poll not implemented"); return null; } public void free() { if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.out.println(name + ":Starting receiveport.free upcall = " + upcall); } // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockNotOwned(); Shutdown shutdown = new Shutdown(); // synchronized (ibis.ipl.impl.messagePassing.Ibis.myIbis) { ibis.ipl.impl.messagePassing.Ibis.myIbis.lock(); if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.out.println(name + ": got Ibis lock"); } stop = true; messageHandled.cv_bcast(); messageArrived.cv_bcast(); if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.out.println(name + ": Enter shutdown.waitPolling; connections = " + connectionToString()); } try { while (connections.size() > 0) { ibis.ipl.impl.messagePassing.Ibis.myIbis.waitPolling(shutdown, 0, false); } } catch (IbisIOException e) { /* well, if it throws an exception, let's quit.. */ } if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.out.println(name + ": Past shutdown.waitPolling"); } /* while (connections.size() > 0) { disconnected.cv_wait(); if (upcall != null) { if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.out.println(name + " waiting for all connections to close (" + connections.size() + ")"); } try { wait(); } catch (InterruptedException e) { // Ignore. } } else { if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.out.println(name + " trying to close all connections (" + connections.size() + ")"); } } } */ if (connectUpcall != null) { acceptThread.free(); } ibis.ipl.impl.messagePassing.Ibis.myIbis.unlock(); /* unregister with name server */ try { if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.out.println(name + ": unregister with name server"); } type.freeReceivePort(name); } catch(Exception e) { // Ignore. } if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.out.println(name + ":done receiveport.free"); } ibis.ipl.impl.messagePassing.Ibis.myIbis.lock(); livingPorts if (livingPorts == 0) { portCounter.s_signal(true); } ibis.ipl.impl.messagePassing.Ibis.myIbis.unlock(); } private String connectionToString() { String t = "Connections ="; for (int i = 0; i < connections.size(); i++) { t = t + " " + (ShadowSendPort)connections.elementAt(i); } return t; } public void run() { if (upcall == null) { System.err.println(Thread.currentThread() + "ReceivePort runs but upcall == null"); } System.err.println(Thread.currentThread() + " ReceivePort " + name + " runs"); try { while (true) { ibis.ipl.ReadMessage msg; msg = null; // synchronized (ibis.ipl.impl.messagePassing.Ibis.myIbis) { ibis.ipl.impl.messagePassing.Ibis.myIbis.lock(); try { if (stop || handlingReceive > 0) { if (DEBUG) { System.err.println("Receive port " + name + " upcall thread polls " + upcall_poll); } break; } /* Avoid waiting threads in waitPolling. Having too many * (like always one server in this ReceivePort) makes the * poll for an expected reply very expensive. * Nowadays, pass 'false' for the preempt flag. */ handlingReceive++; if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println("*********** This ReceivePort daemon hits wait, daemon " + this + " queueFront = " + queueFront); } ibis.ipl.impl.messagePassing.Ibis.myIbis.waitPolling(this, 0, false); if (DEBUG) { upcall_poll++; System.err.println("*********** This ReceivePort daemon past wait, daemon " + this + " queueFront = " + queueFront); } while (! allowUpcalls) { enable.cv_wait(); } msg = doReceive(); // May throw an IbisIOException handlingReceive } finally { ibis.ipl.impl.messagePassing.Ibis.myIbis.unlock(); } if (msg != null) { if (ibis.ipl.impl.messagePassing.Ibis.DEBUG) { System.err.println("Now process this msg " + msg + " msg.fragmentFront.msgHandle " + Integer.toHexString(((ibis.ipl.impl.messagePassing.ReadMessage)msg).fragmentFront.msgHandle)); } // ibis.ipl.impl.messagePassing.Ibis.myIbis.checkLockNotOwned(); // for (int x = 0; x < handlingReceive + 1; x++) { // System.err.print(">"); // System.err.println(); upcall.upcall(msg); // for (int x = 0; x < handlingReceive + 1; x++) { // System.err.print("<"); // System.err.println(); } } } catch (IbisIOException e) { if (e == null) { System.err.println("A NULL Exception?????"); System.err.println("My stack: "); Thread.dumpStack(); // manta.runtime.RuntimeSystem.DebugMe(e, e); } else { System.err.println(e); e.printStackTrace(); } // System.err.println("My stack: "); // Thread.dumpStack(); // System.exit(44); } if (DEBUG) { System.err.println("Receive port " + name + " upcall thread polls " + upcall_poll); } } static void end() { // assert(ibis.ipl.impl.messagePassing.Ibis.myIbis.locked(); while (livingPorts > 0) { try { portCounter.s_wait(0); } catch (ibis.ipl.IbisIOException e) { break; } } } }
package nl.mpi.kinnate; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import nl.mpi.arbil.LinorgSessionStorage; import nl.mpi.arbil.data.ImdiLoader; import nl.mpi.arbil.data.ImdiTreeObject; public class GraphData { private HashMap<String, GraphDataNode> graphDataNodeList = new HashMap<String, GraphDataNode>(); public int gridWidth; public void readData() { String[] treeNodesArray = LinorgSessionStorage.getSingleInstance().loadStringArray("KinGraphTree"); if (treeNodesArray != null) { for (String currentNodeString : treeNodesArray) { try { ImdiTreeObject imdiTreeObject = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(currentNodeString)); graphDataNodeList.put(imdiTreeObject.getUrlString(), new GraphDataNode(imdiTreeObject)); } catch (URISyntaxException exception) { System.err.println(exception.getMessage()); exception.printStackTrace(); } } } calculateLinks(); calculateLocations(); printLocations(); } private void calculateLinks() { System.out.println("calculateLinks"); for (GraphDataNode currentNode : graphDataNodeList.values()) { ArrayList<GraphDataNode> linkNodes = new ArrayList<GraphDataNode>(); for (String currentLinkString : currentNode.getLinks()) { GraphDataNode linkedNode = graphDataNodeList.get(currentLinkString); if (linkedNode != null) { linkNodes.add(linkedNode); System.out.println("link found: " + currentLinkString); } } currentNode.setGraphDataNodes(linkNodes.toArray(new GraphDataNode[]{})); } } private void calculateLocations() { System.out.println("calculateLocations"); gridWidth = (int) Math.sqrt(graphDataNodeList.size()); System.out.println("gridWidth: " + gridWidth); int xPos = 0; int yPos = 0; for (GraphDataNode graphDataNode : graphDataNodeList.values()) { graphDataNode.xPos = xPos; graphDataNode.yPos = yPos; xPos++; if (xPos > gridWidth) { xPos = 0; yPos++; } } } public GraphDataNode[] getDataNodes() { return graphDataNodeList.values().toArray(new GraphDataNode[]{}); } private void printLocations() { System.out.println("printLocations"); for (GraphDataNode graphDataNode : graphDataNodeList.values()) { System.out.println("node: " + graphDataNode.xPos + ":" + graphDataNode.yPos); for (GraphDataNode graphLinkNode : graphDataNode.linkedNodes) { System.out.println("link: " + graphLinkNode.xPos + ":" + graphLinkNode.yPos); } } } public static void main(String args[]) { GraphData graphData = new GraphData(); graphData.readData(); System.exit(0); } }
package info.justaway; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import twitter4j.auth.AccessToken; public class AccountSettingActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account_setting); ListView listView = (ListView) findViewById(R.id.list_view); AccountAdapter adapter = new AccountAdapter(this, R.layout.row_word); listView.setAdapter(adapter); ArrayList<AccessToken> accessTokens = JustawayApplication.getApplication().getAccessTokens(); if (accessTokens != null) { for (AccessToken accessToken : accessTokens) { adapter.add(accessToken); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.account_setting, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.add_account: Intent intent = new Intent(this, SignInActivity.class); intent.putExtra("add_account", true); startActivity(intent); break; } return true; } public class AccountAdapter extends ArrayAdapter<AccessToken> { private ArrayList<AccessToken> mAccountLists = new ArrayList<AccessToken>(); private LayoutInflater mInflater; private int mLayout; public AccountAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.mLayout = textViewResourceId; } @Override public void add(AccessToken account) { super.add(account); mAccountLists.add(account); } public void remove(int position) { super.remove(mAccountLists.remove(position)); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { // null view = mInflater.inflate(this.mLayout, null); } final AccessToken accessToken = mAccountLists.get(position); assert view != null; TextView screenName = (TextView) view.findViewById(R.id.word); TextView trash = (TextView) view.findViewById(R.id.trash); trash.setTypeface(JustawayApplication.getFontello()); screenName.setText("@".concat(accessToken.getScreenName())); if (JustawayApplication.getApplication().getUserId() == accessToken.getUserId()) { screenName.setTextColor(getResources().getColor(R.color.holo_blue_bright)); trash.setVisibility(View.GONE); } else { view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { JustawayApplication.getApplication().setAccessToken(accessToken); finish(); } }); } view.findViewById(R.id.trash).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(AccountSettingActivity.this) .setTitle("@".concat(accessToken.getScreenName().concat(getString(R.string.confirm_remove_account)))) .setPositiveButton( R.string.button_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { remove(position); JustawayApplication.getApplication().removeAccessToken(position); finish(); } }) .setNegativeButton( R.string.button_no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); } }); return view; } } }
package org.biojava.bio.seq.impl; import org.biojava.bio.seq.*; import java.util.*; import java.io.*; import java.lang.reflect.*; import org.biojava.bio.*; import org.biojava.utils.*; import org.biojava.bio.seq.homol.*; /** * Wrap up default sets of Feature implementations. * * @author Thomas Down * @author Greg Cox * @since 1.1 */ public class FeatureImpl { /** * Default implementation of FeatureRealizer, which wraps simple * implementations of Feature and StrandedFeature. This is the * default FeatureRealizer used by SimpleSequence and ViewSequence, * and may also be used by others. When building new FeatureRealizers, * you may wish to use this as a `fallback' realizer, and benefit from * the Feature and StrandedFeature implementations. */ public final static FeatureRealizer DEFAULT; static { SimpleFeatureRealizer d = new SimpleFeatureRealizer() { public Object writeReplace() { try { return new StaticMemberPlaceHolder(SimpleFeatureRealizer.class.getField("DEFAULT")); } catch (NoSuchFieldException ex) { throw new BioError(ex); } } } ; try { d.addImplementation(Feature.Template.class, SimpleFeature.class); d.addImplementation(StrandedFeature.Template.class, SimpleStrandedFeature.class); d.addImplementation(HomologyFeature.Template.class, SimpleHomologyFeature.class); d.addImplementation(RemoteFeature.Template.class, SimpleRemoteFeature.class); } catch (BioException ex) { throw new BioError(ex, "Couldn't initialize default FeatureRealizer"); } DEFAULT = d; } }
package no.javazone; import co.paralleluniverse.fibers.Fiber; import co.paralleluniverse.fibers.Suspendable; import co.paralleluniverse.fibers.httpclient.FiberHttpClientBuilder; import co.paralleluniverse.strands.SuspendableRunnable; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static no.javazone.RunConfig.url; public class FiberExample { private static ObjectMapper mapper = new ObjectMapper(); private static CloseableHttpClient client = FiberHttpClientBuilder. create(20). setMaxConnPerRoute(9999). setMaxConnTotal(9999).build(); /** * In current state - no where near as good performance as vertx, but syntax is better */ public static void main(String[] args) throws Exception { TaskRunner taskRunner = new TaskRunner(1_000); taskRunner.runTask(() -> new Fiber((SuspendableRunnable) () -> { getPersonInCity("abc"); taskRunner.countDown(); }).start()); } @Suspendable private static TypicalExamples.PersonInCity getPersonInCity(String id) { if (!validateId(id)) { throw new IllegalArgumentException("invalid id"); } try { String personContent = new BufferedReader(new InputStreamReader(client.execute(new HttpGet(url + "/person/" + id)).getEntity().getContent())).readLine(); TypicalExamples.Person person = parsePerson(personContent); String addressContent = new BufferedReader(new InputStreamReader((client.execute(new HttpGet(url + "/address/" + id)).getEntity().getContent()))).readLine(); TypicalExamples.Address address = parseAddress(addressContent); return translate(person, address); } catch (IOException e) { throw new RuntimeException(e); } } private static TypicalExamples.Address parseAddress(String body) throws IOException { return mapper.readValue(body, TypicalExamples.Address.class); } private static TypicalExamples.Person parsePerson(String body) throws IOException { return mapper.readValue(body, TypicalExamples.Person.class); } private static TypicalExamples.PersonInCity translate(TypicalExamples.Person p, TypicalExamples.Address a) { return new TypicalExamples.PersonInCity(p.name, a.city); } private static boolean validateId(String id) { return !(id == null || id.isEmpty()); } }
package org.cleartk.util; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import org.apache.uima.cas.ConstraintFactory; import org.apache.uima.cas.FSIndex; import org.apache.uima.cas.FSIntConstraint; import org.apache.uima.cas.FSIterator; import org.apache.uima.cas.FSMatchConstraint; import org.apache.uima.cas.FSTypeConstraint; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeaturePath; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.Type; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.jcas.tcas.DocumentAnnotation; import org.cleartk.type.SplitAnnotation; public class AnnotationRetrieval { /** * This method exists simply as a convenience method for unit testing. It is * not very efficient and should not, in general be used outside the context * of unit testing. */ public static <T extends Annotation> T get(JCas jCas, Class<T> cls, int index) { int type; try { type = (Integer) cls.getField("type").get(null); } catch (IllegalAccessException e) { throw new RuntimeException(); } catch (NoSuchFieldException e) { throw new RuntimeException(); } // TODO we should probably iterate from the end rather than // iterating forward from the begining. FSIndex fsIndex = jCas.getAnnotationIndex(type); if (index < 0) index = fsIndex.size() + index; if (index < 0 || index >= fsIndex.size()) return null; FSIterator iterator = fsIndex.iterator(); Object returnValue = iterator.next(); for (int i = 0; i < index; i++) { returnValue = iterator.next(); } return cls.cast(returnValue); } public static <T extends Annotation> T get(JCas jCas, T annotation, int relativePosition) { return get(jCas, annotation, relativePosition, null); } @SuppressWarnings("unchecked") public static <T extends Annotation> T get(JCas jCas, T annotation, int relativePosition, Annotation windowAnnotation) { FSIterator cursor = jCas.getAnnotationIndex(annotation.getType()).iterator(); cursor.moveTo(annotation); if (relativePosition > 0) { for (int i = 0; i < relativePosition && cursor.isValid(); i++) cursor.moveToNext(); } else { for (int i = 0; i < -relativePosition && cursor.isValid(); i++) cursor.moveToPrevious(); } if (cursor.isValid()) { Annotation relativeAnnotation = (Annotation) cursor.get(); T returnValue = ((Class<T>) annotation.getClass()).cast(relativeAnnotation); if (windowAnnotation != null) { if (AnnotationUtil.contains(windowAnnotation, relativeAnnotation)) return returnValue; else return null; } else return returnValue; } else return null; } public static <RETURN_TYPE extends Annotation> RETURN_TYPE get(JCas jCas, Annotation annotation, Class<RETURN_TYPE> returnCls, int relativePosition) { if(relativePosition == 0) { return getFirstAnnotation(jCas, annotation, returnCls); } else if(relativePosition < 0) { RETURN_TYPE returnValue = getAdjacentAnnotation(jCas, annotation, returnCls, true); if(returnValue == null) return null; if(relativePosition == -1) return returnValue; return get(jCas, returnValue, relativePosition + 1); } else { RETURN_TYPE returnValue = getAdjacentAnnotation(jCas, annotation, returnCls, false); if(returnValue == null) return null; if(relativePosition == 1) return returnValue; return get(jCas, returnValue, relativePosition - 1); } } /** * We initially used the AnnotationIndex.subiterator() but ran into issues * that we wanted to work around concerning the use of type priorities when * the window and windowed annotations have the same begin and end offsets. * By using our own iterator we can back up to the first annotation that has * the same beginning as the window annotation and avoid having to set type * priorities. * * @param jCas * @param windowAnnotation * @return an FSIterator that is at the correct position */ private static FSIterator initializeWindowCursor(JCas jCas, Annotation windowAnnotation) { FSIterator cursor = jCas.getAnnotationIndex().iterator(); cursor.moveTo(windowAnnotation); // if cursor is invalid now we're past the end of the index if( !cursor.isValid() ) return cursor; while (cursor.isValid() && ((Annotation) cursor.get()).getBegin() >= windowAnnotation.getBegin()) { cursor.moveToPrevious(); } if (cursor.isValid()) { cursor.moveToNext(); } else { cursor.moveToFirst(); } return cursor; } /** * @param <T> * determines the return type of the method * @param jCas * the current jCas or view * @param windowAnnotation * an annotation that defines a window * @param cls * determines the return type of the method * @return the last annotation of type cls that is "inside" the window * @see #getAnnotations(JCas, Annotation, Class) */ public static <T extends Annotation> T getLastAnnotation(JCas jCas, Annotation windowAnnotation, Class<T> cls) { FSIterator cursor = initializeWindowCursor(jCas, windowAnnotation); T currentBestGuess = null; while (cursor.isValid() && ((Annotation) cursor.get()).getBegin() <= windowAnnotation.getEnd()) { Annotation annotation = (Annotation) cursor.get(); if (cls.isInstance(annotation) && annotation.getEnd() <= windowAnnotation.getEnd()) currentBestGuess = cls .cast(annotation); cursor.moveToNext(); } return currentBestGuess; } /** * @param <T> * determines the return type of the method * @param jCas * the current jCas or view * @param windowAnnotation * an annotation that defines a window * @param cls * determines the return type of the method * @return the first annotation of type cls that is "inside" the window * @see #getAnnotations(JCas, Annotation, Class) */ public static <T extends Annotation> T getFirstAnnotation(JCas jCas, Annotation windowAnnotation, Class<T> cls) { FSIterator cursor = initializeWindowCursor(jCas, windowAnnotation); // I left in the while loop because the first annotation we see might // not be the right class while (cursor.isValid() && ((Annotation) cursor.get()).getBegin() <= windowAnnotation.getEnd()) { Annotation annotation = (Annotation) cursor.get(); if (cls.isInstance(annotation) && annotation.getEnd() <= windowAnnotation.getEnd()) return cls .cast(annotation); cursor.moveToNext(); } return null; } /** * @param <T> * determines the return type of the method * @param view * the jCAS view * @param cls * determines the return type of the method * @return the first annotation of type cls in this view */ public static <T extends Annotation> T getFirstAnnotation(JCas view, Class<T> cls) { FSIterator cursor = view.getAnnotationIndex().iterator(); cursor.moveToFirst(); while( cursor.isValid() ) { Annotation annotation = (Annotation) cursor.get(); if( cls.isInstance(annotation) ) return cls.cast(annotation); cursor.moveToNext(); } return null; } /* * Find an annotation of a different type that covers the same span. * * @param <T> is the type of annotation we're looking for @param jCas is the * current CAS view @param windowAnnotation determines the span of the * annotation @return the first annotation in the index that has the same * span as windowAnnotation */ public static <T extends Annotation> T getMatchingAnnotation(JCas jCas, Annotation windowAnnotation, Class<T> cls) { if (cls.isInstance(windowAnnotation)) return cls.cast(windowAnnotation); FSIterator cursor = jCas.getAnnotationIndex().iterator(); cursor.moveTo(windowAnnotation); Annotation cursorAnnotation = (Annotation) cursor.get(); if (cursorAnnotation.getBegin() != windowAnnotation.getBegin() || cursorAnnotation.getEnd() != windowAnnotation.getEnd()) return null; while (cursor.isValid() && cursorAnnotation.getBegin() == windowAnnotation.getBegin() && cursorAnnotation.getEnd() == windowAnnotation.getEnd()) { cursor.moveToPrevious(); if (cursor.isValid()) cursorAnnotation = (Annotation) cursor.get(); else cursorAnnotation = null; } if (cursor.isValid()) { cursor.moveToNext(); cursorAnnotation = (Annotation) cursor.get(); } else { cursor.moveToFirst(); cursorAnnotation = (Annotation) cursor.get(); } while (cursor.isValid() && cursorAnnotation.getBegin() == windowAnnotation.getBegin() && cursorAnnotation.getEnd() == windowAnnotation.getEnd()) { if (cls.isInstance(cursorAnnotation)) return cls.cast(cursorAnnotation); cursor.moveToNext(); if (cursor.isValid()) cursorAnnotation = (Annotation) cursor.get(); else cursorAnnotation = null; } return null; } /** * Returns a List of all annotations of a given type. * * @param <T> * The type of Annotation being collected. * @param jCas * The JCas from which annotations should be collected. * @param annotationClass * The Annotation class. * @return A List of all Annotations of the given type. */ public static <T extends Annotation> List<T> getAnnotations(JCas jCas, Class<T> annotationClass) { // get the integer type from the annotation class // not that T.type doesn't work because that gives us Annotation.type // (why?) int type; try { type = annotationClass.getField("type").getInt(null); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } // collect all annotations of the given type into a list AnnotationIndex index = jCas.getAnnotationIndex(type); List<T> annotations = new ArrayList<T>(); for (FSIterator iter = index.iterator(); iter.hasNext();) { Object next = iter.next(); annotations.add(annotationClass.cast(next)); } return annotations; } /** * This method returns all annotations (in order) that are inside a "window" * annotation of a particular kind. The functionality provided is similar to * using AnnotationIndex.subiterator(), however we found the use of type * priorities which is documented in detail in their javadocs to be * distasteful. This method does not require that type priorities be set in * order to work as expected for the condition where the window annotation * and the "windowed" annotation have the same size and location. * * @param <T> * determines the return type of the method * @param jCas * the current jCas or view * @param windowAnnotation * an annotation that defines a window * @param cls * determines the return type of the method * @return a list of annotations of type cls that are "inside" the window * @see AnnotationIndex#subiterator(org.apache.uima.cas.text.AnnotationFS) */ public static <T extends Annotation> List<T> getAnnotations(JCas jCas, Annotation windowAnnotation, Class<T> cls) { if (windowAnnotation instanceof SplitAnnotation) return getAnnotations(jCas, (SplitAnnotation) windowAnnotation, cls); FSIterator cursor = initializeWindowCursor(jCas, windowAnnotation); List<T> annotations = new ArrayList<T>(); while (cursor.isValid() && ((Annotation) cursor.get()).getBegin() <= windowAnnotation.getEnd()) { Annotation annotation = (Annotation) cursor.get(); if (cls.isInstance(annotation) && annotation.getEnd() <= windowAnnotation.getEnd()) annotations.add(cls .cast(annotation)); cursor.moveToNext(); } return annotations; } public static <T extends Annotation> List<T> getAnnotations(JCas jCas, Annotation windowAnnotation, Class<T> cls, boolean exactSpan) { if (windowAnnotation instanceof SplitAnnotation) return getAnnotations(jCas, (SplitAnnotation) windowAnnotation, cls); if (!exactSpan) return getAnnotations(jCas, windowAnnotation, cls); else { FSIterator cursor = initializeWindowCursor(jCas, windowAnnotation); List<T> annotations = new ArrayList<T>(); while (cursor.isValid() && ((Annotation) cursor.get()).getBegin() <= windowAnnotation.getEnd()) { Annotation annotation = (Annotation) cursor.get(); if (cls.isInstance(annotation) && annotation.getBegin() == windowAnnotation.getBegin() && annotation.getEnd() == windowAnnotation.getEnd()) annotations.add(cls.cast(annotation)); cursor.moveToNext(); } return annotations; } } public static <T extends Annotation> List<T> getAnnotations(JCas jCas, int begin, int end, Class<T> cls, boolean exactSpan) { if(begin > end) return null; if (!exactSpan) { return getAnnotations(jCas, begin, end, cls); } else { return getAnnotations(jCas, new Annotation(jCas, begin, end), cls, exactSpan); } } public static <T extends Annotation> List<T> getAnnotations(JCas jCas, SplitAnnotation splitAnnotation, Class<T> cls) { List<T> returnValues = new ArrayList<T>(); for (FeatureStructure subAnnotation : splitAnnotation.getAnnotations().toArray()) { returnValues.addAll(getAnnotations(jCas, (Annotation) subAnnotation, cls)); } return returnValues; } public static <T extends Annotation> List<T> getAnnotations(JCas jCas, int begin, int end, Class<T> cls) { if(begin > end) return null; Annotation annotation = new Annotation(jCas, begin, end); return getAnnotations(jCas, annotation, cls); } /** * This method provides a way to have multiple annotations define the window * that is used to constrain the annotations in the returned list. The * intersection of the windows is determined and used. This method will * treat any split annotations in the list as a contiguous annotation. * * @see #getAnnotations(JCas, Annotation, Class) * @see #getAnnotations(JCas, SplitAnnotation, Class) */ public static <T extends Annotation> List<T> getAnnotations(JCas jCas, List<Annotation> windowAnnotations, Class<T> cls) { if (windowAnnotations == null || windowAnnotations.size() == 0) return null; int windowBegin = Integer.MIN_VALUE; int windowEnd = Integer.MAX_VALUE; for (Annotation windowAnnotation : windowAnnotations) { if (windowAnnotation.getBegin() > windowBegin) windowBegin = windowAnnotation.getBegin(); if (windowAnnotation.getEnd() < windowEnd) windowEnd = windowAnnotation.getEnd(); } return getAnnotations(jCas, windowBegin, windowEnd, cls); } // TODO think about how to make this method faster by avoiding using a // constrained iterator. See TODO note for // get adjacent annotation. /** * returns getContainingAnnotation(jCas, focusAnnotation, cls, false) */ public static <T extends Annotation> T getContainingAnnotation(JCas jCas, Annotation focusAnnotation, Class<T> cls) { return getContainingAnnotation(jCas, focusAnnotation, cls, false); } /** * This method finds the smallest annotation of type cls that contains the * focus annotation. * * @param jCas * @param focusAnnotation * an annotation that will be contained by the returned value * @param cls * determines the type of the returned annotation * @param exclusiveContain * if true, then the method will only return an annotation if it * is larger than the focus annotation. If false, then an * annotation of the same size can be returned if one exists of * the type specified by the cls param. This may be undesirable * if the focus annotation is the same type as the cls param * because it will return the focus annotation when you might * actually want the next biggest annotation that contains the * focus annotation. * @return an annotation of type cls that contains the focus annotation or * null it one does not exist. */ public static <T extends Annotation> T getContainingAnnotation(JCas jCas, Annotation focusAnnotation, Class<T> cls, boolean exclusiveContain) { if(focusAnnotation == null) throw new IllegalArgumentException("focus annotation may not be null"); FSIterator cursor = jCas.getAnnotationIndex().iterator(); //the goal is to move the cursor to the last annotation that begins at the same index as the focus annotation cursor.moveTo(focusAnnotation); while (cursor.isValid()) { cursor.moveToNext(); //if we have moved past the last element, then move cursor to last element and be done if(!cursor.isValid()) { cursor.moveToLast(); break; } //if we have moved to an annotation that does not be begin at the same index as the focus annotation, //then move to previous. Annotation nextAnnotation = (Annotation) cursor.get(); if(nextAnnotation.getBegin() != focusAnnotation.getBegin()) { cursor.moveToPrevious(); break; } } while (cursor.isValid()) { Annotation annotation = (Annotation) cursor.get(); if (exclusiveContain) { if (cls.isInstance(annotation) && annotation.getBegin() <= focusAnnotation.getBegin() && annotation.getEnd() >= focusAnnotation.getEnd() && AnnotationUtil.size(annotation) > AnnotationUtil.size(focusAnnotation)) { return cls.cast(annotation); } } else { if (cls.isInstance(annotation) && annotation.getBegin() <= focusAnnotation.getBegin() && annotation.getEnd() >= focusAnnotation.getEnd()) { return cls.cast(annotation); } } cursor.moveToPrevious(); } return null; } public static <T extends Annotation> List<T> getOverlappingAnnotations(JCas jCas, Annotation focusAnnotation, Class<T> cls, boolean before) { List<T> annotations = new ArrayList<T>(); ConstraintFactory constraintFactory = jCas.getConstraintFactory(); FSTypeConstraint typeConstraint = constraintFactory.createTypeConstraint(); Type type = UIMAUtil.getCasType(jCas, cls); typeConstraint.add(type); FSMatchConstraint overlapConstraint; if(before) overlapConstraint = getOverlapBeforeConstraint(jCas, focusAnnotation, constraintFactory); else overlapConstraint = getOverlapAfterConstraint(jCas, focusAnnotation, constraintFactory); FSIterator iterator = jCas.createFilteredIterator(jCas.getAnnotationIndex(type).iterator(), overlapConstraint); while(iterator.hasNext()) { T annotation = cls.cast(iterator.next()); annotations.add(annotation); } return annotations; } private static FSMatchConstraint getOverlapBeforeConstraint(JCas jCas, Annotation focusAnnotation, ConstraintFactory constraintFactory) { FSIntConstraint beginIntConstraint = constraintFactory.createIntConstraint(); beginIntConstraint.lt(focusAnnotation.getBegin()); FeaturePath beginPath = jCas.createFeaturePath(); Feature beginFeature = jCas.getTypeSystem().getFeatureByFullName("uima.tcas.Annotation:begin"); beginPath.addFeature(beginFeature); FSMatchConstraint beginConstraint = constraintFactory.embedConstraint(beginPath, beginIntConstraint); FSIntConstraint endIntConstraint = constraintFactory.createIntConstraint(); endIntConstraint.gt(focusAnnotation.getBegin()); endIntConstraint.leq(focusAnnotation.getEnd()); FeaturePath endPath = jCas.createFeaturePath(); Feature endFeature = jCas.getTypeSystem().getFeatureByFullName("uima.tcas.Annotation:end"); endPath.addFeature(endFeature); FSMatchConstraint endConstraint = constraintFactory.embedConstraint(endPath, endIntConstraint); return constraintFactory.and(beginConstraint, endConstraint); } private static FSMatchConstraint getOverlapAfterConstraint(JCas jCas, Annotation focusAnnotation, ConstraintFactory constraintFactory) { FSIntConstraint beginIntConstraint = constraintFactory.createIntConstraint(); beginIntConstraint.geq(focusAnnotation.getBegin()); beginIntConstraint.lt(focusAnnotation.getEnd()); FeaturePath beginPath = jCas.createFeaturePath(); Feature beginFeature = jCas.getTypeSystem().getFeatureByFullName("uima.tcas.Annotation:begin"); beginPath.addFeature(beginFeature); FSMatchConstraint beginConstraint = constraintFactory.embedConstraint(beginPath, beginIntConstraint); FSIntConstraint endIntConstraint = constraintFactory.createIntConstraint(); endIntConstraint.gt(focusAnnotation.getEnd()); FeaturePath endPath = jCas.createFeaturePath(); Feature endFeature = jCas.getTypeSystem().getFeatureByFullName("uima.tcas.Annotation:end"); endPath.addFeature(endFeature); FSMatchConstraint endConstraint = constraintFactory.embedConstraint(endPath, endIntConstraint); return constraintFactory.and(beginConstraint, endConstraint); } /** * Finds and returns the annotation of the provided type that is adjacent to * the focus annotation in either to the left or right. Adjacent simply * means the last annotation of the passed in type that ends before the * start of the focus annotation (for the left side) or the first annotation * that starts after the end of the focus annotation (for the right side). * Thus, adacent refers to order of annotations at the annotation level * (e.g. give me the first annotation of type x to the left of the focus * annotation) and does not mean that the annotations are adjacenct at the * character offset level. * * <br> * <b>note:</b> This method runs <b>much</b> faster if the type of the * passed in annotation and the passed in type are the same. * * @param jCas * @param focusAnnotation * an annotation that you want to find an annotation adjacent to * this. * @param adjacentClass * the type of annotation that you want to find * @param adjacentBefore * if true then returns an annotation to the left of the passed * in annotation, otherwise an annotation to the right will be * returned. * @return an annotation of type adjacentType or null */ public static <T extends Annotation> T getAdjacentAnnotation(JCas jCas, Annotation focusAnnotation, Class<T> adjacentClass, boolean adjacentBefore) { try { Type adjacentType = UIMAUtil.getCasType(jCas, adjacentClass); if (focusAnnotation.getType().equals(adjacentType)) { FSIterator iterator = jCas.getAnnotationIndex(adjacentType).iterator(); iterator.moveTo(focusAnnotation); if (adjacentBefore) iterator.moveToPrevious(); else iterator.moveToNext(); return adjacentClass.cast(iterator.get()); } else { FSIterator cursor = jCas.getAnnotationIndex().iterator(); cursor.moveTo(focusAnnotation); if (adjacentBefore) { while (cursor.isValid()) { cursor.moveToPrevious(); Annotation annotation = (Annotation) cursor.get(); if (adjacentClass.isInstance(annotation) && annotation.getEnd() <= focusAnnotation.getBegin()) return adjacentClass .cast(annotation); } } else { while (cursor.isValid()) { cursor.moveToNext(); Annotation annotation = (Annotation) cursor.get(); if (adjacentClass.isInstance(annotation) && annotation.getBegin() >= focusAnnotation.getEnd()) return adjacentClass .cast(annotation); } } } } catch (NoSuchElementException nsee) { return null; } return null; } public static <T extends Annotation> AnnotationIndex getAnnotationIndex(JCas jCas, Class<T> cls) { return jCas.getAnnotationIndex(UIMAUtil.getCasType(jCas, cls)); } /** * Get the DocumentAnnotation for this JCas. * @param jCas The JCas for the document. * @return The DocumentAnnotation. */ public static DocumentAnnotation getDocument(JCas jCas) { return (DocumentAnnotation)jCas.getDocumentAnnotationFs(); } }
// $Id: Controller.java,v 1.18 2004/05/21 20:53:08 ray Exp $ // samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.swing; import java.awt.Component; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.Method; import javax.swing.JButton; import javax.swing.JComponent; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import com.samskivert.Log; import com.samskivert.swing.event.CommandEvent; /** * The controller class provides a basis for the separation of user interface * code into display code and control code. The display code lives in a panel * class (<code>javax.swing.JPanel</code> or something conceptually similar) * and the control code lives in an associated controller class. * * <p> The controller philosophy is thus: The panel class (and its UI * components) convert basic user interface actions into higher level actions * that more cleanly encapsulate the action desired by the user and they pass * those actions on to their controller. The controller then performs abstract * processing based on the users desires and the changing state of the * application and calls back to the panel to affect changes to the display. * * <p> Controllers also support the notion of scope. When a panel wishes to * post an action, it doesn't do it directly to the controller. Instead it does * it using a controller utility function called {@link #postAction}, which * searches up the user interface hierarchy looking for a component that * implements {@link ControllerProvider} which it will use to obtain the * controller "in scope" for that component. That controller is requested to * handle the action, but if it cannot handle the action, the next controller * up the chain is located and requested to process the action. * * <p> In this manner, a hierarchy of controllers (often just two: one * application wide and one for whatever particular mode the application is in * at the moment) can provide a set of services that are available to all user * interface elements in the entire application and in a way that doesn't * require tight connectedness between the UI elements and the controllers. */ public abstract class Controller implements ActionListener { /** * This action listener can be wired up to any action event generator * and it will take care of forwarding that event on to the controller * in scope for the component that generated the action event. * * <p> For example, wiring a button up to a dispatcher would look like * so: * * <pre> * JButton button = new JButton("Do thing"); * button.setActionCommand("dothing"); * button.addActionListener(Controller.DISPATCHER); * </pre> * * or, use the provided convenience function: * * <pre> * JButton button = * Controller.createActionButton("Do thing", "dothing"); * </pre> * * The controllers in scope would then be requested (in order) to * process the <code>dothing</code> action whenever the button was * clicked. */ public static final ActionListener DISPATCHER = new ActionListener() { public void actionPerformed (ActionEvent event) { Controller.postAction(event); } }; /** * Lets this controller know about the panel that it is controlling. */ public void setControlledPanel (final JComponent panel) { panel.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged (HierarchyEvent e) { boolean nowShowing = panel.isDisplayable(); //System.err.println("Controller." + Controller.this + // " nowShowing=" + nowShowing + // ", wasShowing=" + _showing); if (_showing != nowShowing) { _showing = nowShowing; if (_showing) { wasAdded(); } else { wasRemoved(); } } } boolean _showing = false; }); } /** * Called when the panel controlled by this controller was added to * the user interface hierarchy. This assumes that the controlled * panel made itself known to the controller via {@link * #setControlledPanel} (which is done automatically by {@link * ControlledPanel} and derived classes). */ public void wasAdded () { } /** * Called when the panel controlled by this controller was removed * from the user interface hierarchy. This assumes that the controlled * panel made itself known to the controller via {@link * #setControlledPanel} (which is done automatically by {@link * ControlledPanel} and derived classes). */ public void wasRemoved () { } /** * Instructs this controller to process this action event. When an action * is posted by a user interface element, it will be posted to the * controller in closest scope for that element. If that controller handles * the event, it should return true from this method to indicate that * processing should stop. If it cannot handle the event, it can return * false to indicate that the event should be propagated to the next * controller up the chain. * * <p> This method will be called on the AWT thread, so the controller can * safely manipulate user interface components while handling an action. * However, this means that action handling cannot block and should not * take an undue amount of time. If the controller needs to perform * complicated, lengthy processing it should do so with a separate thread, * for example via {@link com.samskivert.swing.util.TaskMaster}. * * <p> The default implementation of this method will reflect on the * controller class, looking for a method that matches the name of the * action event. For example, if the action was "exit" a method named * "exit" would be sought. A handler method must provide one of three * signatures: one accepting no arguments, one including only a reference * to the source object, or one including the source object and an extra * argument (which can be used only if the action event is an instance of * {@link CommandEvent}). For example: * * <pre> * public void cancelClicked (Object source); * public void textEntered (Object source, String text); * </pre> * * The arguments to the method can be as specific or as generic as desired * and reflection will perform the appropriate conversions at runtime. For * example, a method could be declared like so: * * <pre> * public void cancelClicked (JButton source); * </pre> * * One would have to ensure that the only action events generated with the * action command string "cancelClicked" were generated by JButton * instances if such a signature were used. * * @param action the action to be processed. * * @return true if the action was processed, false if it should be * propagated up to the next controller in scope. */ public boolean handleAction (ActionEvent action) { Object arg = null; if (action instanceof CommandEvent) { arg = ((CommandEvent)action).getArgument(); } return handleAction(action.getSource(), action.getActionCommand(), arg); } /** * A version of {@link #handleAction(ActionEvent)} with the parameters * broken out so that it can be used by non-Swing interface toolkits. */ public boolean handleAction (Object source, String action, Object arg) { Method method = null; Object[] args = null; try { // look for the appropriate method Method[] methods = getClass().getMethods(); int mcount = methods.length; for (int i = 0; i < mcount; i++) { if (methods[i].getName().equals(action) || // handle our old style of prepending "handle" methods[i].getName().equals("handle" + action)) { // see if we can generate the appropriate arguments args = generateArguments(methods[i], source, arg); // if we were able to, go ahead and use this method if (args != null) { method = methods[i]; break; } } } } catch (Exception e) { Log.warning("Error searching for action handler method " + "[controller=" + this + ", action=" + action + "]."); return false; } try { if (method != null) { method.invoke(this, args); return true; } else { return false; } } catch (Exception e) { Log.warning("Error invoking action handler [controller=" + this + ", action=" + action + "]."); Log.logStackTrace(e); // even though we choked, we still "handled" the action return true; } } /** * A convenience method for constructing and immediately handling an * event on this controller (via {@link #handleAction(ActionEvent)}). * * @return true if the controller knew how to handle the action, false * otherwise. */ public boolean handleAction (Component source, String command) { return handleAction(new ActionEvent(source, 0, command)); } /** * A convenience method for constructing and immediately handling an * event on this controller (via {@link #handleAction(ActionEvent)}). * * @return true if the controller knew how to handle the action, false * otherwise. */ public boolean handleAction (Component source, String command, Object arg) { return handleAction(new CommandEvent(source, command, arg)); } // documentation inherited from interface ActionListener public void actionPerformed (ActionEvent event) { handleAction(event); } /** * Used by {@link #handleAction} to generate arguments to the action * handler method. */ protected Object[] generateArguments ( Method method, Object source, Object argument) { // figure out what sort of arguments are required by the method Class[] atypes = method.getParameterTypes(); if (atypes == null || atypes.length == 0) { return new Object[0]; } else if (atypes.length == 1) { return new Object[] { source }; } else if (atypes.length == 2) { if (argument != null) { return new Object[] { source, argument }; } Log.warning("Unable to map argumentless event to handler method " + "that requires an argument [controller=" + this + ", method=" + method + ", source=" + source + "]."); } // we would have handled it, but we couldn't return null; } /** * Posts the specified action to the nearest controller in scope. The * controller search begins with the source component of the action and * traverses up the component tree looking for a controller to handle the * action. The controller location and action event processing is * guaranteed to take place on the AWT thread regardless of what thread * calls <code>postAction</code> and that processing will not occur * immediately but is instead appended to the AWT event dispatch queue for * processing. */ public static void postAction (ActionEvent action) { // slip things onto the event queue for later EventQueue.invokeLater(new ActionInvoker(action)); } /** * Like {@link #postAction(ActionEvent)} except that it constructs the * action event for you with the supplied source component and string * command. The <code>id</code> of the event will always be set to * zero. */ public static void postAction (Component source, String command) { // slip things onto the event queue for later ActionEvent event = new ActionEvent(source, 0, command); EventQueue.invokeLater(new ActionInvoker(event)); } /** * Like {@link #postAction(ActionEvent)} except that it constructs a * {@link CommandEvent} with the supplied source component, string * command and argument. */ public static void postAction ( Component source, String command, Object argument) { // slip things onto the event queue for later CommandEvent event = new CommandEvent(source, command, argument); EventQueue.invokeLater(new ActionInvoker(event)); } /** * Creates a button and configures it with the specified label and * action command and adds {@link #DISPATCHER} as an action listener. */ public static JButton createActionButton (String label, String command) { JButton button = new JButton(label); button.setActionCommand(command); button.addActionListener(DISPATCHER); return button; } /** * This class is used to dispatch action events to controllers within * the context of the AWT event dispatch mechanism. */ protected static class ActionInvoker implements Runnable { public ActionInvoker (ActionEvent action) { _action = action; } public void run () { // do some sanity checking on the source Object src = _action.getSource(); if (src == null || !(src instanceof Component)) { Log.warning("Requested to dispatch action on " + "non-component source [source=" + src + ", action=" + _action + "]."); return; } // scan up the component hierarchy looking for a controller on // which to dispatch this action for (Component source = (Component)src; source != null; source = source.getParent()) { if (!(source instanceof ControllerProvider)) { continue; } Controller ctrl = ((ControllerProvider)source).getController(); if (ctrl == null) { Log.warning("Provider returned null controller " + "[provider=" + source + "]."); continue; } try { // if the controller returns true, it handled the // action and we can call this business done if (ctrl.handleAction(_action)) { return; } } catch (Exception e) { Log.warning("Controller choked on action " + "[ctrl=" + ctrl + ", action=" + _action + "]."); Log.logStackTrace(e); } } // if we got here, we didn't find a controller Log.warning("Unable to find a controller to process action " + "[action=" + _action + "]."); } protected ActionEvent _action; } }
package no.jervell.jul; import no.jervell.animation.Animation; import no.jervell.animation.Timer; import no.jervell.swing.WheelView; import java.util.List; import java.util.Random; import java.util.ArrayList; public class GameLogic implements Animation, WheelAnimation.Listener, WheelSpinner.Target { private enum State { INIT, LOOP, WAIT_FOR_PERSON, WINNER, WAIT_FOR_BONUS, FINISHED } private PersonDAO personDAO; private Script script; private State state; private Random rnd = new Random(); private WheelView date; private WheelView person; private WheelView bonus; private WheelRowAnimator blink; public GameLogic( int[] days, Julekarenalender julekarenalender ) { this.personDAO = julekarenalender.personDAO; this.date = julekarenalender.dateWheel; this.person = julekarenalender.personWheel; this.bonus = julekarenalender.bonusWheel; this.blink = new WheelRowAnimator( person ); this.script = new Script( days ); populatePerson( julekarenalender ); setState( State.INIT ); } private void populatePerson( Julekarenalender julekarenalender ) { List<WheelView.Row> rows = new ArrayList<WheelView.Row>( person.getRows() ); for ( Person p : script.getPersonList() ) { rows.add( new WheelView.Row( p, julekarenalender.createPersonWheelRow(p) ) ); } person.setRows( rows ); } public void init( Timer timer ) { date.setEnabled( false ); person.setEnabled( false ); bonus.setEnabled( false ); if ( script.hasCurrent() ) { date.setYOffset( script.getDay() ); } setState( State.LOOP ); } public void move( Timer timer ) { rotateDateWheel(); switch ( state ) { case LOOP: if ( script.hasCurrent() ) { person.setEnabled( true ); setState( State.WAIT_FOR_PERSON ); } else { setState( State.FINISHED ); } break; case WINNER: blink.move( timer ); break; } } private void rotateDateWheel() { if ( script.hasCurrent() ) { double dateY = date.getYOffset(); double diff = script.getDay() - dateY; double absDiff = Math.abs( diff ); if ( absDiff > .001 ) { double move = Math.min( .02, absDiff ); date.setYOffset( dateY + move*Math.signum(diff) ); date.repaint(); } } } public Integer getTargetIndex( WheelView view ) { switch ( state ) { case WAIT_FOR_PERSON: if ( view == person ) { return script.getPerson(); } break; case WINNER: if ( view == person ) { return script.replacePerson(); } else if ( view == bonus ) { boolean repeatingDate = script.hasNext() && script.getDay() == script.getNextDay(); return bonus.getIndex( repeatingDate ? 1 : -1 ); // TODO: Constants? } break; } return null; } public void spinStarted( WheelView view, double velocity ) { System.out.println("--- spin started"); switch ( state ) { case WINNER: blink.stop(); if ( view == person ) { bonus.setEnabled( false ); setState( State.WAIT_FOR_PERSON ); } else if ( view == bonus ) { person.setEnabled( false ); setState( State.WAIT_FOR_BONUS ); } break; } } public void spinStopped( WheelView view ) { System.out.println("--- spin stopped"); switch ( state ) { case WAIT_FOR_PERSON: blink.start( script.getPerson() ); bonus.setEnabled( true ); setState( State.WINNER ); break; case WAIT_FOR_BONUS: bonus.setEnabled( false ); if ( script.move() ) { setState( State.LOOP ); } else { setState( State.FINISHED ); } break; } } private void setState( State state ) { System.out.println( ">>> " + state ); if ( state == State.FINISHED || state == State.WINNER ) { try { personDAO.persist(); } catch ( Exception e ) { System.err.println( "Unable to persist data. Reason: " + e ); } } this.state = state; } private class Script { private int pos; private int[] days; private Person[] winners; private List<Person> queue; private List<Person> personList; public Script( int[] days ) { this.days = days; this.winners = new Person[ days.length ]; this.pos = 0; init(); } private void init() { personList = getFilteredList( personDAO.getPersonList(), getFirstDay() ); queue = new ArrayList<Person>( personList ); for ( int i = 0; i < days.length; ++i ) { winners[ i ] = pickWinner( days[i], queue ); } } public List<Person> getPersonList() { return personList; } private List<Person> getFilteredList( List<Person> list, int minDay ) { List<Person> result = new ArrayList<Person>(); for ( Person p : list ) { if ( p.getDay() == 0 || p.getDay() >= minDay ) { result.add( p ); } } return result; } private int getFirstDay() { if ( days == null || days.length == 0 ) { return 0; } int min = days[0]; for ( int val : days ) { min = Math.min( min, val ); } return min; } private Person pickWinner( int day, List<Person> queue ) { Person winner = extractRiggedWinner( day, queue ); if ( winner == null ) { winner = extractRandomWinner( day, queue ); } if ( winner == null ) { winner = new Person(); winner.setDay( day ); winner.setName( "NOBODY" ); } return winner; } private Person extractRiggedWinner(int day, List<Person> queue ) { for ( Person p : queue ) { if ( p.getDay() == day ) { queue.remove( p ); return p; } } return null; } private Person extractRandomWinner( int day, List<Person> queue ) { if ( queue.size() > 0 ) { Person p = queue.remove( rnd.nextInt( queue.size() ) ); p.setDay( day ); return p; } return null; } public int getDay() { return date.getIndex( winners[ pos ].getDay() ); } public int getNextDay() { return date.getIndex( winners[ pos+1 ].getDay() ); } public int getPerson() { return person.getIndex( winners[ pos ] ); } public int replacePerson() { Person oldPerson = winners[ pos ]; winners[ pos ] = extractRandomWinner( oldPerson.getDay(), queue ); oldPerson.setDay( 0 ); return getPerson(); } public boolean hasCurrent() { return pos < days.length; } public boolean hasNext() { return pos+1 < days.length; } public boolean move() { if ( hasCurrent() ) { pos++; } return hasCurrent(); } } }
package org.ensembl.healthcheck.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.testcase.EnsTestCase; /** * Various database utilities. */ public final class DBUtils { private static final boolean USE_CONNECTION_POOLING = true; private static Logger logger = Logger.getLogger("HealthCheckLogger"); // hide constructor to stop instantiation private DBUtils() { } /** * Open a connection to the database. * * @param driverClassName * The class name of the driver to load. * @param databaseURL * The URL of the database to connect to. * @param user * The username to connect with. * @param password * Password for user. * @return A connection to the database, or null. */ public static Connection openConnection(String driverClassName, String databaseURL, String user, String password) { Connection con = null; if (USE_CONNECTION_POOLING) { con = ConnectionPool.getConnection(driverClassName, databaseURL, user, password); } else { try { Class.forName(driverClassName); Properties props = new Properties(); props.put("user", user); props.put("password", password); props.put("maxRows", "" + 100); con = DriverManager.getConnection(databaseURL, props); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // if use pooling return con; } // openConnection /** * Get a list of the database names for a particular connection. * * @param con * The connection to query. * @return An array of Strings containing the database names. */ public static String[] listDatabases(Connection con) { if (con == null) { logger.severe("Database connection is null"); } ArrayList dbNames = new ArrayList(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SHOW DATABASES"); while (rs.next()) { dbNames.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } String[] ret = new String[dbNames.size()]; return (String[]) dbNames.toArray(ret); } // listDatabases /** * Get a list of the database names that match a certain pattern for a * particular connection. * * @param conn * The connection to query. * @param regex * A regular expression to match. * @return An array of Strings containing the database names. */ public static String[] listDatabases(Connection conn, String regex) { Pattern pattern = null; Matcher matcher = null; if (conn == null) { logger.severe("Database connection is null"); } ArrayList dbMatches = new ArrayList(); pattern = Pattern.compile(regex); String[] allDBNames = listDatabases(conn); for (int i = 0; i < allDBNames.length; i++) { matcher = pattern.matcher(allDBNames[i]); if (matcher.matches()) { dbMatches.add(allDBNames[i]); } } // for i String[] ret = new String[dbMatches.size()]; return (String[]) dbMatches.toArray(ret); } // listDatabases /** * Compare a list of ResultSets to see if there are any differences. Note that * if the ResultSets are large and/or there are many of them, this may take a * long time! * * @return The number of differences. * @param testCase * The test case that is calling the comparison. Used for * ReportManager. * @param resultSetGroup * The list of ResultSets to compare */ public static boolean compareResultSetGroup(List resultSetGroup, EnsTestCase testCase) { boolean same = true; // avoid comparing the same two ResultSets more than once // i.e. only need the upper-right triangle of the comparison matrix int size = resultSetGroup.size(); for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { ResultSet rsi = (ResultSet) resultSetGroup.get(i); ResultSet rsj = (ResultSet) resultSetGroup.get(j); same &= compareResultSets(rsi, rsj, testCase, "", true, true, ""); } } return same; } // compareResultSetGroup /** * Compare two ResultSets. * * @return True if all the following are true: * <ol> * <li>rs1 and rs2 have the same number of columns</li> * <li>The name and type of each column in rs1 is equivalent to the * corresponding column in rs2.</li> * <li>All the rows in rs1 have the same type and value as the * corresponding rows in rs2.</li> * </ol> * @param testCase * The test case calling the comparison; used in ReportManager. * @param text * Additional text to put in any error reports. * @param rs1 * The first ResultSet to compare. * @param rs2 * The second ResultSet to compare. * @param reportErrors * If true, error details are stored in ReportManager as they are * found. * @param singleTableName * If comparing 2 result sets from a single table (or from a DESCRIBE * table) this should be the name of the table, to be output in any * error text. Otherwise "". */ public static boolean compareResultSets(ResultSet rs1, ResultSet rs2, EnsTestCase testCase, String text, boolean reportErrors, boolean warnNull, String singleTableName) { return compareResultSets(rs1, rs2, testCase, text, reportErrors, warnNull, singleTableName, null); } public static boolean compareResultSets(ResultSet rs1, ResultSet rs2, EnsTestCase testCase, String text, boolean reportErrors, boolean warnNull, String singleTableName, int[] columns) { // quick tests first // Check for object equality if (rs1.equals(rs2)) { return true; } try { // get some information about the ResultSets String name1 = getShortDatabaseName(rs1.getStatement().getConnection()); String name2 = getShortDatabaseName(rs2.getStatement().getConnection()); // Check for same column count, names and types ResultSetMetaData rsmd1 = rs1.getMetaData(); ResultSetMetaData rsmd2 = rs2.getMetaData(); if (rsmd1.getColumnCount() != rsmd2.getColumnCount() && columns == null) { ReportManager.problem(testCase, name1, "Column counts differ " + singleTableName + " " + name1 + ": " + rsmd1.getColumnCount() + " " + name2 + ": " + rsmd2.getColumnCount()); return false; // Deliberate early return for performance // reasons } if (columns == null) { columns = new int[rsmd1.getColumnCount()]; for (int i = 0; i < columns.length; i++) { columns[i] = i + 1; } } for (int j = 0; j < columns.length; j++) { int i = columns[j]; // note columns indexed from l if (!((rsmd1.getColumnName(i)).equals(rsmd2.getColumnName(i)))) { ReportManager.problem(testCase, name1, "Column names differ for " + singleTableName + " column " + i + " - " + name1 + ": " + rsmd1.getColumnName(i) + " " + name2 + ": " + rsmd2.getColumnName(i)); // Deliberate early return for performance reasons return false; } if (rsmd1.getColumnType(i) != rsmd2.getColumnType(i)) { ReportManager.problem(testCase, name1, "Column types differ for " + singleTableName + " column " + i + " - " + name1 + ": " + rsmd1.getColumnType(i) + " " + name2 + ": " + rsmd2.getColumnType(i)); return false; // Deliberate early return for performance // reasons } } // for column // make sure both cursors are at the start of the ResultSet // (default is before the start) rs1.beforeFirst(); rs2.beforeFirst(); // if quick checks didn't cause return, try comparing row-wise int row = 1; while (rs1.next()) { if (rs2.next()) { for (int j = 0; j < columns.length; j++) { int i = columns[j]; // note columns indexed from l if (!compareColumns(rs1, rs2, i, warnNull)) { String str = name1 + " and " + name2 + text + " " + singleTableName + " differ at row " + row + " column " + i + " (" + rsmd1.getColumnName(i) + ")" + " Values: " + Utils.truncate(rs1.getString(i), 250, true) + ", " + Utils.truncate(rs2.getString(i), 250, true); if (reportErrors) { ReportManager.problem(testCase, name1, str); } return false; } } row++; } else { // rs1 has more rows than rs2 ReportManager.problem(testCase, name1, singleTableName + " (or definition) has more rows in " + name1 + " than in " + name2); return false; } } // while rs1 // if both ResultSets are the same, then we should be at the end of // both, i.e. .next() should return false if (rs1.next()) { if (reportErrors) { ReportManager.problem(testCase, name1, name1 + " " + singleTableName + " has additional rows that are not in " + name2); } return false; } else if (rs2.next()) { if (reportErrors) { ReportManager.problem(testCase, name2, name2 + " " + singleTableName + " has additional rows that are not in " + name1); } return false; } } catch (SQLException se) { se.printStackTrace(); } return true; } // compareResultSets /** * Compare a particular column in two ResultSets. * * @param rs1 * The first ResultSet to compare. * @param rs2 * The second ResultSet to compare. * @param i * The index of the column to compare. * @return True if the type and value of the columns match. */ public static boolean compareColumns(ResultSet rs1, ResultSet rs2, int i, boolean warnNull) { try { ResultSetMetaData rsmd = rs1.getMetaData(); Connection con1 = rs1.getStatement().getConnection(); Connection con2 = rs2.getStatement().getConnection(); if (rs1.getObject(i) == null) { if (warnNull) { System.out.println("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con1)); } return (rs2.getObject(i) == null); // true if both are null } if (rs2.getObject(i) == null) { if (warnNull) { System.out.println("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i) + " in " + DBUtils.getShortDatabaseName(con2)); } return (rs1.getObject(i) == null); // true if both are null } // Note deliberate early returns for performance reasons switch (rsmd.getColumnType(i)) { case Types.INTEGER: return rs1.getInt(i) == rs2.getInt(i); case Types.SMALLINT: return rs1.getInt(i) == rs2.getInt(i); case Types.TINYINT: return rs1.getInt(i) == rs2.getInt(i); case Types.VARCHAR: return rs1.getString(i).equals(rs2.getString(i)); case Types.FLOAT: return rs1.getFloat(i) == rs2.getFloat(i); case Types.DOUBLE: return rs1.getDouble(i) == rs2.getDouble(i); case Types.TIMESTAMP: return rs1.getTimestamp(i).equals(rs2.getTimestamp(i)); default: // treat everything else as a String (should deal with ENUM and // TEXT) if (rs1.getString(i) == null || rs2.getString(i) == null) { return true; } else { return rs1.getString(i).equals(rs2.getString(i)); } } // switch } catch (SQLException se) { se.printStackTrace(); } return true; } // compareColumns /** * Print a ResultSet to standard out. Optionally limit the number of rows. * * @param maxRows * The maximum number of rows to print. -1 to print all rows. * @param rs * The ResultSet to print. */ public static void printResultSet(ResultSet rs, int maxRows) { int row = 0; try { ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { System.out.print(rs.getString(i) + "\t"); } System.out.println(""); if (maxRows != -1 && ++row >= maxRows) { break; } } } catch (SQLException se) { se.printStackTrace(); } } // printResultSet /** * Gets the database name, without the jdbc:// prefix. * * @param con * The Connection to query. * @return The name of the database (everything after the last / in the JDBC * URL). */ public static String getShortDatabaseName(Connection con) { String url = null; try { url = con.getMetaData().getURL(); } catch (SQLException se) { se.printStackTrace(); } String name = url.substring(url.lastIndexOf('/') + 1); return name; } // getShortDatabaseName /** * Convert properties used by Healthcheck into properties suitable for ensj; * ensj properties host, port, user, password are converted. Note ensj * property database is <em>not</em> set. * * @return A Properties object containing host, port, user and password NOT * database. * @param testRunnerProps * A set of properties in the format used by HealthCheck, e.g. * databaseURL etc. */ public static Properties convertHealthcheckToEnsjProperties(Properties testRunnerProps) { Properties props = new Properties(); // user & password are straightforward props.put("user", testRunnerProps.get("user")); props.put("password", testRunnerProps.get("password")); // get host and port from URL // java.net.URL doesn't support JDBC URLs(!) so we have to hack things // a bit String dbUrl = (String) testRunnerProps.get("databaseURL"); java.net.URL url = null; try { url = new java.net.URL("http" + dbUrl.substring(10)); // strip off // jdbc:mysql: // and // pretend it's http } catch (java.net.MalformedURLException e) { e.printStackTrace(); } if (url != null) { String host = url.getHost(); String port = "" + url.getPort(); props.put("host", host); props.put("port", port); } else { logger.severe("Unable to get host/port from url"); } return props; } // convertHealthcheckToEnsjProperties /** * Convert properties used by Healthcheck into properties suitable for ensj; * ensj properties host, port, user, password are converted. Note ensj * property database is <em>not</em> set. Input properties are obtained from * System.properties. * * @return A Properties object containing host, port, user and password NOT * database. */ public static Properties convertHealthcheckToEnsjProperties() { return convertHealthcheckToEnsjProperties(System.getProperties()); } /** * Generate a name for a temporary database. Should be fairly unique; name is * _temp_{user}_{time} where user is current user and time is current time in * ms. * * @return The temporary name. Will not have any spaces. */ public static String generateTempDatabaseName() { StringBuffer buf = new StringBuffer("_temp_"); buf.append(System.getProperty("user.name")); buf.append("_" + System.currentTimeMillis()); String str = buf.toString(); str = str.replace(' ', '_'); // filter any spaces logger.fine("Generated temporary database name: " + str); return str; } /** * Get a list of all the table names. * * @param con * The database connection to use. * @return An array of Strings representing the names of the tables, obtained * from the SHOW TABLES command. */ public static String[] getTableNames(Connection con) { List result = new ArrayList(); if (con == null) { logger.severe("getTableNames(): Database connection is null"); } try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SHOW TABLES"); while (rs.next()) { result.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return (String[]) result.toArray(new String[result.size()]); } /** * Get a list of the table names that match a particular SQL pattern. * * @param con * The database connection to use. * @param pattern * The SQL pattern to match the table names against. * @return An array of Strings representing the names of the tables. */ public static String[] getTableNames(Connection con, String pattern) { List result = new ArrayList(); if (con == null) { logger.severe("getTableNames(): Database connection is null"); } try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SHOW TABLES LIKE '" + pattern + "'"); while (rs.next()) { result.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return (String[]) result.toArray(new String[result.size()]); } /** * List the columns in a particular table. * * @param table * The name of the table to list. * @param con * The connection to use. * @return A List of Strings representing the column names. */ public static List getColumnsInTable(Connection con, String table) { List result = new ArrayList(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("DESCRIBE " + table); while (rs.next()) { result.add(rs.getString(1)); } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return result; } /** * List the columns and their types in a particular table. * * @param table * The name of the table to list. * @param con * The connection to use. * @param typeFilter * If not null, only return columns whose types start with this * string (case insensitive). * @return A List of 2-element String[] arrays representing the column names * and their types. */ public static List getColumnsAndTypesInTable(Connection con, String table, String typeFilter) { List result = new ArrayList(); typeFilter = typeFilter.toLowerCase(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("DESCRIBE " + table); while (rs.next()) { String[] nameType = new String[2]; nameType[0] = rs.getString(1); nameType[1] = rs.getString(2); if (nameType[1].toLowerCase().startsWith(typeFilter)) { result.add(nameType); System.out.println(nameType[0] + " " + nameType[1]); } } rs.close(); stmt.close(); } catch (SQLException se) { logger.severe(se.getMessage()); } return result; } /** * Execute SQL and writes results to ReportManager.info(). * * @param testCase * testCase which created the sql statement * @param con * connection to execute sql on. * @param sql * sql statement to execute. */ public static void printRows(EnsTestCase testCase, Connection con, String sql) { try { ResultSet rs = con.createStatement().executeQuery(sql); if (rs.next()) { int nCols = rs.getMetaData().getColumnCount(); StringBuffer line = new StringBuffer(); do { line.delete(0, line.length()); for (int i = 1; i <= nCols; ++i) { line.append(rs.getString(i)); if (i < nCols) { line.append("\t"); } } ReportManager.info(testCase, con, line.toString()); } while (rs.next()); } } catch (SQLException e) { e.printStackTrace(); } } } // DBUtils
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.text.FieldPosition; import java.util.Calendar; import java.util.Date; import com.samskivert.Log; /** * Used by various services to generate audit logs which can be useful for auditing, debugging and * other logly necessities. The audit logger automatically rolls over its logs at midnight to * facilitate the collection, processing and possible archiving of the logs. */ public class AuditLogger { /** * Creates an audit logger that logs to the specified file. */ public AuditLogger (File path, String filename) { this(new File(path, filename)); } /** * Creates an audit logger that logs to the specified file. */ public AuditLogger (File fullpath) { _logPath = fullpath; openLog(true); // update the day format _dayStamp = _dayFormat.format(new Date()); scheduleNextRolloverCheck(); } /** * Writes the supplied message to the log, prefixed by a date and timestamp. A newline will be * appended to the message. */ public synchronized void log (String message) { // construct the message StringBuffer buf = new StringBuffer(message.length() + TIMESTAMP_LENGTH); _format.format(new Date(), buf, _fpos); buf.append(message); // and write it to the log boolean wrote = false; if (_logWriter != null) { _logWriter.println(buf.toString()); wrote = !_logWriter.checkError(); } // log an error if we failed to write the log message if (!wrote) { // be careful about logging zillions of errors if something bad happens to our log file if (_throttle.throttleOp()) { _throttled++; } else { if (_throttled > 0) { Log.warning("Suppressed " + _throttled + " intervening error messages."); _throttled = 0; } Log.warning("Failed to write audit log message [file=" + _logPath + ", msg=" + message + "]."); } } } /** * Closes this audit log (generally only done when the server is shutting down. */ public synchronized void close () { if (_logWriter != null) { log("log_closed"); _logWriter.close(); _logWriter = null; } } /** * Opens our log file, sets up our print writer and writes a message to it indicating that it * was opened. */ protected void openLog (boolean freakout) { try { // create our file writer to which we'll log FileOutputStream fout = new FileOutputStream(_logPath, true); OutputStreamWriter writer = new OutputStreamWriter(fout, "UTF8"); _logWriter = new PrintWriter(new BufferedWriter(writer), true); // log a standard message log("log_opened " + _logPath); } catch (IOException ioe) { String errmsg = "Unable to open audit log '" + _logPath + "'"; if (freakout) { throw new RuntimeException(errmsg, ioe); } else { Log.warning(errmsg + " [ioe=" + ioe + "]."); } } } /** * Check to see if it's time to roll over the log file. */ protected synchronized void checkRollOver () { // check to see if we should roll over the log String newDayStamp = _dayFormat.format(new Date()); // hey! we need to roll it over! if (!newDayStamp.equals(_dayStamp)) { log("log_closed"); _logWriter.close(); _logWriter = null; // rename the old file String npath = _logPath.getPath() + "." + _dayStamp; if (!_logPath.renameTo(new File(npath))) { Log.warning("Failed to rename audit log file [path=" + _logPath + ", npath=" + npath + "]."); } // open our new log file openLog(false); // and set the next day stamp _dayStamp = newDayStamp; } scheduleNextRolloverCheck(); } /** * Schedule the next check to see if we should roll the logs over. */ protected void scheduleNextRolloverCheck () { Calendar cal = Calendar.getInstance(); // schedule the next check for the next hour mark long nextCheck = (1000L - cal.get(Calendar.MILLISECOND)) + (59L - cal.get(Calendar.SECOND)) * 1000L + (59L - cal.get(Calendar.MINUTE)) * (1000L * 60L); _rollover.schedule(nextCheck); } /** The interval that rolls over the log file. */ protected Interval _rollover = new Interval() { public void expired () { checkRollOver(); } }; /** The path to our log file. */ protected File _logPath; /** We actually write to this feller here. */ protected PrintWriter _logWriter; /** Suppress freakouts if our log file becomes hosed. */ protected Throttle _throttle = new Throttle(2, 5*60*1000L); /** Used to count the number of throttled messages for reporting. */ protected int _throttled; /** The daystamp of the log file we're currently writing to. */ protected String _dayStamp; /** Used to format log file suffixes. */ protected SimpleDateFormat _dayFormat = new SimpleDateFormat("yyyyMMdd"); /** Used to format timestamps. */ protected SimpleDateFormat _format = new SimpleDateFormat(TIMESTAMP_FORMAT); /** Annoying parameter required by the Format.format() method that appends to a string * buffer. */ protected FieldPosition _fpos = new FieldPosition(SimpleDateFormat.DATE_FIELD); /** Timestamp format used on all log messages. */ protected static final String TIMESTAMP_FORMAT = "yyyy/MM/dd HH:mm:ss:SSS "; /** The length of the timestamp format. */ protected static final int TIMESTAMP_LENGTH = TIMESTAMP_FORMAT.length(); }
package org.jcodings.unicode; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import org.jcodings.ApplyAllCaseFoldFunction; import org.jcodings.CaseFoldCodeItem; import org.jcodings.CodeRange; import org.jcodings.Config; import org.jcodings.IntHolder; import org.jcodings.MultiByteEncoding; import org.jcodings.constants.CharacterType; import org.jcodings.exception.CharacterPropertyException; import org.jcodings.exception.ErrorMessages; import org.jcodings.util.ArrayReader; import org.jcodings.util.CaseInsensitiveBytesHash; import org.jcodings.util.IntArrayHash; import org.jcodings.util.IntHash; public abstract class UnicodeEncoding extends MultiByteEncoding { private static final int MAX_WORD_LENGTH = Config.USE_UNICODE_PROPERTIES ? 44 : 6; private static final int PROPERTY_NAME_MAX_SIZE = MAX_WORD_LENGTH + 1; static final int I_WITH_DOT_ABOVE = 0x0130; static final int DOTLESS_i = 0x0131; static final int DOT_ABOVE = 0x0307; protected UnicodeEncoding(String name, int minLength, int maxLength, int[]EncLen, int[][]Trans) { // ASCII type tables for all Unicode encodings super(name, minLength, maxLength, EncLen, Trans, UNICODE_ISO_8859_1_CTypeTable); isUnicode = true; } protected UnicodeEncoding(String name, int minLength, int maxLength, int[]EncLen) { this(name, minLength, maxLength, EncLen, null); } @Override public String getCharsetName() { return new String(getName()); } // onigenc_unicode_is_code_ctype @Override public boolean isCodeCType(int code, int ctype) { if (Config.USE_UNICODE_PROPERTIES) { if (ctype <= CharacterType.MAX_STD_CTYPE && code < 256) return isCodeCTypeInternal(code, ctype); } else { if (code < 256) return isCodeCTypeInternal(code, ctype); } if (ctype > UnicodeProperties.CodeRangeTable.length) throw new InternalError(ErrorMessages.ERR_TYPE_BUG); return CodeRange.isInCodeRange(UnicodeProperties.CodeRangeTable[ctype].getRange(), code); } // onigenc_unicode_ctype_code_range protected final int[]ctypeCodeRange(int ctype) { if (ctype >= UnicodeProperties.CodeRangeTable.length) throw new InternalError(ErrorMessages.ERR_TYPE_BUG); return UnicodeProperties.CodeRangeTable[ctype].getRange(); } // onigenc_unicode_property_name_to_ctype @Override public int propertyNameToCType(byte[]name, int p, int end) { byte[]buf = new byte[PROPERTY_NAME_MAX_SIZE]; int len = 0; for(int p_ = p; p_ < end; p_+= length(name, p_, end)) { int code = mbcToCode(name, p_, end); if (code == ' ' || code == '-' || code == '_') continue; if (code >= 0x80) throw new CharacterPropertyException(ErrorMessages.ERR_INVALID_CHAR_PROPERTY_NAME); buf[len++] = (byte)code; if (len >= PROPERTY_NAME_MAX_SIZE) throw new CharacterPropertyException(ErrorMessages.ERR_INVALID_CHAR_PROPERTY_NAME, name, p, end); } Integer ctype = CTypeName.CTypeNameHash.get(buf, 0, len); if (ctype == null) throw new CharacterPropertyException(ErrorMessages.ERR_INVALID_CHAR_PROPERTY_NAME, name, p, end); return ctype; } // onigenc_unicode_mbc_case_fold @Override public int mbcCaseFold(int flag, byte[]bytes, IntHolder pp, int end, byte[]fold) { int p = pp.value; int foldP = 0; int code = mbcToCode(bytes, p, end); int len = length(bytes, p, end); pp.value += len; if (Config.USE_UNICODE_CASE_FOLD_TURKISH_AZERI) { if ((flag & Config.CASE_FOLD_TURKISH_AZERI) != 0) { if (code == 'I') { return codeToMbc(DOTLESS_i, fold, foldP); } else if (code == I_WITH_DOT_ABOVE) { return codeToMbc('i', fold, foldP); } } } CodeList to = CaseFold.Hash.get(code); if (to != null) { if (to.codes.length == 1) { return codeToMbc(to.codes[0], fold, foldP); } else { int rlen = 0; for (int i=0; i<to.codes.length; i++) { len = codeToMbc(to.codes[i], fold, foldP); foldP += len; rlen += len; } return rlen; } } for (int i=0; i<len; i++) { fold[foldP++] = bytes[p++]; } return len; } // onigenc_unicode_apply_all_case_fold @Override public void applyAllCaseFold(int flag, ApplyAllCaseFoldFunction fun, Object arg) { /* if (CaseFoldInited == 0) init_case_fold_table(); */ int[]code = new int[]{0}; for (int i=0; i<CaseUnfold11.From.length; i++) { int from = CaseUnfold11.From[i]; CodeList to = CaseUnfold11.To[i]; for (int j=0; j<to.codes.length; j++) { code[0] = from; fun.apply(to.codes[j], code, 1, arg); code[0] = to.codes[j]; fun.apply(from, code, 1, arg); for (int k=0; k<j; k++) { code[0] = to.codes[k]; fun.apply(to.codes[j], code, 1, arg); code[0] = to.codes[j]; fun.apply(to.codes[k], code, 1, arg); } } } if (Config.USE_UNICODE_CASE_FOLD_TURKISH_AZERI && (flag & Config.CASE_FOLD_TURKISH_AZERI) != 0) { code[0] = DOTLESS_i; fun.apply('I', code, 1, arg); code[0] = 'I'; fun.apply(DOTLESS_i, code, 1, arg); code[0] = I_WITH_DOT_ABOVE; fun.apply('i', code, 1, arg); code[0] = 'i'; fun.apply(I_WITH_DOT_ABOVE, code, 1, arg); } else { for (int i=0; i<CaseUnfold11.Locale_From.length; i++) { int from = CaseUnfold11.Locale_From[i]; CodeList to = CaseUnfold11.Locale_To[i]; for (int j=0; j<to.codes.length; j++) { code[0] = from; fun.apply(to.codes[j], code, 1, arg); code[0] = to.codes[j]; fun.apply(from, code, 1, arg); for (int k = 0; k<j; k++) { code[0] = to.codes[k]; fun.apply(to.codes[j], code, 1, arg); code[0] = to.codes[j]; fun.apply(to.codes[k], code, 1, arg); } } } } // USE_UNICODE_CASE_FOLD_TURKISH_AZERI if ((flag & Config.INTERNAL_ENC_CASE_FOLD_MULTI_CHAR) != 0) { for (int i=0; i<CaseUnfold12.From.length; i++) { int[]from = CaseUnfold12.From[i]; CodeList to = CaseUnfold12.To[i]; for (int j=0; j<to.codes.length; j++) { fun.apply(to.codes[j], from, 2, arg); for (int k=0; k<to.codes.length; k++) { if (k == j) continue; code[0] = to.codes[k]; fun.apply(to.codes[j], code, 1, arg); } } } if (!Config.USE_UNICODE_CASE_FOLD_TURKISH_AZERI || (flag & Config.CASE_FOLD_TURKISH_AZERI) == 0) { for (int i=0; i<CaseUnfold12.Locale_From.length; i++) { int[]from = CaseUnfold12.Locale_From[i]; CodeList to = CaseUnfold12.Locale_To[i]; for (int j=0; j<to.codes.length; j++) { fun.apply(to.codes[j], from, 2, arg); for (int k=0; k<to.codes.length; k++) { if (k == j) continue; code[0] = to.codes[k]; fun.apply(to.codes[j], code, 1, arg); } } } } // !USE_UNICODE_CASE_FOLD_TURKISH_AZERI for (int i=0; i<CaseUnfold13.From.length; i++) { int[]from = CaseUnfold13.From[i]; CodeList to = CaseUnfold13.To[i]; for (int j=0; j<to.codes.length; j++) { fun.apply(to.codes[j], from, 3, arg); for (int k=0; k<to.codes.length; k++) { if (k == j) continue; code[0] = to.codes[k]; fun.apply(to.codes[j], code, 1, arg); } } } } // INTERNAL_ENC_CASE_FOLD_MULTI_CHAR } // onigenc_unicode_get_case_fold_codes_by_str @Override public CaseFoldCodeItem[]caseFoldCodesByString(int flag, byte[]bytes, int p, int end) { int code = mbcToCode(bytes, p, end); int len = length(bytes, p, end); if (Config.USE_UNICODE_CASE_FOLD_TURKISH_AZERI) { if ((flag & Config.CASE_FOLD_TURKISH_AZERI) != 0) { if (code == 'I') { return new CaseFoldCodeItem[]{new CaseFoldCodeItem(len, 1, new int[]{DOTLESS_i})}; } else if(code == I_WITH_DOT_ABOVE) { return new CaseFoldCodeItem[]{new CaseFoldCodeItem(len, 1, new int[]{'i'})}; } else if(code == DOTLESS_i) { return new CaseFoldCodeItem[]{new CaseFoldCodeItem(len, 1, new int[]{'I'})}; } else if(code == 'i') { return new CaseFoldCodeItem[]{new CaseFoldCodeItem(len, 1, new int[]{I_WITH_DOT_ABOVE})}; } } } // USE_UNICODE_CASE_FOLD_TURKISH_AZERI int n = 0; int fn = 0; CodeList to = CaseFold.Hash.get(code); CaseFoldCodeItem[]items = null; if (to != null) { items = new CaseFoldCodeItem[Config.ENC_GET_CASE_FOLD_CODES_MAX_NUM]; if (to.codes.length == 1) { int origCode = code; items[0] = new CaseFoldCodeItem(len, 1, new int[]{to.codes[0]}); n++; code = to.codes[0]; to = CaseUnfold11.Hash.get(code); if (to != null) { for (int i=0; i<to.codes.length; i++) { if (to.codes[i] != origCode) { items[n] = new CaseFoldCodeItem(len, 1, new int[]{to.codes[i]}); n++; } } } } else if ((flag & Config.INTERNAL_ENC_CASE_FOLD_MULTI_CHAR) != 0) { int[][]cs = new int[3][4]; int[]ncs = new int[3]; for (fn=0; fn<to.codes.length; fn++) { cs[fn][0] = to.codes[fn]; CodeList z3 = CaseUnfold11.Hash.get(cs[fn][0]); if (z3 != null) { for (int i=0; i<z3.codes.length; i++) { cs[fn][i+1] = z3.codes[i]; } ncs[fn] = z3.codes.length + 1; } else { ncs[fn] = 1; } } if (fn == 2) { for (int i=0; i<ncs[0]; i++) { for (int j=0; j<ncs[1]; j++) { items[n] = new CaseFoldCodeItem(len, 2, new int[]{cs[0][i], cs[1][j]}); n++; } } CodeList z2 = CaseUnfold12.Hash.get(to.codes); if (z2 != null) { for (int i=0; i<z2.codes.length; i++) { if (z2.codes[i] == code) continue; items[n] = new CaseFoldCodeItem(len, 1, new int[]{z2.codes[i]}); n++; } } } else { for (int i=0; i<ncs[0]; i++) { for (int j=0; j<ncs[1]; j++) { for (int k=0; k<ncs[2]; k++) { items[n] = new CaseFoldCodeItem(len, 3, new int[]{cs[0][i], cs[1][j], cs[2][k]}); n++; } } } CodeList z2 = CaseUnfold13.Hash.get(to.codes); if (z2 != null) { for (int i=0; i<z2.codes.length; i++) { if (z2.codes[i] == code) continue; items[n] = new CaseFoldCodeItem(len, 1, new int[]{z2.codes[i]}); n++; } } } /* multi char folded code is not head of another folded multi char */ flag = 0; /* DISABLE_CASE_FOLD_MULTI_CHAR(flag); */ } } else { to = CaseUnfold11.Hash.get(code); if (to != null) { items = new CaseFoldCodeItem[Config.ENC_GET_CASE_FOLD_CODES_MAX_NUM]; for (int i=0; i<to.codes.length; i++) { items[n] = new CaseFoldCodeItem(len, 1, new int[]{to.codes[i]}); n++; } } } if ((flag & Config.INTERNAL_ENC_CASE_FOLD_MULTI_CHAR) != 0) { if (items == null) items = new CaseFoldCodeItem[Config.ENC_GET_CASE_FOLD_CODES_MAX_NUM]; p += len; if (p < end) { final int codes0 = code; final int codes1; code = mbcToCode(bytes, p, end); to = CaseFold.Hash.get(code); if (to != null && to.codes.length == 1) { codes1 = to.codes[0]; } else { codes1 = code; } int clen = length(bytes, p, end); len += clen; CodeList z2 = CaseUnfold12.Hash.get(codes0, codes1); if (z2 != null) { for (int i=0; i<z2.codes.length; i++) { items[n] = new CaseFoldCodeItem(len, 1, new int[]{z2.codes[i]}); n++; } } p += clen; if (p < end) { final int codes2; code = mbcToCode(bytes, p, end); to = CaseFold.Hash.get(code); if (to != null && to.codes.length == 1) { codes2 = to.codes[0]; } else { codes2 = code; } clen = length(bytes, p, end); len += clen; z2 = CaseUnfold13.Hash.get(codes0, codes1, codes2); if (z2 != null) { for (int i=0; i<z2.codes.length; i++) { items[n] = new CaseFoldCodeItem(len, 1, new int[]{z2.codes[i]}); n++; } } } } } if (items == null || n == 0) return EMPTY_FOLD_CODES; if (n < items.length) { CaseFoldCodeItem [] tmp = new CaseFoldCodeItem[n]; System.arraycopy(items, 0, tmp, 0, n); return tmp; } else { return items; } } static final int CASE_MAPPING_SLACK = 12; @Override public final int caseMap(IntHolder flagP, byte[] bytes, IntHolder pp, int end, byte[] to, int toP, int toEnd) { int flags = flagP.value; int toStart = toP; toEnd -= CASE_MAPPING_SLACK; flags |= (flags & (Config.CASE_UPCASE | Config.CASE_DOWNCASE)) << Config.CASE_SPECIAL_OFFSET; while (pp.value < end && toP <= toEnd) { int length = length(bytes, pp.value, end); if (length < 0) return length; int code = mbcToCode(bytes, pp.value, end); pp.value += length; if (code <= 'z') { if (code >= 'a' && code <= 'z') { if ((flags & Config.CASE_UPCASE) != 0) { flags |= Config.CASE_MODIFIED; if ((flags & Config.CASE_FOLD_TURKISH_AZERI) != 0 && code == 'i') code = I_WITH_DOT_ABOVE; else code += 'A' - 'a'; } } else if (code >= 'A' && code <= 'Z') { if ((flags & (Config.CASE_DOWNCASE | Config.CASE_FOLD)) != 0) { flags |= Config.CASE_MODIFIED; if ((flags & Config.CASE_FOLD_TURKISH_AZERI) != 0 && code == 'I') code = DOTLESS_i; else code += 'a' - 'A'; } } } else if ((flags & Config.CASE_ASCII_ONLY) == 0 && code >= 0x00B5) { CodeList folded; if (code == I_WITH_DOT_ABOVE) { if ((flags & (Config.CASE_DOWNCASE | Config.CASE_FOLD)) != 0) { flags |= Config.CASE_MODIFIED; code = 'i'; if ((flags & Config.CASE_FOLD_TURKISH_AZERI) == 0) { toP += codeToMbc(code, to, toP); code = DOT_ABOVE; } } } else if (code == DOTLESS_i) { if ((flags & Config.CASE_UPCASE) != 0) { flags |= Config.CASE_MODIFIED; code = 'I'; } } else if ((folded = CaseFold.Hash.get(code)) != null) { if ((flags & Config.CASE_TITLECASE) != 0 && (folded.flags & Config.CASE_IS_TITLECASE) != 0) { } else if ((flags & folded.flags) != 0) { int[]codes; boolean specialCopy = false; flags |= Config.CASE_MODIFIED; if ((flags & folded.flags & Config.CASE_SPECIALS) != 0) { int specialStart = (folded.flags & Config.SpecialIndexMask) >>> Config.SpecialIndexShift; if ((folded.flags & Config.CASE_IS_TITLECASE) != 0) { if ((flags & (Config.CASE_UPCASE | Config.CASE_DOWNCASE)) == (Config.CASE_UPCASE | Config.CASE_DOWNCASE)) specialCopy = true; else specialStart++; } if (!specialCopy && (folded.flags & Config.CASE_TITLECASE) != 0) { if ((flags & Config.CASE_TITLECASE) != 0) specialCopy = true; else specialStart++; } if (!specialCopy && (folded.flags & Config.CASE_DOWN_SPECIAL) != 0) { if ((flags & Config.CASE_DOWN_SPECIAL) == 0) specialStart++; } codes = CaseMappingSpecials.Values.get(specialStart); } else { codes = folded.codes; } code = codes[0]; for (int i = 1; i < codes.length; i++) { toP += codeToMbc(code, to, toP); code = codes[i]; } } } else if ((folded = CaseUnfold11.Hash.get(code)) != null && (flags & folded.flags) != 0) { flags |= Config.CASE_MODIFIED; code = folded.codes[(flags & folded.flags & Config.CASE_TITLECASE) != 0 ? 1 : 0]; } } toP += codeToMbc(code, to, toP); if ((flags & Config.CASE_TITLECASE) != 0) { flags ^= (Config.CASE_UPCASE | Config.CASE_DOWNCASE | Config.CASE_TITLECASE | Config.CASE_UP_SPECIAL | Config.CASE_DOWN_SPECIAL);} } // while flagP.value = flags; return toP - toStart; } static final short UNICODE_ISO_8859_1_CTypeTable[] = { 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x420c, 0x4209, 0x4208, 0x4208, 0x4208, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4284, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x51a0, 0x41a0, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x4008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0288, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0284, 0x01a0, 0x00a0, 0x00a0, 0x00a0, 0x00a0, 0x00a0, 0x00a0, 0x00a0, 0x00a0, 0x30e2, 0x01a0, 0x00a0, 0x00a8, 0x00a0, 0x00a0, 0x00a0, 0x00a0, 0x10a0, 0x10a0, 0x00a0, 0x30e2, 0x00a0, 0x01a0, 0x00a0, 0x10a0, 0x30e2, 0x01a0, 0x10a0, 0x10a0, 0x10a0, 0x01a0, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x00a0, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x00a0, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2 }; static final class CodeRangeEntry { final String table; final byte[]name; int[]range; CodeRangeEntry(String name, String table) { this.table = table; this.name = name.getBytes(); } public int[]getRange() { if (range == null) range = ArrayReader.readIntArray(table); return range; } } static class CTypeName { private static final CaseInsensitiveBytesHash<Integer> CTypeNameHash = initializeCTypeNameTable(); private static CaseInsensitiveBytesHash<Integer> initializeCTypeNameTable() { CaseInsensitiveBytesHash<Integer> table = new CaseInsensitiveBytesHash<Integer>(); for (int i = 0; i < UnicodeProperties.CodeRangeTable.length; i++) { table.putDirect(UnicodeProperties.CodeRangeTable[i].name, i); } return table; } } private static class CodeList { CodeList(DataInputStream dis) throws IOException { int packed = dis.readInt(); flags = packed & ~Config.CodePointMask; int length = packed & Config.CodePointMask; codes = new int[length]; for (int j = 0; j < length; j++) { codes[j] = dis.readInt(); } } final int[]codes; final int flags; } private static class CaseFold { static IntHash<CodeList> read(String table) { try { DataInputStream dis = ArrayReader.openStream(table); int size = dis.readInt(); IntHash<CodeList> hash = new IntHash<CodeList>(size); for (int i = 0; i < size; i++) { hash.putDirect(dis.readInt(), new CodeList(dis)); } dis.close(); return hash; } catch (IOException iot) { throw new RuntimeException(iot); } } static final IntHash<CodeList>Hash = read("CaseFold"); } private static class CaseUnfold11 { private static final int From[]; private static final CodeList To[]; private static final int Locale_From[]; private static final CodeList Locale_To[]; static Object[] read(String table) { try { DataInputStream dis = ArrayReader.openStream(table); int size = dis.readInt(); int[]from = new int[size]; CodeList[]to = new CodeList[size]; for (int i = 0; i < size; i++) { from[i] = dis.readInt(); to[i] = new CodeList(dis); } dis.close(); return new Object[] {from, to}; } catch (IOException iot) { throw new RuntimeException(iot); } } static { Object[]unfold; unfold = read("CaseUnfold_11"); From = (int[])unfold[0]; To = (CodeList[])unfold[1]; unfold = read("CaseUnfold_11_Locale"); Locale_From = (int[])unfold[0]; Locale_To = (CodeList[])unfold[1]; } static IntHash<CodeList> initializeUnfold1Hash() { IntHash<CodeList> hash = new IntHash<CodeList>(From.length + Locale_From.length); for (int i = 0; i < From.length; i++) { hash.putDirect(From[i], To[i]); } for (int i = 0; i < Locale_From.length; i++) { hash.putDirect(Locale_From[i], Locale_To[i]); } return hash; } static final IntHash<CodeList> Hash = initializeUnfold1Hash(); } private static Object[] readFoldN(int fromSize, String table) { try { DataInputStream dis = ArrayReader.openStream(table); int size = dis.readInt(); int[][]from = new int[size][]; CodeList[]to = new CodeList[size]; for (int i = 0; i < size; i++) { from[i] = new int[fromSize]; for (int j = 0; j < fromSize; j++) { from[i][j] = dis.readInt(); } to[i] = new CodeList(dis); } dis.close(); return new Object[] {from, to}; } catch (IOException iot) { throw new RuntimeException(iot); } } private static class CaseUnfold12 { private static final int From[][]; private static final CodeList To[]; private static final int Locale_From[][]; private static final CodeList Locale_To[]; static { Object[]unfold; unfold = readFoldN(2, "CaseUnfold_12"); From = (int[][])unfold[0]; To = (CodeList[])unfold[1]; unfold = readFoldN(2, "CaseUnfold_12_Locale"); Locale_From = (int[][])unfold[0]; Locale_To = (CodeList[])unfold[1]; } private static IntArrayHash<CodeList> initializeUnfold2Hash() { IntArrayHash<CodeList> unfold2 = new IntArrayHash<CodeList>(From.length + Locale_From.length); for (int i = 0; i < From.length; i++) { unfold2.putDirect(From[i], To[i]); } for (int i = 0; i < Locale_From.length; i++) { unfold2.putDirect(Locale_From[i], Locale_To[i]); } return unfold2; } static final IntArrayHash<CodeList> Hash = initializeUnfold2Hash(); } private static class CaseUnfold13 { private static final int From[][]; private static final CodeList To[]; static { Object[]unfold; unfold = readFoldN(3, "CaseUnfold_13"); From = (int[][])unfold[0]; To = (CodeList[])unfold[1]; } private static IntArrayHash<CodeList> initializeUnfold3Hash() { IntArrayHash<CodeList> unfold3 = new IntArrayHash<CodeList>(From.length); for (int i = 0; i < From.length; i++) { unfold3.putDirect(From[i], To[i]); } return unfold3; } static final IntArrayHash<CodeList> Hash = initializeUnfold3Hash(); } private static class CaseMappingSpecials { static ArrayList<int[]> read() { try { DataInputStream dis = ArrayReader.openStream("CaseMappingSpecials"); int size = dis.readInt(); ArrayList<int[]> values = new ArrayList<int[]>(); for (int i = 0; i < size; i++) { int packed = dis.readInt(); int length = packed >>> Config.SpecialsLengthOffset; int[]codes = new int[length]; codes[0] = packed & ((1 << Config.SpecialsLengthOffset) - 1); for (int j = 1; j < length; j++) { i++; codes[j] = dis.readInt(); } values.add(codes); } dis.close(); return values; } catch (IOException ioe) { throw new RuntimeException(ioe); } } static final ArrayList<int[]> Values = read(); } }
package org.jcoderz.commons.util; import org.jcoderz.commons.ArgumentMalformedException; import org.jcoderz.commons.AssertionFailedException; /** * Utility class for assertions. * * @author Andreas Mandel */ public final class Assert { /** Private constructor to avoid instantiation of utility class. */ private Assert () { // utility class -- no instances are allowed. } /** * Asserts that an object isn't null. * If it is a null reference an ArgumentMalformedException is * thrown with a appropriate message. * * @param parameter object to be tested against null. * @param argumentName name of the provided argument within the * used interface. */ public static void notNull (Object parameter, String argumentName) { if (parameter == null) { throw new ArgumentMalformedException(argumentName, null, "Argument " + argumentName + " must not be null"); } } /** * Asserts that two integers are equal. If they are not * an AssertionFailedException is thrown with the given message. * @param message The message for the condition. This message is * used in the exception if the integers are not equal. * @param expected the expected integer. * @param actual the actual integer. * @throws AssertionFailedException if the two objects are not equal. */ public static void assertEquals (String message, int expected, int actual) throws AssertionFailedException { assertEquals(message, new Integer(expected), new Integer(actual)); } /** * Asserts that two objects are equal. If they are not * an AssertionFailedException is thrown with the given message. * @param message The message for the condition. This message is * used in the exception if the objects are not equal. * @param expected the expected object. * @param actual the actual object. * @throws AssertionFailedException if the two objects are not equal. */ public static void assertEquals (String message, Object expected, Object actual) throws AssertionFailedException { if (!ObjectUtil.equals(expected, actual)) { String newMessage = ""; if (message != null) { newMessage = message + " "; } throw new AssertionFailedException(newMessage + "expected:<" + expected + "> but was:<" + actual + ">"); } } /** * Asserts that a condition is <tt>true</tt>. If it isn't it throws * an AssertionFailedException with the given message. * * @param message The message for the condition. This message is * used in the exception if the condition is <tt>false</tt>. * @param condition the condition to test. * @throws AssertionFailedException if the condition is <tt>false</tt>. */ public static void assertTrue (String message, boolean condition) throws AssertionFailedException { if (!condition) { throw new AssertionFailedException(message); } } /** * Can be called if an assertion already failed. This can be used at * code positions that should never be reached at all. It throws * an AssertionFailedException with the given message. * * @param message The message to be used in the exception. * @throws AssertionFailedException always. */ public static void fail (String message) throws AssertionFailedException { throw new AssertionFailedException(message); } /** * Can be called if an exception is unexpectedly caught. This can * be used at catch blocks that should never be reached at all. * It throws an AssertionFailedException with the given nested * exception. * * @param message The message to be used in the exception. * @param ex the exception that was not expected * @throws AssertionFailedException always. */ public static void fail (String message, Throwable ex) throws AssertionFailedException { throw new AssertionFailedException(message, ex); } }
package openmods.block; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.util.EnumSet; import java.util.List; import java.util.Set; import javax.annotation.Nonnull; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockFaceShape; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Enchantments; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.fml.common.ModContainer; import openmods.Log; import openmods.api.IActivateAwareTile; import openmods.api.IAddAwareTile; import openmods.api.IBreakAwareTile; import openmods.api.ICustomBreakDrops; import openmods.api.ICustomHarvestDrops; import openmods.api.ICustomPickItem; import openmods.api.IHasGui; import openmods.api.INeighbourAwareTile; import openmods.api.INeighbourTeAwareTile; import openmods.api.IPlaceAwareTile; import openmods.api.ISurfaceAttachment; import openmods.config.game.IRegisterableBlock; import openmods.geometry.LocalDirections; import openmods.geometry.Orientation; import openmods.inventory.IInventoryProvider; import openmods.tileentity.OpenTileEntity; import openmods.utils.BlockNotifyFlags; import openmods.utils.BlockUtils; public class OpenBlock extends Block implements IRegisterableBlock { public static class TwoDirections extends OpenBlock { public TwoDirections(Material material) { super(material); } @Override public BlockRotationMode getRotationMode() { return BlockRotationMode.TWO_DIRECTIONS; } } public static class ThreeDirections extends OpenBlock { public ThreeDirections(Material material) { super(material); } @Override public BlockRotationMode getRotationMode() { return BlockRotationMode.THREE_DIRECTIONS; } } public static class FourDirections extends OpenBlock { public FourDirections(Material material) { super(material); } @Override public BlockRotationMode getRotationMode() { return BlockRotationMode.FOUR_DIRECTIONS; } } public static class SixDirections extends OpenBlock { public SixDirections(Material material) { super(material); } @Override public BlockRotationMode getRotationMode() { return BlockRotationMode.SIX_DIRECTIONS; } } public static final int OPEN_MODS_TE_GUI = -1; private static final int EVENT_ADDED = -1; private enum TileEntityCapability { GUI_PROVIDER(IHasGui.class), ACTIVATE_LISTENER(IActivateAwareTile.class), SURFACE_ATTACHEMENT(ISurfaceAttachment.class), BREAK_LISTENER(IBreakAwareTile.class), PLACE_LISTENER(IPlaceAwareTile.class), ADD_LISTENER(IAddAwareTile.class), CUSTOM_PICK_ITEM(ICustomPickItem.class), CUSTOM_BREAK_DROPS(ICustomBreakDrops.class), CUSTOM_HARVEST_DROPS(ICustomHarvestDrops.class), INVENTORY(IInventory.class), INVENTORY_PROVIDER(IInventoryProvider.class), NEIGBOUR_LISTENER(INeighbourAwareTile.class), NEIGBOUR_TE_LISTENER(INeighbourTeAwareTile.class); public final Class<?> intf; private TileEntityCapability(Class<?> intf) { this.intf = intf; } } public enum BlockPlacementMode { ENTITY_ANGLE, SURFACE } private final Set<TileEntityCapability> teCapabilities = EnumSet.noneOf(TileEntityCapability.class); private Object modInstance = null; private Class<? extends TileEntity> teClass = null; private BlockPlacementMode blockPlacementMode = BlockPlacementMode.ENTITY_ANGLE; public final IBlockRotationMode rotationMode; public final IProperty<Orientation> propertyOrientation; private boolean requiresInitialization; public boolean hasCapability(TileEntityCapability capability) { return teCapabilities.contains(capability); } public boolean hasCapabilities(TileEntityCapability capability1, TileEntityCapability capability2) { return hasCapability(capability1) || hasCapability(capability2); } public boolean hasCapabilities(TileEntityCapability... capabilities) { for (TileEntityCapability capability : capabilities) if (teCapabilities.contains(capability)) return true; return false; } public OpenBlock(Material material) { super(material); setHardness(1.0F); // I dont think vanilla actually uses this.. this.hasTileEntity = false; this.rotationMode = getRotationMode(); Preconditions.checkNotNull(this.rotationMode); this.propertyOrientation = this.rotationMode.getProperty(); } protected void setPlacementMode(BlockPlacementMode mode) { this.blockPlacementMode = mode; } protected IBlockRotationMode getRotationMode() { return BlockRotationMode.NONE; } protected IProperty<Orientation> getPropertyOrientation() { return getRotationMode().getProperty(); } protected BlockPlacementMode getPlacementMode() { return this.blockPlacementMode; } protected Orientation getOrientation(IBlockAccess world, BlockPos pos) { final IBlockState state = world.getBlockState(pos); return getOrientation(state); } public Orientation getOrientation(IBlockState state) { // sometimes we get air block... if (state.getBlock() != this) return Orientation.XP_YP; return state.getValue(propertyOrientation); } public EnumFacing getFront(IBlockState state) { return rotationMode.getFront(getOrientation(state)); } public EnumFacing getBack(IBlockState state) { return getFront(state).getOpposite(); } public LocalDirections getLocalDirections(IBlockState state) { return rotationMode.getLocalDirections(getOrientation(state)); } public boolean shouldDropFromTeAfterBreak() { return true; } public boolean shouldOverrideHarvestWithTeLogic() { return hasCapability(TileEntityCapability.CUSTOM_HARVEST_DROPS); } public static OpenBlock getOpenBlock(IBlockAccess world, BlockPos blockPos) { if (world == null) return null; Block block = world.getBlockState(blockPos).getBlock(); if (block instanceof OpenBlock) return (OpenBlock)block; return null; } @Override public TileEntity createTileEntity(World world, IBlockState state) { final TileEntity te = createTileEntity(); if (te instanceof OpenTileEntity) ((OpenTileEntity)te).setup(); return te; } protected TileEntity createTileEntity() { if (teClass == null) return null; try { return teClass.newInstance(); } catch (Exception ex) { throw new RuntimeException("Failed to create TE with class " + teClass, ex); } } public Class<? extends TileEntity> getTileClass() { return teClass; } protected boolean suppressPickBlock() { return false; } @Override @Nonnull public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { if (hasCapability(TileEntityCapability.CUSTOM_PICK_ITEM)) { TileEntity te = world.getTileEntity(pos); if (te instanceof ICustomPickItem) return ((ICustomPickItem)te).getPickBlock(player); } return suppressPickBlock()? ItemStack.EMPTY : super.getPickBlock(state, target, world, pos, player); } private static List<ItemStack> getTileBreakDrops(TileEntity te) { List<ItemStack> breakDrops = Lists.newArrayList(); BlockUtils.getTileInventoryDrops(te, breakDrops); if (te instanceof ICustomBreakDrops) breakDrops = ((ICustomBreakDrops)te).getDrops(breakDrops); return breakDrops; } @Override public void breakBlock(World world, BlockPos pos, IBlockState state) { if (shouldDropFromTeAfterBreak()) { final TileEntity te = world.getTileEntity(pos); if (te != null) { if (te instanceof IBreakAwareTile) ((IBreakAwareTile)te).onBlockBroken(); for (ItemStack stack : getTileBreakDrops(te)) BlockUtils.dropItemStackInWorld(world, pos, stack); world.removeTileEntity(pos); } } super.breakBlock(world, pos, state); } @Override public void harvestBlock(World world, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity te, @Nonnull ItemStack stack) { player.addStat(StatList.getBlockStats(this)); player.addExhaustion(0.025F); if (canSilkHarvest(world, pos, state, player) && EnchantmentHelper.getEnchantmentLevel(Enchantments.SILK_TOUCH, stack) > 0) { handleSilkTouchDrops(world, player, pos, state, te); } else { handleNormalDrops(world, player, pos, state, te, stack); } } protected void handleNormalDrops(World world, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity te, @Nonnull ItemStack stack) { harvesters.set(player); final int fortune = EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, stack); boolean addNormalDrops = true; if (te instanceof ICustomHarvestDrops) { final ICustomHarvestDrops dropper = (ICustomHarvestDrops)te; final List<ItemStack> drops = Lists.newArrayList(); dropper.addHarvestDrops(player, drops, state, fortune, false); ForgeEventFactory.fireBlockHarvesting(drops, world, pos, state, fortune, 1.0f, false, player); for (ItemStack drop : drops) spawnAsEntity(world, pos, drop); addNormalDrops = !dropper.suppressBlockHarvestDrops(); } if (addNormalDrops) dropBlockAsItem(world, pos, state, fortune); harvesters.set(null); } protected void handleSilkTouchDrops(World world, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity te) { List<ItemStack> items = Lists.newArrayList(); boolean addNormalDrops = true; if (te instanceof ICustomHarvestDrops) { final ICustomHarvestDrops dropper = (ICustomHarvestDrops)te; dropper.addHarvestDrops(player, items, state, 0, true); addNormalDrops = !dropper.suppressBlockHarvestDrops(); } if (addNormalDrops) { final ItemStack drop = new ItemStack(Item.getItemFromBlock(this), 1, damageDropped(state)); items.add(drop); } ForgeEventFactory.fireBlockHarvesting(items, world, pos, state, 0, 1.0f, true, player); for (ItemStack stack : items) spawnAsEntity(world, pos, stack); } @Override public void setupBlock(ModContainer container, String id, Class<? extends TileEntity> tileEntity, ItemBlock itemBlock) { this.modInstance = container.getMod(); if (tileEntity != null) { this.teClass = tileEntity; hasTileEntity = true; for (TileEntityCapability capability : TileEntityCapability.values()) if (capability.intf.isAssignableFrom(teClass)) teCapabilities.add(capability); } } @Override public boolean hasTileEntity(IBlockState state) { return teClass != null; } public final static boolean isNeighborBlockSolid(IBlockAccess world, BlockPos blockPos, EnumFacing side) { final BlockPos pos = blockPos.offset(side); final IBlockState state = world.getBlockState(pos); return isExceptionBlockForAttaching(state.getBlock()) || state.getBlockFaceShape(world, pos, side.getOpposite()) == BlockFaceShape.SOLID; } public final static boolean areNeighborBlocksSolid(World world, BlockPos blockPos, EnumFacing... sides) { for (EnumFacing side : sides) { if (isNeighborBlockSolid(world, blockPos, side)) return true; } return false; } @Override public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) { if (hasCapabilities(TileEntityCapability.NEIGBOUR_LISTENER, TileEntityCapability.SURFACE_ATTACHEMENT)) { final TileEntity te = world.getTileEntity(pos); if (te instanceof INeighbourAwareTile) ((INeighbourAwareTile)te).onNeighbourChanged(fromPos, blockIn); if (te instanceof ISurfaceAttachment) { final EnumFacing direction = ((ISurfaceAttachment)te).getSurfaceDirection(); breakBlockIfSideNotSolid(world, pos, direction); } } } protected void breakBlockIfSideNotSolid(World world, BlockPos blockPos, EnumFacing direction) { if (!isNeighborBlockSolid(world, blockPos, direction)) { world.destroyBlock(blockPos, true); } } @Override public void onNeighborChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { if (hasCapability(TileEntityCapability.NEIGBOUR_TE_LISTENER)) { final TileEntity te = world.getTileEntity(pos); if (te instanceof INeighbourTeAwareTile) ((INeighbourTeAwareTile)te).onNeighbourTeChanged(pos); } } @Override public void onBlockAdded(World world, BlockPos blockPos, IBlockState state) { super.onBlockAdded(world, blockPos, state); if (requiresInitialization || hasCapability(TileEntityCapability.ADD_LISTENER)) { world.addBlockEvent(blockPos, this, EVENT_ADDED, 0); } } @Override public boolean onBlockActivated(World world, BlockPos blockPos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { if (hasCapabilities(TileEntityCapability.GUI_PROVIDER, TileEntityCapability.ACTIVATE_LISTENER)) { final TileEntity te = world.getTileEntity(blockPos); if (te instanceof IHasGui && ((IHasGui)te).canOpenGui(player) && !player.isSneaking()) { if (!world.isRemote) openGui(player, world, blockPos); return true; } // TODO Expand for new args if (te instanceof IActivateAwareTile) return ((IActivateAwareTile)te).onBlockActivated(player, hand, side, hitX, hitY, hitZ); } return false; } @SuppressWarnings("deprecation") // TODO review @Override public boolean eventReceived(IBlockState state, World world, BlockPos blockPos, int eventId, int eventParam) { if (eventId < 0 && !world.isRemote) { switch (eventId) { case EVENT_ADDED: return onBlockAddedNextTick(world, blockPos, state); } return false; } if (hasTileEntity) { super.eventReceived(state, world, blockPos, eventId, eventParam); TileEntity te = world.getTileEntity(blockPos); return te != null? te.receiveClientEvent(eventId, eventParam) : false; } else { return super.eventReceived(state, world, blockPos, eventId, eventParam); } } protected boolean onBlockAddedNextTick(World world, BlockPos blockPos, IBlockState state) { if (hasCapability(TileEntityCapability.ADD_LISTENER)) { final IAddAwareTile te = getTileEntity(world, blockPos, IAddAwareTile.class); if (te != null) te.onAdded(); } return true; } @SuppressWarnings("unchecked") public static <U> U getTileEntity(IBlockAccess world, BlockPos blockPos, Class<? extends U> cls) { final TileEntity te = world.getTileEntity(blockPos); return (cls.isInstance(te))? (U)te : null; } @SuppressWarnings("unchecked") public <U extends TileEntity> U getTileEntity(IBlockAccess world, BlockPos blockPos) { Preconditions.checkNotNull(teClass, "This block has no tile entity"); final TileEntity te = world.getTileEntity(blockPos); return (teClass.isInstance(te))? (U)te : null; } protected Orientation calculateOrientationAfterPlace(BlockPos pos, EnumFacing facing, EntityLivingBase placer) { if (blockPlacementMode == BlockPlacementMode.SURFACE) { return rotationMode.getOrientationFacing(facing); } else { return rotationMode.getPlacementOrientationFromEntity(pos, placer); } } public boolean canBlockBePlaced(World world, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ, int itemMetadata, EntityPlayer player) { return true; } @Override public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { final Orientation orientation = calculateOrientationAfterPlace(pos, facing, placer); return getStateFromMeta(meta).withProperty(propertyOrientation, orientation); } @Override public void onBlockPlacedBy(World world, BlockPos blockPos, IBlockState state, EntityLivingBase placer, @Nonnull ItemStack stack) { super.onBlockPlacedBy(world, blockPos, state, placer, stack); if (hasCapability(TileEntityCapability.PLACE_LISTENER)) { final TileEntity te = world.getTileEntity(blockPos); if (te instanceof IPlaceAwareTile) ((IPlaceAwareTile)te).onBlockPlacedBy(state, placer, stack); } } protected boolean isOnTopOfSolidBlock(World world, BlockPos blockPos, EnumFacing side) { return side == EnumFacing.UP && isNeighborBlockSolid(world, blockPos, EnumFacing.DOWN); } public void openGui(EntityPlayer player, World world, BlockPos blockPos) { player.openGui(modInstance, OPEN_MODS_TE_GUI, world, blockPos.getX(), blockPos.getY(), blockPos.getZ()); } public Orientation getOrientationFromMeta(int meta) { return rotationMode.fromValue(meta & rotationMode.getMask()); } public int getMetaFromOrientation(Orientation orientation) { return rotationMode.toValue(orientation); } @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState() .withProperty(propertyOrientation, getOrientationFromMeta(meta)); } @Override public int getMetaFromState(IBlockState state) { final Orientation orientation = state.getValue(propertyOrientation); return getMetaFromOrientation(orientation); } @Override protected BlockStateContainer createBlockState() { // WARNING: this is called from superclass, so rotationMode is not set yet return new BlockStateContainer(this, getPropertyOrientation()); } @Override public boolean rotateBlock(World worldObj, BlockPos blockPos, EnumFacing axis) { if (!canRotateWithTool()) return false; final IBlockState currentState = worldObj.getBlockState(blockPos); final Orientation orientation = currentState.getValue(propertyOrientation); final Orientation newOrientation = rotationMode.calculateToolRotation(orientation, axis); if (newOrientation != null) { if (rotationMode.isOrientationValid(newOrientation)) { final IBlockState newState = createNewStateAfterRotation(worldObj, blockPos, currentState, propertyOrientation, newOrientation); worldObj.setBlockState(blockPos, newState, BlockNotifyFlags.ALL); } else { Log.info("Invalid tool rotation: [%s] %s: (%s): %s->%s", rotationMode, axis, blockPos, orientation, newOrientation); return false; } } if (teCapabilities.contains(TileEntityCapability.SURFACE_ATTACHEMENT)) { final ISurfaceAttachment te = getTileEntity(worldObj, blockPos, ISurfaceAttachment.class); if (te == null) return false; breakBlockIfSideNotSolid(worldObj, blockPos, te.getSurfaceDirection()); } return true; } protected IBlockState createNewStateAfterRotation(World worldObj, BlockPos blockPos, IBlockState currentState, IProperty<Orientation> currentOrientation, Orientation newOrientation) { return currentState.withProperty(propertyOrientation, newOrientation); } public boolean canRotateWithTool() { return rotationMode.toolRotationAllowed(); } @Override public EnumFacing[] getValidRotations(World worldObj, BlockPos pos) { if (!canRotateWithTool()) return RotationAxis.NO_AXIS; return rotationMode.getToolRotationAxes(); } public OpenBlock setRequiresInitialization(boolean value) { this.requiresInitialization = value; return this; } }
// $Id: STATE_TRANSFER.java,v 1.21 2006/04/13 08:14:20 belaban Exp $ package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.View; import org.jgroups.blocks.GroupRequest; import org.jgroups.blocks.RequestCorrelator; import org.jgroups.blocks.RequestHandler; import org.jgroups.stack.Protocol; import org.jgroups.stack.StateTransferInfo; import org.jgroups.util.Rsp; import org.jgroups.util.RspList; import org.jgroups.util.Util; import java.io.Serializable; import java.util.HashMap; import java.util.Properties; import java.util.Vector; class StateTransferRequest implements Serializable { static final int MAKE_COPY=1; // arg = originator of request static final int RETURN_STATE=2; // arg = orginator of request int type=0; final Object arg; private static final long serialVersionUID = -7734608266762273116L; StateTransferRequest(int type, Object arg) { this.type=type; this.arg=arg; } public int getType() { return type; } public Object getArg() { return arg; } public String toString() { return "[StateTransferRequest: type=" + type2Str(type) + ", arg=" + arg + ']'; } static String type2Str(int t) { switch(t) { case MAKE_COPY: return "MAKE_COPY"; case RETURN_STATE: return "RETURN_STATE"; default: return "<unknown>"; } } } /** * State transfer layer. Upon receiving a GET_STATE event from JChannel, a MAKE_COPY message is * sent to all members. When the originator receives MAKE_COPY, it queues all messages to the * channel. * When another member receives the message, it asks the JChannel to provide it with a copy of * the current state (GetStateEvent is received by application, returnState() sends state down the * stack). Then the current layer sends a unicast RETURN_STATE message to the coordinator, which * returns the cached copy. * When the state is received by the originator, the GET_STATE sender is unblocked with a * GET_STATE_OK event up the stack (unless it already timed out).<p> * Requires QUEUE layer on top. * * @author Bela Ban */ public class STATE_TRANSFER extends Protocol implements RequestHandler { Address local_addr=null; final Vector members=new Vector(11); final Message m=null; boolean is_server=false; byte[] cached_state=null; final Object state_xfer_mutex=new Object(); // get state from appl (via channel). long timeout_get_appl_state=5000; long timeout_return_state=5000; RequestCorrelator corr=null; final Vector observers=new Vector(5); final HashMap map=new HashMap(7); /** * All protocol names have to be unique ! */ public String getName() { return "STATE_TRANSFER"; } public void init() throws Exception { map.put("state_transfer", Boolean.TRUE); map.put("protocol_class", getClass().getName()); } public void start() throws Exception { corr=new RequestCorrelator(getName(), this, this); passUp(new Event(Event.CONFIG, map)); } public void stop() { if(corr != null) { corr.stop(); corr=null; } } public boolean setProperties(Properties props) { String str; super.setProperties(props); // Milliseconds to wait for application to provide requested state, events are // STATE_TRANSFER up and STATE_TRANSFER_OK down str=props.getProperty("timeout_get_appl_state"); if(str != null) { timeout_get_appl_state=Long.parseLong(str); props.remove("timeout_get_appl_state"); } // Milliseconds to wait for 1 or all members to return its/their state. 0 means wait // forever. States are retrieved using GroupRequest/RequestCorrelator str=props.getProperty("timeout_return_state"); if(str != null) { timeout_return_state=Long.parseLong(str); props.remove("timeout_return_state"); } if(props.size() > 0) { log.error("STATE_TRANSFER.setProperties(): the following properties are not recognized: " + props); return false; } return true; } public Vector requiredUpServices() { Vector ret=new Vector(2); ret.addElement(new Integer(Event.START_QUEUEING)); ret.addElement(new Integer(Event.STOP_QUEUEING)); return ret; } public void up(Event evt) { switch(evt.getType()) { case Event.BECOME_SERVER: is_server=true; break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; case Event.TMP_VIEW: case Event.VIEW_CHANGE: Vector new_members=((View)evt.getArg()).getMembers(); synchronized(members) { members.removeAllElements(); if(new_members != null && new_members.size() > 0) for(int k=0; k < new_members.size(); k++) members.addElement(new_members.elementAt(k)); } break; } if(corr != null) corr.receive(evt); // will consume or pass up, depending on header else passUp(evt); } public void down(Event evt) { Object coord, state; Vector event_list; StateTransferInfo info; switch(evt.getType()) { case Event.TMP_VIEW: case Event.VIEW_CHANGE: Vector new_members=((View)evt.getArg()).getMembers(); synchronized(members) { members.removeAllElements(); if(new_members != null && new_members.size() > 0) for(int k=0; k < new_members.size(); k++) members.addElement(new_members.elementAt(k)); } break; case Event.GET_STATE: // generated by JChannel.getState() info=(StateTransferInfo)evt.getArg(); coord=determineCoordinator(); if(coord == null || coord.equals(local_addr)) { event_list=new Vector(1); event_list.addElement(new Event(Event.GET_STATE_OK, new StateTransferInfo())); passUp(new Event(Event.STOP_QUEUEING, event_list)); return; // don't pass down any further ! } try { sendMakeCopyMessage(); // multicast MAKE_COPY to all members (including me) state=getStateFromSingle(info.target); } catch(Throwable t) { if(log.isErrorEnabled()) log.error("failed sending state request", t); state=null; } /* Pass up the state to the application layer (insert into JChannel's event queue */ event_list=new Vector(1); event_list.addElement(new Event(Event.GET_STATE_OK, new StateTransferInfo(null, info.state_id, 0L, (byte[])state))); /* Now stop queueing */ passUp(new Event(Event.STOP_QUEUEING, event_list)); return; // don't pass down any further ! case Event.GET_APPLSTATE_OK: synchronized(state_xfer_mutex) { info=(StateTransferInfo)evt.getArg(); cached_state=info.state; state_xfer_mutex.notifyAll(); } return; // don't pass down any further ! } passDown(evt); // pass on to the layer below us } public Object handle(Message msg) { StateTransferRequest req; try { req=(StateTransferRequest)msg.getObject(); switch(req.getType()) { case StateTransferRequest.MAKE_COPY: makeCopy(req.getArg()); return null; case StateTransferRequest.RETURN_STATE: if(is_server) return cached_state; else { if(warn) log.warn("RETURN_STATE: returning null" + "as I'm not yet an operational state server !"); return null; } default: if(log.isErrorEnabled()) log.error("type " + req.getType() + "is unknown in StateTransferRequest !"); return null; } } catch(Exception e) { if(log.isErrorEnabled()) log.error("exception is " + e); return null; } } byte[] getStateFromSingle(Address target) throws Throwable { Vector dests=new Vector(11); Message msg; StateTransferRequest r=new StateTransferRequest(StateTransferRequest.RETURN_STATE, local_addr); RspList rsp_list; Rsp rsp; Address dest; GroupRequest req; int num_tries=0; try { msg=new Message(null, null, Util.objectToByteBuffer(r)); } catch(Exception e) { if(log.isErrorEnabled()) log.error("exception=" + e); return null; } while(members.size() > 1 && num_tries++ < 3) { // excluding myself dest=target != null? target : determineCoordinator(); if(dest == null) return null; msg.setDest(dest); dests.removeAllElements(); dests.addElement(dest); req=new GroupRequest(msg, corr, dests, GroupRequest.GET_FIRST, timeout_return_state, 0); req.execute(); rsp_list=req.getResults(); for(int i=0; i < rsp_list.size(); i++) { // get the first non-suspected result rsp=(Rsp)rsp_list.elementAt(i); if(rsp.wasReceived()) return (byte[])rsp.getValue(); } Util.sleep(1000); } return null; } // Vector getStateFromMany(Vector targets) { // Vector dests=new Vector(11); // Message msg; // StateTransferRequest r=new StateTransferRequest(StateTransferRequest.RETURN_STATE, local_addr); // RspList rsp_list; // GroupRequest req; // int i; // if(targets != null) { // for(i=0; i < targets.size(); i++) // if(!local_addr.equals(targets.elementAt(i))) // dests.addElement(targets.elementAt(i)); // else { // for(i=0; i < members.size(); i++) // if(!local_addr.equals(members.elementAt(i))) // dests.addElement(members.elementAt(i)); // if(dests.size() == 0) // return null; // msg=new Message(); // try { // msg.setBuffer(Util.objectToByteBuffer(r)); // catch(Exception e) { // req=new GroupRequest(msg, corr, dests, GroupRequest.GET_ALL, timeout_return_state, 0); // req.execute(); // rsp_list=req.getResults(); // return rsp_list.getResults(); void sendMakeCopyMessage() throws Throwable { GroupRequest req; Message msg=new Message(); StateTransferRequest r=new StateTransferRequest(StateTransferRequest.MAKE_COPY, local_addr); Vector dests=new Vector(11); for(int i=0; i < members.size(); i++) dests.addElement(members.elementAt(i)); if(dests.size() == 0) return; try { msg.setBuffer(Util.objectToByteBuffer(r)); } catch(Exception e) { } req=new GroupRequest(msg, corr, dests, GroupRequest.GET_ALL, timeout_return_state, 0); req.execute(); } /** * Return the first element of members which is not me. Otherwise return null. */ Address determineCoordinator() { Address ret=null; if(members != null && members.size() > 1) { for(int i=0; i < members.size(); i++) if(!local_addr.equals(members.elementAt(i))) return (Address)members.elementAt(i); } return ret; } /** * If server, ask application to send us a copy of its state (STATE_TRANSFER up, * STATE_TRANSFER down). If client, start queueing events. Queuing will be stopped when * state has been retrieved (or not) from single or all member(s). */ void makeCopy(Object sender) { if(sender.equals(local_addr)) { // was sent by us, has to start queueing passUp(new Event(Event.START_QUEUEING)); } else { // only retrieve state from appl when not in client state anymore if(is_server) { // get state from application and store it locally synchronized(state_xfer_mutex) { cached_state=null; StateTransferInfo info=new StateTransferInfo(local_addr); passUp(new Event(Event.GET_APPLSTATE, info)); if(cached_state == null) { try { state_xfer_mutex.wait(timeout_get_appl_state); // wait for STATE_TRANSFER_OK } catch(Exception e) { } } } } } } }
package org.animotron; import static org.animotron.graph.AnimoGraph.finishTx; import static org.animotron.graph.AnimoGraph.isTransactionActive; import org.animotron.exception.AnimoException; import org.animotron.statement.Statement; import org.animotron.statement.ml.*; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class Expression extends AbstractExpression { Object[][] e; public Expression(Object[]... e) throws AnimoException { this.e = e; build(); } private void build() throws AnimoException { try { startGraph(); for(Object[] i : e) { buildExpression(i); } endGraph(); } finally { if (isTransactionActive(tx)) { tx.failure(); finishTx(tx); } } } private void buildExpression(Object[]... e) { if (e != null) for (Object i : e) buildStatement((Object[]) i); } private void buildStatement(Object[] e) { start((Statement) e[0], (String) e[1]); buildExpression((Object[][]) e[2]); end(); } public static Object[] _(Statement statement, String reference) { Object[] e = {statement, reference, null}; return e; } public static Object[] _(Statement statement, Object[]... p) { Object[] e = {statement, null, p}; return e; } public static Object[] _(Statement statement, String reference, Object[]... p) { Object[] e = {statement, reference, p}; return e; } public static Object[] element(String name) { return _(ELEMENT._, name(name)); } public static Object[] element(String name, Object[]... p) { return _(ELEMENT._, name(name), p); } public static Object[] attribute(String name) { return _(ATTRIBUTE._, name(name)); } public static Object[] attribute(String name, String value) { return _(ATTRIBUTE._, name(name), text(value)); } public static Object[] comment(String value) { return _(COMMENT._, text(value)); } public static Object[] cdata(String value) { return _(CDATA._, text(value)); } public static Object[] pi(String value) { return _(PI._, text(value)); } public static Object[] namespace(String name, String value) { return _(NS._, name(name), text(value)); } public static Object[] namespace(String value) { return _(NS._, text(value)); } public static Object[] name(String value) { return _(NAME._, value); } public static Object[] text(String value) { return _(TEXT._, value); } }
package org.jmist.packages; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.jmist.framework.AbstractGeometry; import org.jmist.framework.Geometry; import org.jmist.toolkit.Box3; import org.jmist.toolkit.Sphere; /** * A <code>Geometry</code> that is composed of component geometries. * @author bkimmel */ public abstract class CompositeGeometry extends AbstractGeometry { /** * Adds a child <code>Geometry</code> to this * <code>CompositeGeometry</code>. * @param child The child <code>Geometry</code> to add. * @return A reference to this <code>CompositeGeometry</code> so that calls * to this method may be chained. */ public CompositeGeometry addChild(Geometry child) { this.children.add(child); return this; } /* (non-Javadoc) * @see org.jmist.framework.Bounded3#boundingBox() */ @Override public Box3 boundingBox() { /* The default behavior is pessimistic (i.e., the result is the union * of the bounding boxes for each of the children. */ Collection<Box3> boxes = new ArrayList<Box3>(); for (Geometry child : this.children) { boxes.add(child.boundingBox()); } return Box3.smallestContaining(boxes); } /* (non-Javadoc) * @see org.jmist.framework.Bounded3#boundingSphere() */ @Override public Sphere boundingSphere() { /* The default behavior is to return the sphere that bounds the * bounding box. */ Box3 boundingBox = this.boundingBox(); return new Sphere(boundingBox.center(), boundingBox.diagonal() / 2.0); } /* (non-Javadoc) * @see org.jmist.framework.Geometry#isClosed() */ @Override public boolean isClosed() { for (Geometry child : this.children) { if (!child.isClosed()) { return false; } } return true; } /** * Gets the list of child geometries. * @return The <code>List</code> of child geometries. */ protected final List<Geometry> children() { return this.children; } /** The child geometries. */ private final List<Geometry> children = new ArrayList<Geometry>(); }
package org.jboss.modules; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; public final class Module { static { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { try { URL.setURLStreamHandlerFactory(new ModularURLStreamHandlerFactory()); } catch (Throwable t) { // todo log a warning or something } return null; } }); } /** * The system module, which is always available. */ public static final Module SYSTEM = new Module(); static volatile ModuleLogger log = NoopModuleLogger.getInstance(); private static ModuleLoaderSelector moduleLoaderSelector = ModuleLoaderSelector.DEFAULT; private final ModuleIdentifier identifier; private final String mainClassName; private final ModuleClassLoader moduleClassLoader; private final ModuleLoader moduleLoader; private List<Dependency> dependencies; private Set<DependencyExport> exportedDependencies; private final AtomicBoolean exportsDetermined = new AtomicBoolean(); private Map<String, List<DependencyImport>> pathsToImports; private final AtomicBoolean importsDetermined = new AtomicBoolean(); private Set<String> localExportedPaths; Module(final ModuleSpec spec, final Set<Flag> flags, final ModuleLoader moduleLoader) { this.moduleLoader = moduleLoader; identifier = spec.getIdentifier(); mainClassName = spec.getMainClass(); final ModuleContentLoader moduleContentLoader = spec.getContentLoader(); // should be safe, so... //noinspection ThisEscapedInObjectConstruction moduleClassLoader = new ModuleClassLoader(this, flags, spec.getAssertionSetting(), moduleContentLoader); localExportedPaths = Collections.unmodifiableSet(moduleContentLoader.getFilteredLocalPaths()); } private Module() { identifier = ModuleIdentifier.SYSTEM; mainClassName = null; //noinspection ThisEscapedInObjectConstruction final SystemModuleClassLoader classLoader = new SystemModuleClassLoader(this, Collections.<Flag>emptySet(), AssertionSetting.INHERIT); moduleClassLoader = classLoader; localExportedPaths = Collections.unmodifiableSet(classLoader.getExportedPaths()); pathsToImports = null; // bypassed by the system MCL moduleLoader = InitialModuleLoader.INSTANCE; } void setDependencies(final List<Dependency> dependencies) { if(this.dependencies != null) { throw new IllegalStateException("Module dependencies can only be set once"); } this.dependencies = dependencies; } /** * Get an exported resource from a specific root in this module. * * @param rootPath the module root to search * @param resourcePath the path of the resource * @return the resource */ public final Resource getExportedResource(final String rootPath, final String resourcePath) { return moduleClassLoader.getRawResource(rootPath, resourcePath); } /** * Run a module's main class, if any. * * @param args the arguments to pass * @throws NoSuchMethodException if there is no main method * @throws InvocationTargetException if the main method failed * @throws ClassNotFoundException if the main class is not found */ public final void run(final String[] args) throws NoSuchMethodException, InvocationTargetException, ClassNotFoundException { try { if (mainClassName == null) { throw new NoSuchMethodException("No main class defined for " + this); } final Class<?> mainClass = moduleClassLoader.loadExportedClass(mainClassName); if (mainClass == null) { throw new NoSuchMethodException("No main class named '" + mainClassName + "' found in " + this); } final Method mainMethod = mainClass.getMethod("main", String[].class); final int modifiers = mainMethod.getModifiers(); if (! Modifier.isStatic(modifiers)) { throw new NoSuchMethodException("Main method is not static for " + this); } // ignore the return value mainMethod.invoke(null, new Object[] {args}); } catch (IllegalAccessException e) { // unexpected; should be public throw new IllegalAccessError(e.getMessage()); } } /** * Get this module's identifier. * * @return the identifier */ public ModuleIdentifier getIdentifier() { return identifier; } /** * Get the module loader which created this module. * * @return the module loader of this module */ public ModuleLoader getModuleLoader() { return moduleLoader; } /** * Load a service from this module. * * @param serviceType the service type class * @param <S> the service type * @return the service loader */ public <S> ServiceLoader<S> loadService(Class<S> serviceType) { return ServiceLoader.load(serviceType, moduleClassLoader); } /** * Load a service from the named module. * * @param moduleIdentifier the module identifier * @param serviceType the service type class * @param <S> the service type * @return the service loader * @throws ModuleLoadException if the given module could not be loaded */ public static <S> ServiceLoader<S> loadService(ModuleIdentifier moduleIdentifier, Class<S> serviceType) throws ModuleLoadException { return Module.getModule(moduleIdentifier).loadService(serviceType); } /** * Load a service from the named module. * * @param moduleIdentifier the module identifier * @param serviceType the service type class * @param <S> the service type * @return the service loader * @throws ModuleLoadException if the given module could not be loaded */ public static <S> ServiceLoader<S> loadService(String moduleIdentifier, Class<S> serviceType) throws ModuleLoadException { return loadService(ModuleIdentifier.fromString(moduleIdentifier), serviceType); } /** * Get the class loader for a module. * * @return the module class loader */ public ModuleClassLoader getClassLoader() { return moduleClassLoader; } /** * Get all the paths exported by this module. * * @return the paths that are exported by this module */ public Set<String> getExportedPaths() { return localExportedPaths; } Map<String, List<DependencyImport>> getPathsToImports() { if(importsDetermined.compareAndSet(false, true)) { pathsToImports = new HashMap<String, List<DependencyImport>>(); for(Dependency dependency : dependencies) { final Module dependencyModule = dependency.getModule(); final PathFilter exportFilter = dependency.getExportFilter(); final PathFilter importFilter = dependency.getImportFilter(); final Set<DependencyExport> moduleExportedDependencies = dependencyModule.getExportedDependencies(); for(DependencyExport dependencyExport : moduleExportedDependencies) { final Module dependencyExportModule = dependencyExport.module; if(dependencyExportModule.equals(this)); final Set<String> dependenciesLocalExports = dependencyExportModule.getExportedPaths(); for(String exportPath : dependenciesLocalExports) { if(importFilter.accept(exportPath)) { final boolean shouldExport = dependency.isExport() && exportFilter.accept(exportPath) && dependencyExport.exportFilter.accept(exportPath); if(!pathsToImports.containsKey(exportPath)) pathsToImports.put(exportPath, new ArrayList<DependencyImport>()); pathsToImports.get(exportPath).add(new DependencyImport(dependencyExportModule, shouldExport)); } } } final Set<String> dependenciesLocalExports = dependencyModule.getExportedPaths(); for(String exportPath : dependenciesLocalExports) { if(importFilter.accept(exportPath)) { final boolean shouldExport = dependency.isExport() && exportFilter.accept(exportPath); if(!pathsToImports.containsKey(exportPath)) pathsToImports.put(exportPath, new ArrayList<DependencyImport>()); pathsToImports.get(exportPath).add(new DependencyImport(dependencyModule, shouldExport)); } } } } return pathsToImports; } Set<DependencyExport> getExportedDependencies() { if(exportsDetermined.compareAndSet(false, true)) { exportedDependencies = new HashSet<DependencyExport>(); for(Dependency dependency : dependencies) { if(dependency.isExport()) { final Module dependencyModule = dependency.getModule(); exportedDependencies.add(new DependencyExport(dependencyModule, dependency.getExportFilter())); final Set<DependencyExport> dependencyExports = dependencyModule.getExportedDependencies(); for(DependencyExport dependencyExport : dependencyExports) { final Module exportModule = dependencyExport.module; if(exportModule.equals(this)) continue; exportedDependencies.add(new DependencyExport(exportModule, new DelegatingPathFilter(dependencyExport.exportFilter, dependency.getExportFilter()))); } } } } return exportedDependencies; } /** * Get the module for a loaded class, or {@code null} if the class did not come from any module. * * @param clazz the class * @return the module it came from */ public static Module forClass(Class<?> clazz) { final ClassLoader cl = clazz.getClassLoader(); return cl instanceof ModuleClassLoader ? ((ModuleClassLoader) cl).getModule() : cl == null || cl == ClassLoader.getSystemClassLoader() ? SYSTEM : null; } /** * Load a class from a module. * * @param moduleIdentifier the identifier of the module from which the class should be loaded * @param className the class name to load * @param initialize {@code true} to initialize the class * @return the class * @throws ModuleLoadException if the module could not be loaded * @throws ClassNotFoundException if the class could not be loaded */ public static Class<?> loadClass(final ModuleIdentifier moduleIdentifier, final String className, final boolean initialize) throws ModuleLoadException, ClassNotFoundException { return Class.forName(className, initialize, ModuleClassLoader.forModule(moduleIdentifier)); } /** * Load a class from a module. The class will be initialized. * * @param moduleIdentifier the identifier of the module from which the class should be loaded * @param className the class name to load * @return the class * @throws ModuleLoadException if the module could not be loaded * @throws ClassNotFoundException if the class could not be loaded */ public static Class<?> loadClass(final ModuleIdentifier moduleIdentifier, final String className) throws ModuleLoadException, ClassNotFoundException { return Class.forName(className, true, ModuleClassLoader.forModule(moduleIdentifier)); } /** * Load a class from a module. * * @param moduleIdentifierString the identifier of the module from which the class should be loaded * @param className the class name to load * @param initialize {@code true} to initialize the class * @return the class * @throws ModuleLoadException if the module could not be loaded * @throws ClassNotFoundException if the class could not be loaded */ public static Class<?> loadClass(final String moduleIdentifierString, final String className, final boolean initialize) throws ModuleLoadException, ClassNotFoundException { return Class.forName(className, initialize, ModuleClassLoader.forModule(ModuleIdentifier.fromString(moduleIdentifierString))); } /** * Load a class from a module. The class will be initialized. * * @param moduleIdentifierString the identifier of the module from which the class should be loaded * @param className the class name to load * @return the class * @throws ModuleLoadException if the module could not be loaded * @throws ClassNotFoundException if the class could not be loaded */ public static Class<?> loadClass(final String moduleIdentifierString, final String className) throws ModuleLoadException, ClassNotFoundException { return Class.forName(className, true, ModuleClassLoader.forModule(ModuleIdentifier.fromString(moduleIdentifierString))); } /** * Get the module with the given identifier from the current module loader as returned by {@link ModuleLoaderSelector#getCurrentLoader()} * on the current module loader selector. * * @param identifier the module identifier * @return the module * @throws ModuleLoadException if an error occurs */ public static Module getModule(final ModuleIdentifier identifier) throws ModuleLoadException { return moduleLoaderSelector.getCurrentLoader().loadModule(identifier); } /** * The enumeration of flag values which can be used to configure a module instance. */ public enum Flag { // flags here /** * Indicates that the module's local resources should be loaded before consulting external imports. */ CHILD_FIRST } /** * Get the string representation of this module. * * @return the string representation */ public String toString() { return "Module \"" + identifier + "\""; } /** * Set the current module loader selector. * * @param moduleLoaderSelector the new selector, must not be {@code null} */ public static void setModuleLoaderSelector(final ModuleLoaderSelector moduleLoaderSelector) { if (moduleLoaderSelector == null) { throw new IllegalArgumentException("moduleLoaderSelector is null"); } // todo: perm check Module.moduleLoaderSelector = moduleLoaderSelector; } /** * Change the logger used by the module system. * * @param logger the new logger, must not be {@code null} */ public static void setModuleLogger(final ModuleLogger logger) { if (logger == null) { throw new IllegalArgumentException("logger is null"); } // todo: perm check log = logger; } static final class DependencyImport { private final Module module; private final boolean export; DependencyImport(Module module, boolean export) { this.module = module; this.export = export; } public Module getModule() { return module; } public boolean isExport() { return export; } } static final class DependencyExport { private final Module module; private final PathFilter exportFilter; DependencyExport(Module module, PathFilter exportFilter) { this.module = module; this.exportFilter = exportFilter; } Module getModule() { return module; } } }
package org.lockss.extractor; import java.util.*; import org.apache.commons.collections4.*; import org.apache.commons.collections4.map.*; import org.lockss.util.*; /** * Collection of metadata about a single article or other feature. Consists of * two maps that associate one or more string values with a string key. The raw * map should hold the raw keys and values extracted from one or more (html, * xml, etc.) files; the cooked map holds standard metadata (DOI, ISSN, etc.) * associated with well-known keys. */ public class ArticleMetadata { private static Logger log = Logger.getLogger("ArticleMetadata"); private MultiValueMap rawMap = new MultiValueMap(); private MultiValueMap cookedmap = new MultiValueMap(); private Locale locale; public ArticleMetadata() { } public void setLocale(Locale locale) { if (cookedmap.isEmpty()) { this.locale = locale; } else { throw new IllegalStateException( "Cannot set locale after storing any cooked metadata"); } } /** * Return the Locale in which values (e.g., dates) in this metadata should be * interpreted. Returns the systemwide default from (@link * MetadataUtil#getDefaultLocale()} if no Locale has't been explicitly set * with {@link #setLocale(Locale)}. */ public Locale getLocale() { return locale != null ? locale : MetadataUtil.getDefaultLocale(); } /* * Accessors ensure that metadata keys are case-insensitive strings * (lowercased). */ // Raw map /** * Set or add to the value associated with the key in the raw metadata map. */ public void putRaw(String key, String value) { rawMap.put(key.toLowerCase(), value); } /** * Set the value associated with the key in the raw metadata map. */ public void putRaw(String key, Map<String, String> value) { rawMap.put(key.toLowerCase(), value); } /** * Return the list of raw values associated with a key, or an empty list. */ public List<String> getRawList(String key) { return getRawCollection(key); } /** * Return the map of raw values associated with a key, or an empty map if none. */ public Map<String, String> getRawMap(MetadataField field) { return getRawMap(field.getKey()); } /** * Return the map of raw values associated with a key, or an empty map if none. */ public Map<String, String> getRawMap(String key) { List<Map<String, String>> lst = (List<Map<String, String>>)rawMap.get(key); if (lst == null || lst.isEmpty()) { return Collections.<String, String> emptyMap(); } return lst.get(0); } /** * Return the first or only raw value associated with a key, else null if * none. */ public String getRaw(String key) { List<String> lst = getRawCollection(key); if (lst.isEmpty()) { return null; } else { return lst.get(0); } } /** Return true if the key has an associated value in the raw map */ public boolean containsRawKey(String key) { return rawMap.containsKey(key.toLowerCase()); } /** Return the set of keys in the raw map */ public Set<String> rawKeySet() { return rawMap.keySet(); } /** Return the raw Entry set */ public Set<Map.Entry<String, List<String>>> rawEntrySet() { return rawMap.entrySet(); } /** Return the size of the raw map */ public int rawSize() { return rawMap.size(); } private List<String> getRawCollection(String key) { List<String> res = getMapCollection(rawMap, key); if (res == null || res.isEmpty()) { return Collections.<String> emptyList(); } return res; } private List<String> getMapCollection(MultiValueMap map, String key) { return (List<String>) map.getCollection(key.toLowerCase()); } // Cooked map /** * Set or add to the value associated with the key. If the field has a * validator/normalizer it will be applied to the value first. Returns true * iff the value validates and is stored successfully. * * <h4>Single-valued fields</h4>A valid value will be stored if either no * value is already present or the new value is equal to the current value. If * a different value is present nothing is stored. <br> * A raw value that doesn't validate will be stored as an {@link InvalidValue} * along with the validation exception, iff no valid value is already present. * (See {@link #hasValidValue(MetadataField)}, * {@link #hasInvalidValue(MetadataField)} and {@link #get(MetadataField)}.) * * <h4>Multi-valued fields</h4>A valid value will be added and true returned; * an invalid valid will not be stored, and false returned. If the field has a * splitter it will be invoked to convert the value into a list of values. If * there is also a validator/normalizer, it will be invoked on each split * value. If any of them fails to validate the behavior is undefined. */ public boolean put(MetadataField field, String value) { MetadataException ex = put0(field, value); return ex == null; } /** * Set or add to the value associated with the key. If the field has a * validator/normalizer it will be applied to the value first. Throws * MetadataException if the value does not validate or is not stored * successfully * * <h4>Single-valued fields</h4>A valid value will be stored if either no * value is already present or the new value is equal to the current value. If * a different value is present nothing is stored and a * MetadataException.CardinalityException is thrown. <br> * A raw value that doesn't validate will cause a * MetadataException.ValidationException to be thrown. If no valid value is * already present. the invalid raw value will be stored as an * {@link InvalidValue} along with the validation exception. (See * {@link #hasValidValue(MetadataField)}, * {@link #hasInvalidValue(MetadataField)} and {@link #get(MetadataField)}.) * * <h4>Multi-valued fields</h4>A valid value will be added. An invalid valid * will not be added, and a validation exception will be thrown. If the field * has a splitter it will be invoked to convert the value into a list of * values. If there is also a validator/normalizer, it will be invoked on each * split value. If any of them fails to validate the behavior is undefined. */ public void putValid(MetadataField field, String value) throws MetadataException { MetadataException ex = put0(field, value); if (ex != null) { throw ex; } } /** Store the value in the ArticleMetadata unless it's null or the field * already has a valid value. I.e., store the value iff it's better than * the one that's already there. * @param field The MetadataField into which to store * @param val the value to store * @returns true if the value was stored */ public boolean putIfBetter(MetadataField field, String value) { if (value != null && !hasValidValue(field)) { put(field, value); return true; } return false; } /** Store the value in the ArticleMetadata, replacing any previous value. * @param field The MetadataField into which to store * @param val the value to store * @returns true */ public boolean replace(MetadataField field, String value) { putSingle(field, value, true); return true; } private MetadataException put0(MetadataField field, String value) { switch (field.getCardinality()) { case Single: return putSingle(field, value, false); case Multi: return putMulti(field, value); } return new MetadataException("Unknown field type: " + field.getCardinality()).setField(field); } private String getKey(MetadataField field) { return field.getKey().toLowerCase(); } private MetadataException putSingle(MetadataField field,final String value, boolean force) { String key = getKey(field); MetadataException valEx = null; String normVal = null; try { if(field.hasExtractor()){ try{ String val = field.extract(this, value); normVal = field.validate(this, val); }catch(IndexOutOfBoundsException e){ MetadataException ex = new MetadataException.CardinalityException(value, "Attempt to reset single-valued key: " + key + " to " + value); ex.setField(field); ex.setNormalizedValue(normVal); ex.setRawValue(value); throw ex; } } else{ normVal = field.validate(this, value); } List curval = getCollection(key); if (curval.isEmpty()) { cookedmap.put(key, normVal); return null; } else if (force || isInvalid(curval.get(0))) { cookedmap.remove(key); cookedmap.put(key, normVal); return null; } else if (value.equals(curval.get(0))) { return null; } MetadataException ex = new MetadataException.CardinalityException(value, "Attempt to reset single-valued key: " + key + " to " + value); ex.setField(field); ex.setNormalizedValue(normVal); ex.setRawValue(value); return ex; } catch (MetadataException ex) { if (getCollection(key).isEmpty()) { InvalidValue ival = new InvalidValue(value, ex); cookedmap.put(key, ival); } ex.setField(field); ex.setRawValue(value); return ex; } } private MetadataException putMulti(MetadataField field, String value) { String key = getKey(field); MetadataException valEx = null; String normVal; if (field.hasSplitter()) { MetadataException elemEx = null; for (String elem : field.split(this, value)) { try { String normElem = field.validate(this, elem); cookedmap.put(key, normElem); } catch (MetadataException.ValidationException ex) { if (elemEx == null) { elemEx = ex; } } } return elemEx; } try { normVal = field.validate(this, value); cookedmap.put(key, normVal); return null; } catch (MetadataException.ValidationException ex) { ex.setRawValue(value); ex.setField(field); return ex; } } /** * Return true iff the field has either a valid value or an invalid value */ public boolean hasValue(MetadataField field) { List curval = getCollection(getKey(field)); return !curval.isEmpty(); } /** Return true iff the field has a valid value */ public boolean hasValidValue(MetadataField field) { List curval = getCollection(getKey(field)); return !curval.isEmpty() && !isInvalid(curval.get(0)); } /** Return true iff the field has a value, which is invalid */ public boolean hasInvalidValue(MetadataField field) { List curval = getCollection(getKey(field)); return !curval.isEmpty() && isInvalid(curval.get(0)); } private boolean isValid(Object obj) { return !(obj instanceof InvalidValue); } private boolean isInvalid(Object obj) { return obj instanceof InvalidValue; } /** If the field has an invalid value, return the {@link InvalidValue} * describing it, else null */ public InvalidValue getInvalid(MetadataField field) { return getInvalid(field.getKey()); } /** * If the key has an invalid value, return the {@link InvalidValue} * describing it, else null */ private InvalidValue getInvalid(String key) { List lst = getCollection(key); if (lst.isEmpty()) { return null; } Object res = lst.get(0); if (res instanceof InvalidValue) { return (InvalidValue) res; } return null; } /** Return the value associated with a key, else null if no valid value */ public String get(MetadataField field) { return get(field.getKey()); } /** * Return the list of values associated with a key, or an empty list if none. */ public List<String> getList(String key) { List lst = getCollection(key); if (lst.isEmpty() || lst.get(0) instanceof InvalidValue) { return Collections.<String> emptyList(); } return lst; } /** * Return the list of values associated with a key,or an empty list if none */ public List<String> getList(MetadataField field) { return getList(field.getKey()); } /** Return the value associated with a key, else null if no valid value */ public String get(String key) { return get(key, null); } /** * Return the value associated with a key, else dfault if no valid value */ private String get(String key, String dfault) { List lst = getCollection(key); if (lst.isEmpty()) { return dfault; } Object res = lst.get(0); if (res instanceof String) { return (String) res; } if (res instanceof InvalidValue) { return null; } return null; } /** Return the keyset of the cooked map */ public Set<String> keySet() { return cookedmap.keySet(); } // Simple entrySet would return keys of invalid values, not clear that's good. // public Set<Map.Entry<String,List<String>>> entrySet() { // return cookedmap.entrySet(); /** Return the size of the cooked map */ public int size() { return cookedmap.size(); } /** Return true if the cooked map is empty */ public boolean isEmpty() { return cookedmap.isEmpty(); } /** * Copies values from the raw metadata map to the cooked map according to the * supplied map. Any MetadataExceptions thrown while storing into the cooked * map are returned in a List. * * @param rawToCooked * maps raw key -> cooked MatadataField. */ public List<MetadataException> cook(MultiMap rawToCooked) { List<MetadataException> errors = new ArrayList<MetadataException>(); for (Map.Entry ent : (Collection<Map.Entry<String, Collection<MetadataField>>>) (rawToCooked.entrySet())) { String rawKey = (String) ent.getKey(); Collection<MetadataField> fields = (Collection) ent.getValue(); for (MetadataField field : fields) { cookField(rawKey, field, errors); } } return errors; } /** * Copies values from the raw metadata map to the cooked map according to the * supplied map. Any MetadataExceptions thrown while storing into the cooked * map are returned in a List. * * @param rawToCooked * maps raw key -> cooked MatadataField. * @deprecated Switch to commons collections4 and use {@link * #cook(org.apache.commons.collections4.map.MultiMap)} */ @Deprecated public List<MetadataException> cook(org.apache.commons.collections.MultiMap rawToCooked) { List<MetadataException> errors = new ArrayList<MetadataException>(); for (Map.Entry ent : (Collection<Map.Entry<String, Collection<MetadataField>>>) (rawToCooked.entrySet())) { String rawKey = (String) ent.getKey(); Collection<MetadataField> fields = (Collection) ent.getValue(); for (MetadataField field : fields) { cookField(rawKey, field, errors); } } return errors; } private void cookField(String rawKey, MetadataField field, List<MetadataException> errors) { List<String> rawlst = getRawCollection(rawKey); if (!rawlst.isEmpty()) { for (String rawval : rawlst) { try { putValid(field, rawval); } catch (MetadataException ex) { errors.add(ex); } } } } private MetadataField findField(String key) { key = key.toLowerCase(); MetadataField res = MetadataField.findField(key); return (res != null) ? res : new MetadataField.Default(key); } private List getCollection(String key) { List<String> res = getMapCollection(cookedmap, key); if (res == null || res.isEmpty()) { return Collections.EMPTY_LIST; } return res; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[md:"); for (String key : keySet()) { sb.append(" ["); sb.append(key); sb.append(": "); List lst = getCollection(key); if (lst.isEmpty()) { sb.append("(null)"); } else if (lst.get(0) instanceof InvalidValue) { sb.append(lst.get(0)); } else { sb.append(lst); } sb.append("]"); } return sb.toString(); } /** Return a pretty printed String */ public String ppString(int indent) { StringBuilder sb = new StringBuilder(); String tab = StringUtil.tab(indent); sb.append(tab); if (cookedmap.isEmpty()) { sb.append("Metadata (empty)\n"); } else { sb.append("Metadata\n"); dumpMap(sb, cookedmap, indent + 2); } sb.append(tab); if (rawMap.isEmpty()) { sb.append("Raw Metadata (empty)\n"); } else { sb.append("Raw Metadata\n"); dumpMap(sb, rawMap, indent + 2); } return sb.toString(); } private void dumpMap(StringBuilder sb, MultiValueMap map, int indent) { String tab = StringUtil.tab(indent); for (String key : StringUtil.caseIndependentSortedSet((Set<String>)map.keySet())) { sb.append(tab); sb.append(key); sb.append(": "); List lst = getMapCollection(map, key); if (lst.isEmpty()) { sb.append("(null)"); } else if (lst.size() == 1 || lst.get(0) instanceof InvalidValue) { sb.append(lst.get(0)); } else { sb.append("["); sb.append(StringUtil.separatedString(lst, "; ")); sb.append("]"); } sb.append("\n"); } } /** * Record of a failed attempt to store a value in the cooked map, either * because the value didn't validate or a second store isn't allowed in a * Single cardinality field */ public static class InvalidValue { private String rawValue; private MetadataException ex; public InvalidValue(String rawValue, MetadataException ex) { this.rawValue = rawValue; this.ex = ex; } /** Return the raw value that was attempted to be stored. */ public String getRawValue() { return rawValue; } /** Return the exception thrown by the validator. */ public MetadataException getException() { return ex; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[inv: "); sb.append(rawValue); sb.append(", "); sb.append(ex.toString()); sb.append("]"); return sb.toString(); } } }
package org.jmmo.util; import org.jmmo.util.impl.FilesIterator; import java.nio.file.DirectoryStream; import java.nio.file.Path; import java.util.*; import java.util.concurrent.Callable; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class StreamUtil { private StreamUtil() {} @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public static <T> Stream<T> optional(Optional<T> optional) { return optional.map(Stream::of).orElseGet(Stream::empty); } public static <T> Stream<T> nullable(T value) { return value == null ? Stream.empty() : Stream.of(value); } public static <T> Stream<T> fromIterator(Iterator<T> iterator) { return fromIterator(iterator, 0); } public static <T> Stream<T> fromIterator(Iterator<T> iterator, int characteristics) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, characteristics), false); } public static <T> Stream<T> supply(Supplier<T> supplier) { return fromIterator(new Iterator<T>() { boolean prepared; T current; @Override public boolean hasNext() { if (!prepared) { prepared = true; current = supplier.get(); } return current != null; } @Override public T next() { if (hasNext()) { prepared = false; return current; } else { throw new NoSuchElementException(); } } }, Spliterator.NONNULL); } public static Stream<MatchResult> matchResults(Matcher matcher) { return supply(() -> matcher.find() ? matcher.toMatchResult() : null); } public static Stream<String> matchGroups(Matcher matcher) { return matchGroups(matcher, 1); } public static Stream<String> matchGroups(Matcher matcher, int group) { return supply(() -> matcher.find() ? matcher.group(group) : null); } public static Stream<Throwable> causes(Throwable throwable) { return supply(new Supplier<Throwable>() { Throwable next = throwable; @Override public Throwable get() { final Throwable current = next; if (current != null) { next = current.getCause(); } return current; } }); } /** * Finds files within a given directory and its subdirectories. */ public static Stream<Path> files(Path directory) { return fromIterator(new FilesIterator(directory), Spliterator.NONNULL); } /** * Finds files within a given directory and its subdirectories. * The files are filtered by matching the String representation of their file names against the given globbing pattern. */ public static Stream<Path> files(Path directory, String glob) { return fromIterator(new FilesIterator(directory, glob), Spliterator.NONNULL); } /** * Finds files within a given directory and its subdirectories. * The files are filtered by the given filter */ public static Stream<Path> files(Path directory, DirectoryStream.Filter<Path> filter) { return fromIterator(new FilesIterator(filter, directory), Spliterator.NONNULL); } /** * Throws checked exceptions like unchecked ones * @param ex any exception * @param <R> fake result type * @param <T> exception type * @return never returns * @throws T */ @SuppressWarnings("unchecked") public static <R, T extends Throwable> R sneakyThrow(Throwable ex) throws T { throw (T) ex; } /** * Prevent necessity to check exceptions from lambdas that return some result * @param callable some lambda throwing checked exception * @param <R> result type * @return lambda result */ public static <R> R unchecked(Callable<R> callable) { try { return callable.call(); } catch (Exception ex) { return sneakyThrow(ex); } } /** * Runnable that throw some exception */ @FunctionalInterface public interface ThrowableRunnable { void run() throws Exception; } /** * Prevent necessity to check exceptions from lambdas that don't return any result * @param runnable some lambda throwing checked exception */ public static void unchecked(ThrowableRunnable runnable) { try { runnable.run(); } catch (Exception ex) { sneakyThrow(ex); } } /** * Prevent necessity to check exceptions from lambdas that don't return any result, * then return null of required type * @param runnable some lambda throwing checked exception * @param <T> return value type * @return null value of T type */ public static <T> T uncheckedNull(ThrowableRunnable runnable) { try { runnable.run(); } catch (Exception ex) { sneakyThrow(ex); } return null; } /** * Prevent necessity to check exceptions from lambdas that return some result and ignore result * @param callable some lambda throwing checked exception * @param <R> ignored result type */ public static <R> void uncheckedVoid(Callable<R> callable) { try { callable.call(); } catch (Exception ex) { sneakyThrow(ex); } } /** * Executes runnable then return null of required type * @param runnable some code * @param <T> return value type * @return null value of T type */ public static <T> T result(Runnable runnable) { runnable.run(); return null; } /** * Executes something that returns result and ignore result * @param supplier Something that returns result * @param <T> ignored result type */ public static <T> void resultVoid(Supplier<T> supplier) { supplier.get(); } /** * Returns an iterator consisting of the results of applying the given * function to the elements of this iterator. * @param iterator source iterator * @param mapper function to apply to each element * @return new iterator */ public static <T, R> Iterator<R> iteratorMap(Iterator<T> iterator, Function<? super T, ? extends R> mapper) { return new Iterator<R>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public R next() { return mapper.apply(iterator.next()); } @Override public void remove() { iterator.remove(); } }; } /** * Returns an iterator consisting of the elements of this stream that match * the given predicate. * @param iterator source iterator * @param predicate predicate to apply to each element to determine if it should be included * @return new iterator */ public static <T> Iterator<T> iteratorFilter(Iterator<T> iterator, Predicate<? super T> predicate) { return new Iterator<T>() { T next; boolean hasNext; @Override public boolean hasNext() { if (hasNext) { return true; } while (iterator.hasNext()) { next = iterator.next(); if (predicate.test(next)) { hasNext = true; return true; } } return false; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } hasNext = false; return next; } @Override public void remove() { if (!hasNext()) { throw new NoSuchElementException(); } iterator.remove(); } }; } /** * Returns an iterator consisting of the results of replacing each element of * this iterator with the contents of a mapped iterator produced by applying * the provided mapping function to each element. * @param iterator source iterator * @param mapper function to apply to each element * @return new iterator */ public static <T, R> Iterator<R> iteratorFlatMap(Iterator<T> iterator, Function<? super T, ? extends Iterator<? extends R>> mapper) { return new Iterator<R>() { Iterator<? extends R> current = Collections.emptyIterator(); @Override public boolean hasNext() { if (current.hasNext()) { return true; } if (!iterator.hasNext()) { return false; } current = mapper.apply(iterator.next()); return hasNext(); } @Override public R next() { if (!hasNext()) { throw new NoSuchElementException(); } return current.next(); } @Override public void remove() { if (!hasNext()) { throw new NoSuchElementException(); } current.remove(); } }; } }
package org.jsoup.nodes; import org.jsoup.helper.DataUtil; import org.jsoup.helper.Validate; import org.jsoup.internal.StringUtil; import org.jsoup.parser.ParseSettings; import org.jsoup.parser.Parser; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import org.jsoup.select.Evaluator; import javax.annotation.Nullable; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.ArrayList; import java.util.List; /** A HTML Document. @author Jonathan Hedley, jonathan@hedley.net */ public class Document extends Element { private OutputSettings outputSettings = new OutputSettings(); private Parser parser; // the parser used to parse this document private QuirksMode quirksMode = QuirksMode.noQuirks; private String location; private boolean updateMetaCharset = false; /** Create a new, empty Document. @param baseUri base URI of document @see org.jsoup.Jsoup#parse @see #createShell */ public Document(String baseUri) { super(Tag.valueOf("#root", ParseSettings.htmlDefault), baseUri); this.location = baseUri; this.parser = Parser.htmlParser(); // default, but overridable } /** Create a valid, empty shell of a document, suitable for adding more elements to. @param baseUri baseUri of document @return document with html, head, and body elements. */ public static Document createShell(String baseUri) { Validate.notNull(baseUri); Document doc = new Document(baseUri); doc.parser = doc.parser(); Element html = doc.appendElement("html"); html.appendElement("head"); html.appendElement("body"); return doc; } /** * Get the URL this Document was parsed from. If the starting URL is a redirect, * this will return the final URL from which the document was served from. * @return location */ public String location() { return location; } /** * Returns this Document's doctype. * @return document type, or null if not set */ public @Nullable DocumentType documentType() { for (Node node : childNodes) { if (node instanceof DocumentType) return (DocumentType) node; else if (!(node instanceof LeafNode)) // scans forward across comments, text, processing instructions etc break; } return null; // todo - add a set document type? } /** Find the root HTML element, or create it if it doesn't exist. @return the root HTML element. */ private Element htmlEl() { for (Element el: childElementsList()) { if (el.normalName().equals("html")) return el; } return appendElement("html"); } /** Get this document's {@code head} element. <p> As a side-effect, if this Document does not already have a HTML structure, it will be created. If you do not want that, use {@code #selectFirst("head")} instead. @return {@code head} element. */ public Element head() { Element html = htmlEl(); for (Element el: html.childElementsList()) { if (el.normalName().equals("head")) return el; } return html.prependElement("head"); } /** Get this document's {@code <body>} or {@code <frameset>} element. <p> As a <b>side-effect</b>, if this Document does not already have a HTML structure, it will be created with a {@code <body>} element. If you do not want that, use {@code #selectFirst("body")} instead. @return {@code body} element for documents with a {@code <body>}, a new {@code <body>} element if the document had no contents, or the outermost {@code <frameset> element} for frameset documents. */ public Element body() { Element html = htmlEl(); for (Element el: html.childElementsList()) { if ("body".equals(el.normalName()) || "frameset".equals(el.normalName())) return el; } return html.appendElement("body"); } /** Get the string contents of the document's {@code title} element. @return Trimmed title, or empty string if none set. */ public String title() { // title is a preserve whitespace tag (for document output), but normalised here Element titleEl = head().selectFirst(titleEval); return titleEl != null ? StringUtil.normaliseWhitespace(titleEl.text()).trim() : ""; } private static final Evaluator titleEval = new Evaluator.Tag("title"); /** Set the document's {@code title} element. Updates the existing element, or adds {@code title} to {@code head} if not present @param title string to set as title */ public void title(String title) { Validate.notNull(title); Element titleEl = head().selectFirst(titleEval); if (titleEl == null) // add to head titleEl = head().appendElement("title"); titleEl.text(title); } /** Create a new Element, with this document's base uri. Does not make the new element a child of this document. @param tagName element tag name (e.g. {@code a}) @return new element */ public Element createElement(String tagName) { return new Element(Tag.valueOf(tagName, ParseSettings.preserveCase), this.baseUri()); } /** Normalise the document. This happens after the parse phase so generally does not need to be called. Moves any text content that is not in the body element into the body. @return this document after normalisation */ public Document normalise() { Element htmlEl = htmlEl(); // these all create if not found Element head = head(); body(); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normaliseTextNodes(head); normaliseTextNodes(htmlEl); normaliseTextNodes(this); normaliseStructure("head", htmlEl); normaliseStructure("body", htmlEl); ensureMetaCharsetElement(); return this; } // does not recurse. private void normaliseTextNodes(Element element) { List<Node> toMove = new ArrayList<>(); for (Node node: element.childNodes) { if (node instanceof TextNode) { TextNode tn = (TextNode) node; if (!tn.isBlank()) toMove.add(tn); } } for (int i = toMove.size()-1; i >= 0; i Node node = toMove.get(i); element.removeChild(node); body().prependChild(new TextNode(" ")); body().prependChild(node); } } // merge multiple <head> or <body> contents into one, delete the remainder, and ensure they are owned by <html> private void normaliseStructure(String tag, Element htmlEl) { Elements elements = this.getElementsByTag(tag); Element master = elements.first(); // will always be available as created above if not existent if (elements.size() > 1) { // dupes, move contents to master List<Node> toMove = new ArrayList<>(); for (int i = 1; i < elements.size(); i++) { Node dupe = elements.get(i); toMove.addAll(dupe.ensureChildNodes()); dupe.remove(); } for (Node dupe : toMove) master.appendChild(dupe); } // ensure parented by <html> if (master.parent() != null && !master.parent().equals(htmlEl)) { htmlEl.appendChild(master); // includes remove() } } @Override public String outerHtml() { return super.html(); // no outer wrapper tag } /** Set the text of the {@code body} of this document. Any existing nodes within the body will be cleared. @param text unencoded text @return this document */ @Override public Element text(String text) { body().text(text); // overridden to not nuke doc structure return this; } @Override public String nodeName() { return "#document"; } /** * Sets the charset used in this document. This method is equivalent * to {@link OutputSettings#charset(java.nio.charset.Charset) * OutputSettings.charset(Charset)} but in addition it updates the * charset / encoding element within the document. * * <p>This enables * {@link #updateMetaCharsetElement(boolean) meta charset update}.</p> * * <p>If there's no element with charset / encoding information yet it will * be created. Obsolete charset / encoding definitions are removed!</p> * * <p><b>Elements used:</b></p> * * <ul> * <li><b>Html:</b> <i>&lt;meta charset="CHARSET"&gt;</i></li> * <li><b>Xml:</b> <i>&lt;?xml version="1.0" encoding="CHARSET"&gt;</i></li> * </ul> * * @param charset Charset * * @see #updateMetaCharsetElement(boolean) * @see OutputSettings#charset(java.nio.charset.Charset) */ public void charset(Charset charset) { updateMetaCharsetElement(true); outputSettings.charset(charset); ensureMetaCharsetElement(); } /** * Returns the charset used in this document. This method is equivalent * to {@link OutputSettings#charset()}. * * @return Current Charset * * @see OutputSettings#charset() */ public Charset charset() { return outputSettings.charset(); } /** * Sets whether the element with charset information in this document is * updated on changes through {@link #charset(java.nio.charset.Charset) * Document.charset(Charset)} or not. * * <p>If set to <tt>false</tt> <i>(default)</i> there are no elements * modified.</p> * * @param update If <tt>true</tt> the element updated on charset * changes, <tt>false</tt> if not * * @see #charset(java.nio.charset.Charset) */ public void updateMetaCharsetElement(boolean update) { this.updateMetaCharset = update; } /** * Returns whether the element with charset information in this document is * updated on changes through {@link #charset(java.nio.charset.Charset) * Document.charset(Charset)} or not. * * @return Returns <tt>true</tt> if the element is updated on charset * changes, <tt>false</tt> if not */ public boolean updateMetaCharsetElement() { return updateMetaCharset; } @Override public Document clone() { Document clone = (Document) super.clone(); clone.outputSettings = this.outputSettings.clone(); return clone; } /** * Ensures a meta charset (html) or xml declaration (xml) with the current * encoding used. This only applies with * {@link #updateMetaCharsetElement(boolean) updateMetaCharset} set to * <tt>true</tt>, otherwise this method does nothing. * * <ul> * <li>An existing element gets updated with the current charset</li> * <li>If there's no element yet it will be inserted</li> * <li>Obsolete elements are removed</li> * </ul> * * <p><b>Elements used:</b></p> * * <ul> * <li><b>Html:</b> <i>&lt;meta charset="CHARSET"&gt;</i></li> * <li><b>Xml:</b> <i>&lt;?xml version="1.0" encoding="CHARSET"&gt;</i></li> * </ul> */ private void ensureMetaCharsetElement() { if (updateMetaCharset) { OutputSettings.Syntax syntax = outputSettings().syntax(); if (syntax == OutputSettings.Syntax.html) { Element metaCharset = selectFirst("meta[charset]"); if (metaCharset != null) { metaCharset.attr("charset", charset().displayName()); } else { head().appendElement("meta").attr("charset", charset().displayName()); } select("meta[name=charset]").remove(); // Remove obsolete elements } else if (syntax == OutputSettings.Syntax.xml) { Node node = childNodes().get(0); if (node instanceof XmlDeclaration) { XmlDeclaration decl = (XmlDeclaration) node; if (decl.name().equals("xml")) { decl.attr("encoding", charset().displayName()); if (decl.hasAttr("version")) decl.attr("version", "1.0"); } else { decl = new XmlDeclaration("xml", false); decl.attr("version", "1.0"); decl.attr("encoding", charset().displayName()); prependChild(decl); } } else { XmlDeclaration decl = new XmlDeclaration("xml", false); decl.attr("version", "1.0"); decl.attr("encoding", charset().displayName()); prependChild(decl); } } } } /** * A Document's output settings control the form of the text() and html() methods. */ public static class OutputSettings implements Cloneable { /** * The output serialization syntax. */ public enum Syntax {html, xml} private Entities.EscapeMode escapeMode = Entities.EscapeMode.base; private Charset charset = DataUtil.UTF_8; private final ThreadLocal<CharsetEncoder> encoderThreadLocal = new ThreadLocal<>(); // initialized by start of OuterHtmlVisitor @Nullable Entities.CoreCharset coreCharset; // fast encoders for ascii and utf8 private boolean prettyPrint = true; private boolean outline = false; private int indentAmount = 1; private Syntax syntax = Syntax.html; public OutputSettings() {} /** * Get the document's current HTML escape mode: <code>base</code>, which provides a limited set of named HTML * entities and escapes other characters as numbered entities for maximum compatibility; or <code>extended</code>, * which uses the complete set of HTML named entities. * <p> * The default escape mode is <code>base</code>. * @return the document's current escape mode */ public Entities.EscapeMode escapeMode() { return escapeMode; } /** * Set the document's escape mode, which determines how characters are escaped when the output character set * does not support a given character:- using either a named or a numbered escape. * @param escapeMode the new escape mode to use * @return the document's output settings, for chaining */ public OutputSettings escapeMode(Entities.EscapeMode escapeMode) { this.escapeMode = escapeMode; return this; } /** * Get the document's current output charset, which is used to control which characters are escaped when * generating HTML (via the <code>html()</code> methods), and which are kept intact. * <p> * Where possible (when parsing from a URL or File), the document's output charset is automatically set to the * input charset. Otherwise, it defaults to UTF-8. * @return the document's current charset. */ public Charset charset() { return charset; } /** * Update the document's output charset. * @param charset the new charset to use. * @return the document's output settings, for chaining */ public OutputSettings charset(Charset charset) { this.charset = charset; return this; } /** * Update the document's output charset. * @param charset the new charset (by name) to use. * @return the document's output settings, for chaining */ public OutputSettings charset(String charset) { charset(Charset.forName(charset)); return this; } CharsetEncoder prepareEncoder() { // created at start of OuterHtmlVisitor so each pass has own encoder, so OutputSettings can be shared among threads CharsetEncoder encoder = charset.newEncoder(); encoderThreadLocal.set(encoder); coreCharset = Entities.CoreCharset.byName(encoder.charset().name()); return encoder; } CharsetEncoder encoder() { CharsetEncoder encoder = encoderThreadLocal.get(); return encoder != null ? encoder : prepareEncoder(); } /** * Get the document's current output syntax. * @return current syntax */ public Syntax syntax() { return syntax; } /** * Set the document's output syntax. Either {@code html}, with empty tags and boolean attributes (etc), or * {@code xml}, with self-closing tags. * @param syntax serialization syntax * @return the document's output settings, for chaining */ public OutputSettings syntax(Syntax syntax) { this.syntax = syntax; return this; } /** * Get if pretty printing is enabled. Default is true. If disabled, the HTML output methods will not re-format * the output, and the output will generally look like the input. * @return if pretty printing is enabled. */ public boolean prettyPrint() { return prettyPrint; } /** * Enable or disable pretty printing. * @param pretty new pretty print setting * @return this, for chaining */ public OutputSettings prettyPrint(boolean pretty) { prettyPrint = pretty; return this; } /** * Get if outline mode is enabled. Default is false. If enabled, the HTML output methods will consider * all tags as block. * @return if outline mode is enabled. */ public boolean outline() { return outline; } /** * Enable or disable HTML outline mode. * @param outlineMode new outline setting * @return this, for chaining */ public OutputSettings outline(boolean outlineMode) { outline = outlineMode; return this; } /** * Get the current tag indent amount, used when pretty printing. * @return the current indent amount */ public int indentAmount() { return indentAmount; } /** * Set the indent amount for pretty printing * @param indentAmount number of spaces to use for indenting each level. Must be {@literal >=} 0. * @return this, for chaining */ public OutputSettings indentAmount(int indentAmount) { Validate.isTrue(indentAmount >= 0); this.indentAmount = indentAmount; return this; } @Override public OutputSettings clone() { OutputSettings clone; try { clone = (OutputSettings) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } clone.charset(charset.name()); // new charset and charset encoder clone.escapeMode = Entities.EscapeMode.valueOf(escapeMode.name()); // indentAmount, prettyPrint are primitives so object.clone() will handle return clone; } } /** * Get the document's current output settings. * @return the document's current output settings. */ public OutputSettings outputSettings() { return outputSettings; } /** * Set the document's output settings. * @param outputSettings new output settings. * @return this document, for chaining. */ public Document outputSettings(OutputSettings outputSettings) { Validate.notNull(outputSettings); this.outputSettings = outputSettings; return this; } public enum QuirksMode { noQuirks, quirks, limitedQuirks } public QuirksMode quirksMode() { return quirksMode; } public Document quirksMode(QuirksMode quirksMode) { this.quirksMode = quirksMode; return this; } /** * Get the parser that was used to parse this document. * @return the parser */ public Parser parser() { return parser; } /** * Set the parser used to create this document. This parser is then used when further parsing within this document * is required. * @param parser the configured parser to use when further parsing is required for this document. * @return this document, for chaining. */ public Document parser(Parser parser) { this.parser = parser; return this; } }
package org.opencms.rmi; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.PrintStream; import java.io.StreamTokenizer; import java.io.StringReader; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Client application used to connect locally to the CmsShell server.<p> */ public class CmsRemoteShellClient { /** Command parameter for passing an additional shell commands class name. */ public static final String PARAM_ADDITIONAL = "additional"; /** Command parameter for controlling the port to use for the initial RMI lookup. */ public static final String PARAM_REGISTRY_PORT = "registryPort"; /** Command parameter for passing a shell script file name. */ public static final String PARAM_SCRIPT = "script"; /** The name of the additional commands class. */ private String m_additionalCommands; /** True if echo mode is turned on. */ private boolean m_echo; /** The error code which should be returned in case of errors. */ private int m_errorCode; /** True if exit was called. */ private boolean m_exitCalled; /** True if an error occurred. */ private boolean m_hasError; /** The input stream to read the commands from. */ private InputStream m_input; /** Controls whether shell is interactive. */ private boolean m_interactive; /** The output stream. */ private PrintStream m_out; /** The prompt. */ private String m_prompt; /** The port used for the RMI registry. */ private int m_registryPort; /** The RMI referencce to the shell server. */ private I_CmsRemoteShell m_remoteShell; /** * Creates a new instance.<p> * * @param args the parameters * @throws IOException if something goes wrong */ public CmsRemoteShellClient(String[] args) throws IOException { Map<String, String> params = parseArgs(args); String script = params.get(PARAM_SCRIPT); if (script == null) { m_interactive = true; m_input = System.in; } else { m_input = new FileInputStream(script); } m_additionalCommands = params.get(PARAM_ADDITIONAL); String port = params.get(PARAM_REGISTRY_PORT); m_registryPort = CmsRemoteShellConstants.DEFAULT_PORT; if (port != null) { try { m_registryPort = Integer.parseInt(port); if (m_registryPort < 0) { System.out.println("Invalid port: " + port); System.exit(1); } } catch (NumberFormatException e) { System.out.println("Invalid port: " + port); System.exit(1); } } } /** * Main method, which starts the shell client.<p> * * @param args the command line arguments * @throws Exception if something goes wrong */ public static void main(String[] args) throws Exception { CmsRemoteShellClient client = new CmsRemoteShellClient(args); client.run(); } /** * Validates, parses and returns the command line arguments.<p> * * @param args the command line arguments * @return the map of parsed arguments */ public Map<String, String> parseArgs(String[] args) { Map<String, String> result = new HashMap<String, String>(); Set<String> allowedKeys = new HashSet<String>( Arrays.asList(PARAM_ADDITIONAL, PARAM_SCRIPT, PARAM_REGISTRY_PORT)); for (String arg : args) { if (arg.startsWith("-")) { int eqPos = arg.indexOf("="); if (eqPos >= 0) { String key = arg.substring(1, eqPos); if (!allowedKeys.contains(key)) { wrongUsage(); } String val = arg.substring(eqPos + 1); result.put(key, val); } else { wrongUsage(); } } else { wrongUsage(); } } return result; } /** * Main loop of the shell server client.<p> * * Reads commands from either stdin or a file, executes them remotely and displays the results. * * @throws Exception if something goes wrong */ public void run() throws Exception { Registry registry = LocateRegistry.getRegistry(m_registryPort); I_CmsRemoteShellProvider provider = (I_CmsRemoteShellProvider)(registry.lookup( CmsRemoteShellConstants.PROVIDER)); m_remoteShell = provider.createShell(m_additionalCommands); m_prompt = m_remoteShell.getPrompt(); m_out = new PrintStream(System.out); try { LineNumberReader lnr = new LineNumberReader(new InputStreamReader(m_input, "UTF-8")); while (!exitCalled()) { if (m_interactive || isEcho()) { // print the prompt in front of the commands to process only when 'interactive' printPrompt(); } String line = lnr.readLine(); if (line == null) { break; } if (line.trim().startsWith(" m_out.println(line); continue; } StringReader lineReader = new StringReader(line); StreamTokenizer st = new StreamTokenizer(lineReader); st.eolIsSignificant(true); st.wordChars('*', '*'); // put all tokens into a List List<String> parameters = new ArrayList<String>(); while (st.nextToken() != StreamTokenizer.TT_EOF) { if (st.ttype == StreamTokenizer.TT_NUMBER) { parameters.add(Integer.toString(new Double(st.nval).intValue())); } else { parameters.add(st.sval); } } lineReader.close(); if (parameters.size() == 0) { // empty line, just need to check if echo is on if (isEcho()) { m_out.println(); } continue; } // extract command and arguments String command = parameters.get(0); List<String> arguments = new ArrayList<String>(parameters.subList(1, parameters.size())); // execute the command with the given arguments executeCommand(command, arguments); } } catch (Throwable t) { t.printStackTrace(); if (m_errorCode != -1) { System.exit(m_errorCode); } } } /** * Executes a command remotely, displays the command output and updates the internal state.<p> * * @param command the command * @param arguments the arguments */ private void executeCommand(String command, List<String> arguments) { try { CmsShellCommandResult result = m_remoteShell.executeCommand(command, arguments); m_out.print(result.getOutput()); updateState(result); if (m_exitCalled) { System.exit(0); } else if (m_hasError && (m_errorCode != -1)) { System.exit(m_errorCode); } } catch (RemoteException r) { r.printStackTrace(System.err); System.exit(1); } } /** * Returns true if the exit command has been called.<p> * * @return true if the exit command has been called */ private boolean exitCalled() { return m_exitCalled; } /** * Returns true if echo mode is enabled.<p> * * @return true if echo mode is enabled */ private boolean isEcho() { return m_echo; } /** * Prints the prompt.<p> */ private void printPrompt() { System.out.print(m_prompt); } /** * Updates the internal client state based on the state received from the server.<p> * * @param result the result of the last shell command execution */ private void updateState(CmsShellCommandResult result) { m_errorCode = result.getErrorCode(); m_prompt = result.getPrompt(); m_exitCalled = result.isExitCalled(); m_hasError = result.hasError(); m_echo = result.hasEcho(); } /** * Displays text which shows the valid command line parameters, and then exits. */ private void wrongUsage() { String usage = "Usage: java -cp $PATH_TO_OPENCMS_JAR org.opencms.rmi.CmsRemoteShellClient\n" + " -script=[path to script] (optional) \n" + " -registryPort=[port of RMI registry] (optional, default is " + CmsRemoteShellConstants.DEFAULT_PORT + ")\n" + " -additional=[additional commands class name] (optional)"; System.out.println(usage); System.exit(1); } }
package org.jtrfp.trcl.gpu; import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.Callable; import java.util.concurrent.Future; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.Controller; import org.jtrfp.trcl.LineSegment; import org.jtrfp.trcl.RenderMode; import org.jtrfp.trcl.Sequencer; import org.jtrfp.trcl.Tickable; import org.jtrfp.trcl.TransparentTriangleList; import org.jtrfp.trcl.Triangle; import org.jtrfp.trcl.TriangleList; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.core.TextureDescription; public class Model { // [FRAME][LIST] private ArrayList<ArrayList<Triangle>> tLists = new ArrayList<ArrayList<Triangle>>(); private ArrayList<ArrayList<Triangle>> ttLists = new ArrayList<ArrayList<Triangle>>(); private ArrayList<ArrayList<LineSegment>> lsLists = new ArrayList<ArrayList<LineSegment>>(); private TransparentTriangleList ttpList; private TriangleList tpList; private int frameDelay; private boolean smoothAnimation; public static final String UNNAMED = "[unnamed]"; private String debugName = UNNAMED; private boolean animateUV = false; private Controller controller; private final TR tr; private long animationUpdateThresholdMillis = 0; private static final long ANIMATION_UPDATE_INTERVAL = 10; private final ArrayList<Tickable> tickableAnimators = new ArrayList<Tickable>(); private volatile boolean animated=false; private boolean modelFinalized = false; private Future<Model> finalizedModel; //Keeps hard references to Textures to keep them from getting gobbled. private final HashSet<TextureDescription> textures = new HashSet<TextureDescription>(); public Model(boolean smoothAnimation, TR tr, String debugName) { this.tr = tr; this.smoothAnimation = smoothAnimation; this.debugName = debugName; // Frame zero tLists.add(new ArrayList<Triangle>()); lsLists.add(new ArrayList<LineSegment>()); ttLists.add(new ArrayList<Triangle>()); } public TriangleList getTriangleList() { try{finalizedModel.get();} catch(Exception e){throw new RuntimeException(e);} return tpList; } public TransparentTriangleList getTransparentTriangleList() { try{finalizedModel.get();} catch(Exception e){throw new RuntimeException(e);} return ttpList; } public ArrayList<ArrayList<Triangle>> getRawTriangleLists() { return tLists; } public ArrayList<ArrayList<Triangle>> getRawTransparentTriangleLists() { return ttLists; } ArrayList<ArrayList<LineSegment>> getRawLineSegmentLists() { return lsLists; } public Vector3D getMaximumVertexDims(){ double maxX=0,maxY=0,maxZ = 0; final TransparentTriangleList ttList = getTransparentTriangleList(); if(ttList != null){ final Vector3D mV = ttList.getMaximumVertexDims(); maxX = mV.getX(); maxY = mV.getY(); maxZ = mV.getZ(); } final TriangleList tList = getTriangleList(); if(tList != null){ final Vector3D mV = tList.getMaximumVertexDims(); maxX = Math.max(mV.getX(),maxX); maxY = Math.max(mV.getY(),maxY); maxZ = Math.max(mV.getZ(),maxZ); } return new Vector3D(maxX,maxY,maxZ); }//end getMaximumVertexValue() /** * Sets up formal GPU primitive lists * * @return */ public Future<Model> finalizeModel() { return finalizedModel = tr.getThreadManager().submitToThreadPool(new Callable<Model>(){ @Override public Model call() throws Exception { Future<Void> tpFuture=null, ttpFuture=null; if(modelFinalized) return Model.this; modelFinalized = true; if(animated)//Discard frame zero {tLists.remove(0);ttLists.remove(0);} Controller c = controller; {//Start scope numFrames final int numFrames = tLists.size(); if (c == null) {if(frameDelay==0)frameDelay=1; c = new Sequencer(getFrameDelayInMillis(), numFrames, true);} Triangle[][] tris = new Triangle[numFrames][]; for (int i = 0; i < numFrames; i++) { tris[i] = tLists.get(i).toArray(new Triangle[] {}); assert tris[i]!=null:"tris intolerably null";//Verify poss. race condition. for(Triangle triangle:tLists.get(i)) textures.add(triangle.texture); }// Get all frames for each triangle if (tris[0].length != 0) { tpList = new TriangleList(tris, getFrameDelayInMillis(), "Model."+debugName, animateUV, c, tr, Model.this); tpFuture = tpList.uploadToGPU(); }// end if(length!=0) else tpList = null; }//end scope numFrames {//start scope numFrames final int numFrames = ttLists.size(); Triangle[][] ttris = new Triangle[numFrames][]; for (int i = 0; i < numFrames; i++) { ttris[i] = ttLists.get(i).toArray(new Triangle[] {}); for(Triangle triangle:ttLists.get(i)) textures.add(triangle.texture); }// Get all frames for each triangle if (ttris[0].length != 0) { ttpList = new TransparentTriangleList(ttris, getFrameDelayInMillis(), debugName, animateUV, c, tr, Model.this); ttpFuture = ttpList.uploadToGPU(); }// end if(length!=0) else ttpList = null; tLists =null; ttLists=null; lsLists=null; }//end scope numframes return Model.this; }}); }// end finalizeModel() public void addFrame(Model m) { if(!animated)animated=true; // Opaque Triangles { tLists.add(m.getRawTriangleLists().get(0)); } // Transparent triangles { ttLists.add(m.getRawTransparentTriangleLists().get(0)); } // Line Segs { lsLists.add(m.getRawLineSegmentLists().get(0)); } }// end addFrame(...) /** * * @return`The time between frames in milliseconds * @since Jan 5, 2013 */ public int getFrameDelayInMillis() { return frameDelay; } /** * @param frameDelay * the frameDelay to set */ public void setFrameDelayInMillis(int frameDelayInMillis) { if(frameDelayInMillis<=0) throw new IllegalArgumentException("Frame interval in millis is intolerably zero or negative: "+frameDelayInMillis); this.frameDelay = frameDelayInMillis; } public void addTriangle(Triangle triangle) { if (triangle.isAlphaBlended()) { ttLists.get(0).add(triangle); } else tLists.get(0).add(triangle); } public void addLineSegment(LineSegment seg) { lsLists.get(0).add(seg); } public void addTriangles(Triangle[] tris) { for (Triangle t : tris) { addTriangle(t); } } public void addLineSegments(LineSegment[] lss) { for (LineSegment ls : lss) { addLineSegment(ls); } }// end addLineSegments /** * @return the smoothAnimation */ public boolean isSmoothAnimation() { return smoothAnimation; } /** * @param smoothAnimation * the smoothAnimation to set */ public void setSmoothAnimation(boolean smoothAnimation) { this.smoothAnimation = smoothAnimation; } public static Model buildCube(double w, double h, double d, TextureDescription tunnelTexturePalette, double[] origin, boolean hasAlpha, TR tr) { return buildCube(w, h, d, tunnelTexturePalette, origin, 0, 0, 1, 1, hasAlpha, tr); } public static Model buildCube(double w, double h, double d, TextureDescription tunnelTexturePalette, double[] origin, TR tr) { return buildCube(w, h, d, tunnelTexturePalette, origin, 0, 0, 1, 1, tr); } public static Model buildCube(double w, double h, double d, TextureDescription tunnelTexturePalette, double[] origin, double u0, double v0, double u1, double v1, TR tr) { return buildCube(w, h, d, tunnelTexturePalette, origin, u0, v0, u1, v1, false, tr); } public static Model buildCube(double w, double h, double d, TextureDescription tunnelTexturePalette, double[] origin, double u0, double v0, double u1, double v1, boolean hasAlpha, TR tr) { return buildCube(w,h,d,tunnelTexturePalette,origin,u0,v0,u1,v1,hasAlpha,true,tr); } public static Model buildCube(double w, double h, double d, TextureDescription tunnelTexturePalette, double[] origin, double u0, double v0, double u1, double v1, boolean hasAlpha, boolean hasNorm, TR tr) { Model m = new Model(false, tr, "Model.buildCube"); // Top m.addTriangles(Triangle.quad2Triangles( new double[] { 0 - origin[0], w - origin[0], w - origin[0], 0 - origin[0] }, new double[] { 0 - origin[1], 0 - origin[1], 0 - origin[1], 0 - origin[1] }, new double[] { 0 - origin[2], 0 - origin[2], d - origin[2], d - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.MINUS_K:Vector3D.ZERO,"Model.buildCube.front")); // Bottom m.addTriangles(Triangle.quad2Triangles( new double[] { 0 - origin[0], w - origin[0], w - origin[0], 0 - origin[0] }, new double[] { h - origin[1], h - origin[1], h - origin[1], h - origin[1] }, new double[] { d - origin[2], d - origin[2], 0 - origin[2], 0 - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.MINUS_K:Vector3D.ZERO,"Model.buildCube.front")); // Front m.addTriangles(Triangle.quad2Triangles( new double[] { 0 - origin[0],w - origin[0], w - origin[0], 0 - origin[0] }, new double[] { h - origin[1], h - origin[1], 0 - origin[1], 0 - origin[1] }, new double[] { 0 - origin[2], 0 - origin[2], 0 - origin[2],0 - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.MINUS_K:Vector3D.ZERO,"Model.buildCube.front")); // Left m.addTriangles(Triangle.quad2Triangles( new double[] { 0 - origin[0], 0 - origin[0],0 - origin[0], 0 - origin[0]}, new double[] { 0 - origin[1], 0 - origin[1], h - origin[1], h - origin[1] }, new double[] { 0 - origin[2], d - origin[2], d - origin[2], 0 - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.MINUS_I:Vector3D.ZERO,"Model.buildCube.left")); // Right m.addTriangles(Triangle.quad2Triangles(new double[] { w - origin[0], w - origin[0], w - origin[0], w - origin[0] }, new double[] { h - origin[1], h - origin[1], 0 - origin[1], 0 - origin[1] }, new double[] { 0 - origin[2], d - origin[2], d - origin[2], 0 - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.PLUS_I:Vector3D.ZERO,"Model.buildCube.right")); // Back m.addTriangles(Triangle.quad2Triangles(new double[] { 0 - origin[0], w - origin[0], w - origin[0], 0 - origin[0] }, new double[] { 0 - origin[1], 0 - origin[1], h - origin[1], h - origin[1] }, new double[] { d - origin[2], d - origin[2], d - origin[2], d - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v0, v0, v1, v1 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.PLUS_K:Vector3D.ZERO,"Model.buildCube.back")); return m; }// end buildCube /** * @return the debugName */ public String getDebugName() { return debugName; } /** * @param debugName * the debugName to set */ public void setDebugName(String debugName) { this.debugName = debugName; } /** * @return the animateUV */ public boolean isAnimateUV() { return animateUV; } /** * @param animateUV * the animateUV to set */ public void setAnimateUV(boolean animateUV) { this.animateUV = animateUV; } /** * @param controller * the controller to set */ public void setController(Controller controller) { this.controller = controller; } /** * @return the controller */ public Controller getController() { return controller; } public void proposeAnimationUpdate() { long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis > animationUpdateThresholdMillis) { synchronized(tickableAnimators){ final int size = tickableAnimators.size(); for (int i = 0; i < size; i++){ final Tickable t = tickableAnimators.get(i); if(t!=null) tickableAnimators.get(i).tick(); }//end for(animators) animationUpdateThresholdMillis = currentTimeMillis + ANIMATION_UPDATE_INTERVAL; }//end sync(tickableAnimators) }// end if(time to update) }// end proposeAnimationUpdate() public void addTickableAnimator(Tickable t) { tickableAnimators.add(t); } public double getMaximumVertexValue() { final Vector3D maxDims = getMaximumVertexDims(); double max = maxDims.getX(); max = Math.max(max,maxDims.getY()); max = Math.max(max,maxDims.getZ()); return max; }//end getMaximumVertexValue() }// end Model
package org.jtrfp.trcl.gpu; import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.Callable; import java.util.concurrent.Future; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.Controller; import org.jtrfp.trcl.LineSegment; import org.jtrfp.trcl.RenderMode; import org.jtrfp.trcl.Sequencer; import org.jtrfp.trcl.Tickable; import org.jtrfp.trcl.TransparentTriangleList; import org.jtrfp.trcl.Triangle; import org.jtrfp.trcl.TriangleList; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.core.TRFuture; public class Model { // [FRAME][LIST] private ArrayList<ArrayList<Triangle>> tLists = new ArrayList<ArrayList<Triangle>>(); private ArrayList<ArrayList<Triangle>> ttLists = new ArrayList<ArrayList<Triangle>>(); private ArrayList<ArrayList<LineSegment>> lsLists = new ArrayList<ArrayList<LineSegment>>(); private TransparentTriangleList ttpList; private TriangleList tpList; private int frameDelay; private boolean smoothAnimation; public static final String UNNAMED = "[unnamed]"; private String debugName = UNNAMED; private boolean animateUV = false; private Controller controller; private final TR tr; private long animationUpdateThresholdMillis = 0; private static final long ANIMATION_UPDATE_INTERVAL = 10; private final ArrayList<Tickable> tickableAnimators = new ArrayList<Tickable>(); private volatile boolean animated=false; private boolean modelFinalized = false; private TRFuture<Model> finalizedModel; //Keeps hard references to Textures to keep them from getting gobbled. private final HashSet<Texture> textures = new HashSet<Texture>(); public Model(boolean smoothAnimation, TR tr, String debugName) { this.tr = tr; this.smoothAnimation = smoothAnimation; this.debugName = debugName; // Frame zero tLists.add(new ArrayList<Triangle>()); lsLists.add(new ArrayList<LineSegment>()); ttLists.add(new ArrayList<Triangle>()); } public TriangleList getTriangleList() { try{finalizedModel.get();} catch(Exception e){throw new RuntimeException(e);} return tpList; } public TransparentTriangleList getTransparentTriangleList() { try{finalizedModel.get();} catch(Exception e){throw new RuntimeException(e);} return ttpList; } public ArrayList<ArrayList<Triangle>> getRawTriangleLists() { return tLists; } public ArrayList<ArrayList<Triangle>> getRawTransparentTriangleLists() { return ttLists; } ArrayList<ArrayList<LineSegment>> getRawLineSegmentLists() { return lsLists; } public Vector3D getMaximumVertexDims(){ double maxX=0,maxY=0,maxZ = 0; final TransparentTriangleList ttList = getTransparentTriangleList(); if(ttList != null){ final Vector3D mV = ttList.getMaximumVertexDims(); maxX = mV.getX(); maxY = mV.getY(); maxZ = mV.getZ(); } final TriangleList tList = getTriangleList(); if(tList != null){ final Vector3D mV = tList.getMaximumVertexDims(); maxX = Math.max(mV.getX(),maxX); maxY = Math.max(mV.getY(),maxY); maxZ = Math.max(mV.getZ(),maxZ); } return new Vector3D(maxX,maxY,maxZ); }//end getMaximumVertexValue() public Vector3D getMinimumVertexDims(){ double minX=0,minY=0,minZ=0; final TransparentTriangleList ttList = getTransparentTriangleList(); if(ttList != null){ final Vector3D mV = ttList.getMinimumVertexDims(); minX = mV.getX(); minY = mV.getY(); minZ = mV.getZ(); } final TriangleList tList = getTriangleList(); if(tList != null){ final Vector3D mV = tList.getMinimumVertexDims(); minX = Math.min(mV.getX(),minX); minY = Math.min(mV.getY(),minY); minZ = Math.min(mV.getZ(),minZ); } return new Vector3D(minX,minY,minZ); }//end getMinimumVertexValue() /** * Sets up formal GPU primitive lists * * @return */ public TRFuture<Model> finalizeModel() { if(tr == null) return null;//Mock tolerance. if(finalizedModel != null) return finalizedModel; return finalizedModel = tr.getThreadManager().submitToThreadPool(new Callable<Model>(){ @Override public Model call() throws Exception { Future<Void> tpFuture=null, ttpFuture=null; if(modelFinalized) return Model.this; modelFinalized = true; if(animated)//Discard frame zero {tLists.remove(0);ttLists.remove(0);} Controller c = controller; {//Start scope numFrames final int numFrames = tLists.size(); if (c == null) {if(frameDelay==0)frameDelay=1; setController(new Sequencer(getFrameDelayInMillis(), numFrames, true));} Triangle[][] tris = new Triangle[numFrames][]; for (int i = 0; i < numFrames; i++) { tris[i] = tLists.get(i).toArray(new Triangle[] {}); assert tris[i]!=null:"tris intolerably null";//Verify poss. race condition. for(Triangle triangle:tLists.get(i)) textures.add(triangle.texture); }// Get all frames for each triangle if (tris[0].length != 0) { tpList = new TriangleList(tris, getFrameDelayInMillis(), "Model."+debugName, animateUV, getController(), tr, Model.this); tpFuture = tpList.uploadToGPU(); }// end if(length!=0) else tpList = null; }//end scope numFrames {//start scope numFrames final int numFrames = ttLists.size(); Triangle[][] ttris = new Triangle[numFrames][]; for (int i = 0; i < numFrames; i++) { ttris[i] = ttLists.get(i).toArray(new Triangle[] {}); for(Triangle triangle:ttLists.get(i)) textures.add(triangle.texture); }// Get all frames for each triangle if (ttris[0].length != 0) { ttpList = new TransparentTriangleList(ttris, getFrameDelayInMillis(), debugName, animateUV, getController(), tr, Model.this); ttpFuture = ttpList.uploadToGPU(); }// end if(length!=0) else ttpList = null; tLists =null; ttLists=null; lsLists=null; }//end scope numframes return Model.this; }}); }// end finalizeModel() public void addFrame(Model m) { if(!animated)animated=true; // Opaque Triangles { tLists.add(m.getRawTriangleLists().get(0)); } // Transparent triangles { ttLists.add(m.getRawTransparentTriangleLists().get(0)); } // Line Segs { lsLists.add(m.getRawLineSegmentLists().get(0)); } }// end addFrame(...) /** * * @return`The time between frames in milliseconds * @since Jan 5, 2013 */ public int getFrameDelayInMillis() { return frameDelay; } /** * @param frameDelay * the frameDelay to set */ public void setFrameDelayInMillis(int frameDelayInMillis) { if(frameDelayInMillis<=0) throw new IllegalArgumentException("Frame interval in millis is intolerably zero or negative: "+frameDelayInMillis); this.frameDelay = frameDelayInMillis; } public void addTriangle(Triangle triangle) { if (triangle.isAlphaBlended()) { ttLists.get(0).add(triangle); } else tLists.get(0).add(triangle); } public void addLineSegment(LineSegment seg) { lsLists.get(0).add(seg); } public void addTriangles(Triangle[] tris) { for (Triangle t : tris) { addTriangle(t); } } public void addLineSegments(LineSegment[] lss) { for (LineSegment ls : lss) { addLineSegment(ls); } }// end addLineSegments /** * @return the smoothAnimation */ public boolean isSmoothAnimation() { return smoothAnimation; } /** * @param smoothAnimation * the smoothAnimation to set */ public void setSmoothAnimation(boolean smoothAnimation) { this.smoothAnimation = smoothAnimation; } public static Model buildCube(double w, double h, double d, Texture tunnelTexturePalette, double[] origin, boolean hasAlpha, TR tr) { return buildCube(w, h, d, tunnelTexturePalette, origin, 0, 0, 1, 1, hasAlpha, tr); } public static Model buildCube(double w, double h, double d, Texture tunnelTexturePalette, double[] origin, TR tr) { return buildCube(w, h, d, tunnelTexturePalette, origin, 0, 0, 1, 1, tr); } public static Model buildCube(double w, double h, double d, Texture tunnelTexturePalette, double[] origin, double u0, double v0, double u1, double v1, TR tr) { return buildCube(w, h, d, tunnelTexturePalette, origin, u0, v0, u1, v1, false, tr); } public static Model buildCube(double w, double h, double d, Texture tunnelTexturePalette, double[] origin, double u0, double v0, double u1, double v1, boolean hasAlpha, TR tr) { return buildCube(w,h,d,tunnelTexturePalette,origin,u0,v0,u1,v1,hasAlpha,true,tr); } public static Model buildCube(double w, double h, double d, Texture tunnelTexturePalette, double[] origin, double u0, double v0, double u1, double v1, boolean hasAlpha, boolean hasNorm, TR tr) { Model m = new Model(false, tr, "Model.buildCube"); // Top m.addTriangles(Triangle.quad2Triangles( new double[] { 0 - origin[0], w - origin[0], w - origin[0], 0 - origin[0] }, new double[] { 0 - origin[1], 0 - origin[1], 0 - origin[1], 0 - origin[1] }, new double[] { 0 - origin[2], 0 - origin[2], d - origin[2], d - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.MINUS_K:Vector3D.ZERO,"Model.buildCube.front")); // Bottom m.addTriangles(Triangle.quad2Triangles( new double[] { 0 - origin[0], w - origin[0], w - origin[0], 0 - origin[0] }, new double[] { h - origin[1], h - origin[1], h - origin[1], h - origin[1] }, new double[] { d - origin[2], d - origin[2], 0 - origin[2], 0 - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.MINUS_K:Vector3D.ZERO,"Model.buildCube.front")); // Front m.addTriangles(Triangle.quad2Triangles( new double[] { 0 - origin[0],w - origin[0], w - origin[0], 0 - origin[0] }, new double[] { h - origin[1], h - origin[1], 0 - origin[1], 0 - origin[1] }, new double[] { 0 - origin[2], 0 - origin[2], 0 - origin[2],0 - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.MINUS_K:Vector3D.ZERO,"Model.buildCube.front")); // Left m.addTriangles(Triangle.quad2Triangles( new double[] { 0 - origin[0], 0 - origin[0],0 - origin[0], 0 - origin[0]}, new double[] { 0 - origin[1], 0 - origin[1], h - origin[1], h - origin[1] }, new double[] { 0 - origin[2], d - origin[2], d - origin[2], 0 - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.MINUS_I:Vector3D.ZERO,"Model.buildCube.left")); // Right m.addTriangles(Triangle.quad2Triangles(new double[] { w - origin[0], w - origin[0], w - origin[0], w - origin[0] }, new double[] { h - origin[1], h - origin[1], 0 - origin[1], 0 - origin[1] }, new double[] { 0 - origin[2], d - origin[2], d - origin[2], 0 - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v1, v1, v0, v0 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.PLUS_I:Vector3D.ZERO,"Model.buildCube.right")); // Back m.addTriangles(Triangle.quad2Triangles(new double[] { 0 - origin[0], w - origin[0], w - origin[0], 0 - origin[0] }, new double[] { 0 - origin[1], 0 - origin[1], h - origin[1], h - origin[1] }, new double[] { d - origin[2], d - origin[2], d - origin[2], d - origin[2] }, new double[] { u0, u1, u1, u0 }, new double[] { v0, v0, v1, v1 }, tunnelTexturePalette, RenderMode.STATIC, hasAlpha, hasNorm?Vector3D.PLUS_K:Vector3D.ZERO,"Model.buildCube.back")); return m; }// end buildCube /** * @return the debugName */ public String getDebugName() { return debugName; } /** * @param debugName * the debugName to set */ public void setDebugName(String debugName) { this.debugName = debugName; } /** * @return the animateUV */ public boolean isAnimateUV() { return animateUV; } /** * @param animateUV * the animateUV to set */ public void setAnimateUV(boolean animateUV) { this.animateUV = animateUV; } /** * @param controller * the controller to set */ public void setController(Controller controller) { this.controller = controller; } /** * @return the controller */ public Controller getController() { return controller; } public void proposeAnimationUpdate() { long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis > animationUpdateThresholdMillis) { synchronized(tickableAnimators){ final int size = tickableAnimators.size(); for (int i = 0; i < size; i++){ final Tickable t = tickableAnimators.get(i); if(t!=null) tickableAnimators.get(i).tick(); }//end for(animators) animationUpdateThresholdMillis = currentTimeMillis + ANIMATION_UPDATE_INTERVAL; }//end sync(tickableAnimators) }// end if(time to update) }// end proposeAnimationUpdate() public void addTickableAnimator(Tickable t) { tickableAnimators.add(t); } public double getMaximumVertexValue() { final Vector3D maxDims = getMaximumVertexDims(); double max = maxDims.getX(); max = Math.max(max,maxDims.getY()); max = Math.max(max,maxDims.getZ()); return max; }//end getMaximumVertexValue() public double getMinimumVertexValue() { final Vector3D minDims = getMinimumVertexDims(); double min = minDims.getX(); min = Math.min(min,minDims.getY()); min = Math.min(min,minDims.getZ()); return min; }//end getMaximumVertexValue() public double getMaximumVertexValueAbs(){ return Math.max(getMaximumVertexValue(),Math.abs(getMinimumVertexValue())); }//end getMaximumVertexVAlueAbs() @Override public String toString(){ if(getDebugName()==null) return super.toString(); return "["+this.getClass().getName()+" debugName="+debugName+" hash="+hashCode()+"]"; } }// end Model
package org.lantern; import java.io.File; import java.io.IOException; import java.util.Collection; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Configures Lantern. This can be either on the first run of the application * or through the user changing his or her configurations in the configuration * screen. */ public class Configurator { private static final Logger LOG = LoggerFactory.getLogger(Configurator.class); private volatile static boolean configured = false; private static final MacProxyManager mpm = new MacProxyManager("testId", 4291); private static final String WINDOWS_REGISTRY_PROXY_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"; private static final String ps = "ProxyServer"; private static final String pe = "ProxyEnable"; private static final String LANTERN_PROXY_ADDRESS = "127.0.0.1:"+ LanternConstants.LANTERN_LOCALHOST_HTTP_PORT; private static final File PROXY_ON = new File("proxy_on.pac"); private static final File PROXY_OFF = new File("proxy_off.pac"); static { if (!PROXY_ON.isFile()) { final String msg = "No pac at: "+PROXY_ON.getAbsolutePath() +"\nfrom: " + new File(".").getAbsolutePath(); LOG.error(msg); throw new IllegalStateException(msg); } if (!PROXY_OFF.isFile()) { final String msg = "No pac at: "+PROXY_OFF.getAbsolutePath() +"\nfrom: " + new File(".").getAbsolutePath(); LOG.error(msg); throw new IllegalStateException(msg); } } private static final File ACTIVE_PAC = new File(LanternUtils.configDir(), "proxy.pac"); public static void configure() { if (configured) { LOG.error("Configure called twice?"); return; } configured = true; reconfigure(); } public static void reconfigure() { if (!LanternUtils.propsFile().isFile()) { System.out.println("PLEASE ENTER YOUR GOOGLE ACCOUNT DATA IN " + LanternUtils.propsFile() + " in the following form:" + "\ngoogle.user=your_name@gmail.com\ngoogle.pwd=your_password"); return; } final File git = new File(".git"); if (git.isDirectory() && !CensoredUtils.isForceCensored()) { LOG.info("Running from repository...not auto-configuring proxy."); return; } if (CensoredUtils.isCensored() || CensoredUtils.isForceCensored()) { LOG.info("Auto-configuring proxy..."); // We only want to configure the proxy if the user is in censored mode. if (SystemUtils.IS_OS_MAC_OSX) { configureOsxProxy(); } else if (SystemUtils.IS_OS_WINDOWS) { configureWindowsProxy(); // The firewall config is actually handled in a bat file from the // installer. //configureWindowsFirewall(); } } else { LOG.info("Not auto-configuring proxy in an uncensored country"); } } private static void configureOsxProxy() { configureOsxProxyPacFile(); configureOsxScript(); // Note that non-daemon hooks can exit prematurely with CTL-C, // but not if System.exit is used as it should be in deployed // versions. final Thread hook = new Thread(new Runnable() { @Override public void run() { LOG.info("Unproxying..."); unproxyOsx(); } }, "Unset-Web-Proxy-OSX"); Runtime.getRuntime().addShutdownHook(hook); } private static void configureOsxScript() { final String result = mpm.runScript(getScriptPath(), "on"); LOG.info("Result of script is: {}", result); } private static String getScriptPath() { final String name = "configureNetworkServices.bash"; final File script = new File(name); if (!script.isFile()) { final String msg = "No file: "+script.getAbsolutePath()+"\nfrom "+ new File(".").getAbsolutePath(); LOG.error(msg); throw new IllegalStateException(msg); } return script.getAbsolutePath(); } /** * Uses a pack file to manipulate browser's use of Lantern. */ private static void configureOsxProxyPacFile() { try { FileUtils.copyFile(PROXY_ON, ACTIVE_PAC); } catch (final IOException e) { LOG.error("Could not copy pac file?", e); } } private static void configureOsxProxyNetworkSetup() { final Collection<String> services = mpm.getNetworkServices(); for (final String service : services) { LOG.info("Setting web proxy for {}", service); final String val1 = mpm.runNetworkSetup("-setwebproxy", service.trim(), "127.0.0.1", String.valueOf(LanternConstants.LANTERN_LOCALHOST_HTTP_PORT)); LOG.info("Got return val:\n"+val1); // Also set it for HTTPS!! LOG.info("Setting secure web proxy for {}", service); final String val2 = mpm.runNetworkSetup("-setsecurewebproxy", service.trim(), "127.0.0.1", String.valueOf(LanternConstants.LANTERN_LOCALHOST_HTTP_PORT)); LOG.info("Got return val:\n"+val2); } } private static void configureWindowsProxy() { if (!SystemUtils.IS_OS_WINDOWS) { LOG.info("Not running on Windows"); return; } // We first want to read the start values so we can return the // registry to the original state when we shut down. final String proxyServerOriginal = WindowsRegistry.read(WINDOWS_REGISTRY_PROXY_KEY, ps); final String proxyEnableOriginal = WindowsRegistry.read(WINDOWS_REGISTRY_PROXY_KEY, pe); final String proxyServerUs = "127.0.0.1:"+ LanternConstants.LANTERN_LOCALHOST_HTTP_PORT; final String proxyEnableUs = "1"; LOG.info("Setting registry to use Lantern as a proxy..."); final int enableResult = WindowsRegistry.writeREG_SZ(WINDOWS_REGISTRY_PROXY_KEY, ps, proxyServerUs); final int serverResult = WindowsRegistry.writeREG_DWORD(WINDOWS_REGISTRY_PROXY_KEY, pe, proxyEnableUs); if (enableResult != 0) { LOG.error("Error enabling the proxy server? Result: "+enableResult); } if (serverResult != 0) { LOG.error("Error setting proxy server? Result: "+serverResult); } final Runnable runner = new Runnable() { @Override public void run() { unproxyWindows(proxyServerOriginal, proxyEnableOriginal); } }; // We don't make this a daemon thread because we want to make sure it // executes before shutdown. Runtime.getRuntime().addShutdownHook(new Thread (runner)); } public static void unproxy() { if (SystemUtils.IS_OS_WINDOWS) { // We first want to read the start values so we can return the // registry to the original state when we shut down. final String proxyServerOriginal = WindowsRegistry.read(WINDOWS_REGISTRY_PROXY_KEY, ps); if (proxyServerOriginal.equals(LANTERN_PROXY_ADDRESS)) { unproxyWindows(proxyServerOriginal, "0"); } } else if (SystemUtils.IS_OS_MAC_OSX) { unproxyOsx(); } else { LOG.warn("We don't yet support proxy configuration on other OSes"); } } protected static void unproxyWindows(final String proxyServerOriginal, final String proxyEnableOriginal) { LOG.info("Resetting Windows registry settings to original values."); final String proxyEnableUs = "1"; // On shutdown, we need to check if the user has modified the // registry since we originally set it. If they have, we want // to keep their setting. If not, we want to revert back to // before Lantern started. final String proxyServer = WindowsRegistry.read(WINDOWS_REGISTRY_PROXY_KEY, ps); final String proxyEnable = WindowsRegistry.read(WINDOWS_REGISTRY_PROXY_KEY, pe); if (proxyServer.equals(LANTERN_PROXY_ADDRESS)) { LOG.info("Setting proxy server back to: {}", proxyServerOriginal); WindowsRegistry.writeREG_SZ(WINDOWS_REGISTRY_PROXY_KEY, ps, proxyServerOriginal); LOG.info("Successfully reset proxy server"); } if (proxyEnable.equals(proxyEnableUs)) { LOG.info("Setting proxy enable back to: {}", proxyEnableOriginal); WindowsRegistry.writeREG_DWORD(WINDOWS_REGISTRY_PROXY_KEY, pe, proxyEnableOriginal); LOG.info("Successfully reset proxy enable"); } LOG.info("Done resetting the Windows registry"); } private static void unproxyOsx() { unproxyOsxPacFile(); unproxyOsxScript(); } private static void unproxyOsxScript() { final String result = mpm.runScript(getScriptPath(), "off"); LOG.info("Result of script is: {}", result); } private static void unproxyOsxPacFile() { try { LOG.info("Unproxying!!"); FileUtils.copyFile(PROXY_OFF, ACTIVE_PAC); LOG.info("Done unproxying!!"); } catch (final IOException e) { LOG.error("Could not copy pac file?", e); } } private static void unproxyOsxNetworkServices() { final Collection<String> services = mpm.getNetworkServices(); for (final String service : services) { LOG.info("Unsetting web proxy "+service); final String val1 = mpm.runNetworkSetup( "-setwebproxystate", service.trim(), "off"); LOG.info("Got return val:\n"+val1); LOG.info("Unsetting web proxy secure "+service); final String val2 = mpm.runNetworkSetup( "-setsecurewebproxystate", service.trim(), "off"); LOG.info("Got return val:\n"+val2); } } public static boolean configured() { return configured; } /* * This is done in the installer. private void configureWindowsFirewall() { final boolean oldNetSh; if (SystemUtils.IS_OS_WINDOWS_2000 || SystemUtils.IS_OS_WINDOWS_XP) { oldNetSh = true; } else { oldNetSh = false; } if (oldNetSh) { final String[] commands = { "netsh", "firewall", "add", "allowedprogram", "\""+SystemUtils.getUserDir()+"/Lantern.exe\"", "\"Lantern\"", "ENABLE" }; CommonUtils.nativeCall(commands); } else { final String[] commands = { "netsh", "advfirewall", "firewall", "add", "rule", "name=\"Lantern\"", "dir=in", "action=allow", "program=\""+SystemUtils.getUserDir()+"/Lantern.exe\"", "enable=yes", "profile=any" }; CommonUtils.nativeCall(commands); } } */ }
package org.usfirst.frc.team1492.robot; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.Joystick.AxisType; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.SampleRobot; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Timer; public class Robot extends SampleRobot { Talon motorLeft; Talon motorRight; Talon motorCenter; // Motor controller for the middle of the H Talon motorLift; Talon motorArm; DoubleSolenoid pistonArmTilt1; DoubleSolenoid pistonArmTilt2; DoubleSolenoid pistonLiftWidth; // PIDController PIDControllerLift; AnalogInput analogLift; DigitalInput digitalInLiftTop; DigitalInput digitalInLiftBottom; DigitalInput digitalInArmUp; DigitalInput digitalInArmDown; Joystick stickLeft; Joystick stickRight; Joystick stickAux; boolean[] stickAuxLastButton; double SETTING_hDriveDampening; double SETTING_motorLiftSpeed; double SETTING_armLiftSpeed; int liftPos = 0; int liftPosMax = 4; int liftPosMin = 0; double[] liftPosPresets = { 0, .25, .5, .75, 1 }; String autoModeNone = "None"; String autoModeMoveForward = "Move Forward"; String autoMode2 = "Two"; String autoMode3 = "Three"; String autoMode = autoModeNone; Command autoCommand; SendableChooser autoChooser; public Robot() { motorLeft = new Talon(1); motorRight = new Talon(2); motorCenter = new Talon(0); motorLift = new Talon(4); motorArm = new Talon(3); pistonArmTilt1 = new DoubleSolenoid(1, 0); pistonArmTilt2 = new DoubleSolenoid(2, 3); pistonLiftWidth = new DoubleSolenoid(4, 5); analogLift = new AnalogInput(0); digitalInLiftTop = new DigitalInput(0); digitalInLiftBottom = new DigitalInput(1); digitalInArmUp = new DigitalInput(2); digitalInArmDown = new DigitalInput(3); /* * PIDControllerLift = new PIDController(0, 0, 0, analogLift, * motorLift); PIDControllerLift.setInputRange(0, 1); * PIDControllerLift.setOutputRange(0, .5); PIDControllerLift.disable(); */ stickLeft = new Joystick(0); stickRight = new Joystick(1); stickAux = new Joystick(2); stickAuxLastButton = new boolean[stickAux.getButtonCount()]; autoChooser = new SendableChooser(); autoChooser.addDefault("No Auto", autoModeNone); autoChooser.addObject("Forward", autoModeMoveForward); autoChooser.addObject("Auto 2", autoMode2); autoChooser.addObject("Auto 3", autoMode3); SmartDashboard.putData("Auto Mode", autoChooser); } @Override public void autonomous() { autoMode = (String) autoChooser.getSelected(); SmartDashboard.putString("Start Auto", autoMode); SmartDashboard.putString("End Auto", ""); SmartDashboard.putString("End Auto", autoMode); SmartDashboard.putString("Start Auto", ""); autoMode = autoModeNone; } @Override public void operatorControl() { CameraThread camThread = new CameraThread(); camThread.start(); SmartDashboard.putBoolean("Camera thread working", true); // PIDControllerLift.enable(); while (isOperatorControl() && isEnabled()) { // SmartDashboard.putBoolean("CameraThread Running", // camThread.running); driveControl(); manipulatorControl(); Timer.delay(0.005); } // PIDControllerLift.disable(); camThread.finish(); } @Override public void test() { } public void driveControl() { SETTING_hDriveDampening = SmartDashboard .getNumber("hDriveDampening", 5); double leftSide = -stickLeft.getAxis(AxisType.kY); double rightSide = stickRight.getAxis(AxisType.kY); double h = farthestFrom0(stickLeft.getAxis(AxisType.kX), stickRight.getAxis(AxisType.kX)); h = deadbandScale(h, .2); // h /= 2; motorLeft.set(leftSide); motorRight.set(rightSide); motorCenter.set(h); } public void manipulatorControl() { // Calibration: SETTING_motorLiftSpeed = ((-stickAux.getAxis(AxisType.kZ)) / 2) + .5; SmartDashboard.putNumber("motorLiftSpeed (auxStick)", SETTING_motorLiftSpeed); SETTING_armLiftSpeed = ((-stickRight.getAxis(AxisType.kZ)) / 2) + .5; SmartDashboard.putNumber("armLiftSpeed (rightStick)", SETTING_armLiftSpeed); SmartDashboard.putNumber("AnalogLift PID (" + analogLift.getChannel() + ")", analogLift.pidGet()); // All the digital inputs: SmartDashboard.putBoolean( "digitalInLiftTop (" + digitalInLiftTop.getChannel() + ")", digitalInLiftTop.get()); SmartDashboard.putBoolean( "digitalInLiftBottom (" + digitalInLiftBottom.getChannel() + ")", digitalInLiftBottom.get()); SmartDashboard.putBoolean( "digitalInArmUp (" + digitalInArmUp.getChannel() + ")", digitalInArmUp.get()); SmartDashboard.putBoolean( "digitalInArmDown (" + digitalInArmDown.getChannel() + ")", digitalInArmDown.get()); // Lift Up/Down /* * DISABLED PID if(stickAux.getRawButton(3) && * !stickAuxLastButton[3]){//up liftPos ++; } * if(stickAux.getRawButton(2) && !stickAuxLastButton[2]){//down liftPos * --; } * * if (liftPos > liftPosMax) { liftPos = liftPosMax; } if (liftPos < * liftPosMin) { liftPos = liftPosMin; } * * PIDControllerLift.setSetpoint(liftPosPresets[liftPos]); * * if ((digitalInLiftTop.get() && liftPos == liftPosMax) || * (digitalInLiftBottom.get() && liftPos == liftPosMin)) { * motorLift.set(0); } */ // Instead of PID double liftSpeed = 0; if (stickAux.getRawButton(3) && digitalInLiftTop.get()) { liftSpeed = SETTING_motorLiftSpeed; } if (stickAux.getRawButton(2) && digitalInLiftBottom.get()) { liftSpeed = -SETTING_motorLiftSpeed; } motorLift.set(liftSpeed); // Arm Up/Down double armSpeed = stickAux.getAxis(AxisType.kY) * SETTING_armLiftSpeed; /* * if ((digitalInArmUp.get() && armSpeed > 0) || (digitalInArmDown.get() * && armSpeed < 0)) { armSpeed = 0; } */ motorArm.set(armSpeed); // Lift Width in/out if (stickAux.getRawButton(4)) { // left out pistonLiftWidth.set(Value.kForward); } if (stickAux.getRawButton(5)) { // right in pistonLiftWidth.set(Value.kReverse); } // arm tilt // pistonArmTilt1.set(Value.kOff); // pistonArmTilt2.set(Value.kOff); if (stickAux.getRawButton(6)) { // tilt forward pistonArmTilt1.set(Value.kForward); pistonArmTilt2.set(Value.kForward); } if (stickAux.getRawButton(7)) { // tilt backward pistonArmTilt1.set(Value.kReverse); pistonArmTilt2.set(Value.kReverse); } for (int i = 1; i < stickAuxLastButton.length; i++) { stickAuxLastButton[i] = stickAux.getRawButton(7); } } double deadbandScale(double input, double threshold) { return input > threshold ? (input - threshold) / (1 - threshold) : input < -threshold ? (input + threshold) / (1 - threshold) : 0; } double farthestFrom0(double a, double b) { return (Math.abs(a) > Math.abs(b)) ? a : b; } }
package org.lantern; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Console; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOError; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.net.UnknownHostException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Scanner; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPOutputStream; import javax.crypto.Cipher; import javax.net.ssl.SSLSocket; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.URIException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOExceptionWithCause; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang.math.NumberUtils; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.packet.Packet; import org.lantern.event.Events; import org.lantern.event.RefreshTokenEvent; import org.lantern.proxy.pt.Flashlight; import org.lantern.state.Mode; import org.lantern.state.Model; import org.lantern.state.ModelIo; import org.lantern.state.Settings; import org.lantern.state.StaticSettings; import org.lantern.util.PublicIpAddress; import org.lantern.win.Registry; import org.lastbamboo.common.offer.answer.NoAnswerException; import org.lastbamboo.common.p2p.P2PClient; import org.littleshoot.commom.xmpp.XmppUtils; import org.littleshoot.proxy.impl.ProxyUtils; import org.littleshoot.util.FiveTuple; import org.littleshoot.util.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import com.google.common.io.Files; /** * Utility methods for use with Lantern. */ public class LanternUtils { private static final Logger LOG = LoggerFactory.getLogger(LanternUtils.class); private static final String REQUESTED_MODE_TOO_SOON = "Requesting mode before model populated! Testing?"; private static final SecureRandom secureRandom = new SecureRandom(); private static boolean amFallbackProxy = false; private static String keystorePath = "<UNSET>"; private static Model model; private static final Properties privateProps = new Properties(); private static final File privatePropsFile; public static boolean isDevMode() { return LanternClientConstants.isDevMode(); } /* public static Socket openRawOutgoingPeerSocket( final URI uri, final P2PClient p2pClient, final Map<URI, AtomicInteger> peerFailureCount) throws IOException { return openOutgoingPeerSocket(uri, p2pClient, peerFailureCount, true); } */ static { LOG.debug("LOADING PRIVATE PROPS FILE!"); // The following are only used for diagnostics. if (LanternClientConstants.TEST_PROPS.isFile()) { privatePropsFile = LanternClientConstants.TEST_PROPS; } else if (LanternClientConstants.TEST_PROPS2.isFile()){ privatePropsFile = LanternClientConstants.TEST_PROPS2; } else { privatePropsFile = new File("test.properties"); } if (privatePropsFile.isFile()) { InputStream is = null; try { is = new FileInputStream(privatePropsFile); privateProps.load(is); LOG.debug("LOADED PRIVATE PROPS FILE!"); } catch (final IOException e) { LOG.debug("COULD NOT LOAD PRIVATE PROPS FILE AT "+ privatePropsFile); } finally { IOUtils.closeQuietly(is); } } else { LOG.debug("NO PRIVATE PROPS FILE AT: "+privatePropsFile); } } public static FiveTuple openOutgoingPeer( final URI uri, final P2PClient<FiveTuple> p2pClient, final Map<URI, AtomicInteger> peerFailureCount) throws IOException { if (p2pClient == null) { LOG.info("P2P client is null. Testing?"); throw new IOException("P2P client not connected"); } // Start the connection attempt. try { LOG.debug("Creating a new socket to {}", uri); return p2pClient.newSocket(uri); } catch (final NoAnswerException nae) { // This is tricky, as it can mean two things. First, it can mean // the XMPP message was somehow lost. Second, it can also mean // the other side is actually not there and didn't respond as a // result. LOG.info("Did not get answer!! Closing channel from browser", nae); final AtomicInteger count = peerFailureCount.get(uri); if (count == null) { LOG.debug("Incrementing failure count"); peerFailureCount.put(uri, new AtomicInteger(0)); } else if (count.incrementAndGet() > 5) { LOG.info("Got a bunch of failures in a row to this peer. " + "Removing it."); // We still reset it back to zero. Note this all should // ideally never happen, and we should be able to use the // XMPP presence alerts to determine if peers are still valid // or not. peerFailureCount.put(uri, new AtomicInteger(0)); //proxyStatusListener.onCouldNotConnectToPeer(uri); } throw new IOExceptionWithCause(nae); } catch (final IOException ioe) { //proxyStatusListener.onCouldNotConnectToPeer(uri); LOG.debug("Could not connect to peer", ioe); throw ioe; } } public static Socket openOutgoingPeerSocket(final URI uri, final P2PClient<Socket> p2pClient, final Map<URI, AtomicInteger> peerFailureCount) throws IOException { return openOutgoingPeerSocket(uri, p2pClient, peerFailureCount, false); } private static Socket openOutgoingPeerSocket( final URI uri, final P2PClient<Socket> p2pClient, final Map<URI, AtomicInteger> peerFailureCount, final boolean raw) throws IOException { if (p2pClient == null) { LOG.info("P2P client is null. Testing?"); throw new IOException("P2P client not connected"); } // Start the connection attempt. try { LOG.info("Creating a new socket to {}", uri); final Socket sock; if (raw) { sock = p2pClient.newRawSocket(uri); } else { sock = p2pClient.newSocket(uri); } // Note that it's OK that this prints SSL_NULL_WITH_NULL_NULL -- // the handshake doesn't actually happen until the first IO, so // the SSL ciphers and such should be all null at this point. LOG.debug("Got outgoing peer socket {}", sock); if (sock instanceof SSLSocket) { LOG.debug("Socket has ciphers {}", Arrays.asList(((SSLSocket)sock).getEnabledCipherSuites())); } else { LOG.warn("Not an SSL socket..."); } //startReading(sock, browserToProxyChannel, recordStats); return sock; } catch (final NoAnswerException nae) { // This is tricky, as it can mean two things. First, it can mean // the XMPP message was somehow lost. Second, it can also mean // the other side is actually not there and didn't respond as a // result. LOG.info("Did not get answer!! Closing channel from browser", nae); final AtomicInteger count = peerFailureCount.get(uri); if (count == null) { LOG.info("Incrementing failure count"); peerFailureCount.put(uri, new AtomicInteger(0)); } else if (count.incrementAndGet() > 5) { LOG.info("Got a bunch of failures in a row to this peer. " + "Removing it."); // We still reset it back to zero. Note this all should // ideally never happen, and we should be able to use the // XMPP presence alerts to determine if peers are still valid // or not. peerFailureCount.put(uri, new AtomicInteger(0)); //proxyStatusListener.onCouldNotConnectToPeer(uri); } throw new IOExceptionWithCause(nae); } catch (final IOException ioe) { //proxyStatusListener.onCouldNotConnectToPeer(uri); LOG.info("Could not connect to peer", ioe); throw ioe; } } public static byte[] utf8Bytes(final String str) { try { return str.getBytes("UTF-8"); } catch (final UnsupportedEncodingException e) { LOG.error("No UTF-8?", e); throw new RuntimeException("No UTF-8?", e); } } public static Collection<String> toHttpsCandidates(final String uriStr) { final Collection<String> segments = new LinkedHashSet<String>(); try { final org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(uriStr, false); final String host = uri.getHost(); //LOG.info("Using host: {}", host); segments.add(host); final String[] segmented = host.split("\\."); //LOG.info("Testing segments: {}", Arrays.asList(segmented)); for (int i = 0; i < segmented.length; i++) { final String tmp = segmented[i]; segmented[i] = "*"; final String segment = StringUtils.join(segmented, '.'); //LOG.info("Adding segment: {}", segment); segments.add(segment); segmented[i] = tmp; } for (int i = 1; i < segmented.length - 1; i++) { final String segment = "*." + StringUtils.join(segmented, '.', i, segmented.length);//segmented.slice(i,segmented.length).join("."); //LOG.info("Checking segment: {}", segment); segments.add(segment); } } catch (final URIException e) { LOG.error("Could not create URI?", e); } return segments; } public static void waitForInternet() { while (true) { if (hasNetworkConnection()) { return; } try { Thread.sleep(50); } catch (final InterruptedException e) { LOG.error("Interrupted?", e); } } } public static boolean hasNetworkConnection() { LOG.debug("Checking for network connection by looking up public IP"); final InetAddress ip = new PublicIpAddress().getPublicIpAddress(); LOG.debug("Returning result: "+ip); return ip != null; } public static int randomPort() { if (LanternConstants.ON_APP_ENGINE) { // Can't create server sockets on app engine. return -1; } for (int i = 0; i < 20; i++) { int randomInt = secureRandom.nextInt(); if (randomInt == Integer.MIN_VALUE) { // Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE -- caught // by FindBugs. randomInt = 0; } final int randomPort = 1024 + (Math.abs(randomInt) % 60000); ServerSocket sock = null; try { sock = new ServerSocket(); sock.bind(new InetSocketAddress("127.0.0.1", randomPort)); final int port = sock.getLocalPort(); return port; } catch (final IOException e) { LOG.info("Could not bind to port: {}", randomPort); } finally { if (sock != null) { try { sock.close(); } catch (IOException e) { } } } } // If we can't grab one of our securely chosen random ports, use // whatever port the OS assigns. ServerSocket sock = null; try { sock = new ServerSocket(); sock.bind(null); final int port = sock.getLocalPort(); return port; } catch (final IOException e) { LOG.info("Still could not bind?"); int randomInt = secureRandom.nextInt(); if (randomInt == Integer.MIN_VALUE) { // see above randomInt = 0; } return 1024 + (Math.abs(randomInt) % 60000); } finally { if (sock != null) { try { sock.close(); } catch (IOException e) { } } } } /** * Execute keytool, returning the output. * * @throws IOException If the executable cannot be found. */ public static String runKeytool(final String... args) { final Collection<String> withMx = new ArrayList<String>(); withMx.addAll(Arrays.asList(args)); withMx.add("-JXms64m"); try { final CommandLine command = new CommandLine(findKeytoolPath(), args); command.execute(); final String output = command.getStdOut(); if (!command.isSuccessful()) { LOG.info("Command failed!! Args: {}\nResult: {}", Arrays.asList(args), output); } return output; } catch (IOException e) { LOG.warn("Could not run key tool?", e); } return ""; } private static String findKeytoolPath() { if (SystemUtils.IS_OS_MAC_OSX) { // try to explicitly select the 1.6 keytool -- // The user may have 1.5 selected as the default // javavm (default in os x 10.5.8) // in this case, the default location below will // point to the 1.5 keytool instead. final File keytool16 = new File( "/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Commands/keytool"); if (keytool16.exists()) { return keytool16.getAbsolutePath(); } } final File jh = new File(System.getProperty("java.home"), "bin"); if (jh.isDirectory()) { final String name; if (SystemUtils.IS_OS_WINDOWS) { name = "keytool.exe"; } else { name = "keytool"; } try { return new File(jh, name).getCanonicalPath(); } catch (final IOException e) { LOG.warn("Error getting canonical path: " + jh); } } else { LOG.warn("java.home/bin not a directory? "+jh); } final File defaultLocation = new File("/usr/bin/keytool"); if (defaultLocation.exists()) { return defaultLocation.getAbsolutePath(); } final String networkSetupBin = CommandLine.findExecutable("keytool"); if (networkSetupBin != null) { return networkSetupBin; } LOG.error("Could not find keytool?!?!?!?"); return null; } public static boolean isLanternHub(final String jabberid) { try { final String userid = LanternXmppUtils.jidToEmail(jabberid); return LanternClientConstants.LANTERN_JID.equals(userid); } catch (EmailAddressUtils.NormalizationException e) { LOG.warn("Unnormalizable jabberid: " + jabberid); // Since the controller's id is normalizable, this must be // something else. return false; } } public static Packet activateOtr(final XMPPConnection conn) { return XmppUtils.goOffTheRecord(LanternClientConstants.LANTERN_JID, conn); } public static Packet deactivateOtr(final XMPPConnection conn) { return XmppUtils.goOnTheRecord(LanternClientConstants.LANTERN_JID, conn); } public static void browseUrl(final String uri) { if( !Desktop.isDesktopSupported() ) { LOG.error("Desktop not supported?"); LinuxBrowserLaunch.openURL(uri); return; } final Desktop desktop = Desktop.getDesktop(); if( !desktop.isSupported(Desktop.Action.BROWSE )) { LOG.error("Browse not supported?"); } try { desktop.browse(new URI(uri)); } catch (final IOException e) { LOG.warn("Error opening browser", e); } catch (final URISyntaxException e) { LOG.warn("Could not load URI", e); } } public static char[] readPasswordCLI() throws IOException { Console console = System.console(); if (console == null) { LOG.debug("No console -- using System.in..."); final Scanner sc = new Scanner(System.in, "UTF-8"); final char[] line = sc.nextLine().toCharArray(); sc.close(); return line; } try { return console.readPassword(); } catch (final IOError e) { throw new IOException("Could not read pass from console", e); } } public static String readLineCLI() throws IOException { Console console = System.console(); if (console == null) { return readLineCliNoConsole(); } try { return console.readLine(); } catch (final IOError e) { throw new IOException("Could not read line from console", e); } } public static String readLineCliNoConsole() { LOG.debug("No console -- using System.in..."); final Scanner sc = new Scanner(System.in, "UTF-8"); //sc.useDelimiter("\n"); //return sc.next(); final String line = sc.nextLine(); sc.close(); return line; } /** * Returns <code>true</code> if the specified string is either "true" or * "on" ignoring case. * * @param val The string in question. * @return <code>true</code> if the specified string is either "true" or * "on" ignoring case, otherwise <code>false</code>. */ public static boolean isTrue(final String val) { return checkTrueOrFalse(val, "true", "on"); } /** * Returns <code>true</code> if the specified string is either "false" or * "off" ignoring case. * * @param val The string in question. * @return <code>true</code> if the specified string is either "false" or * "off" ignoring case, otherwise <code>false</code>. */ public static boolean isFalse(final String val) { return checkTrueOrFalse(val, "false", "off"); } private static boolean checkTrueOrFalse(final String val, final String str1, final String str2) { final String str = val.trim(); return StringUtils.isNotBlank(str) && (str.equalsIgnoreCase(str1) || str.equalsIgnoreCase(str2)); } /** * Replaces the first instance of the specified regex in the given file * with the replacement string and writes out the new complete file. * * @param file The file to modify. * @param regex The regular expression to search for. * @param replacement The replacement string. */ public static void replaceInFile(final File file, final String regex, final String replacement) { LOG.debug("Replacing "+regex+" with "+replacement+" in "+file); try { final String cur = FileUtils.readFileToString(file, "UTF-8"); final String noStart = cur.replaceFirst(regex, replacement); FileUtils.writeStringToFile(file, noStart, "UTF-8"); } catch (final IOException e) { LOG.warn("Could not replace string in file", e); } } public static void loadJarLibrary(final Class<?> jarRepresentative, final String fileName) throws IOException { File tempDir = null; InputStream is = null; try { tempDir = Files.createTempDir(); final File tempLib = new File(tempDir, fileName); is = jarRepresentative.getResourceAsStream("/" + fileName); if (is == null) { final String msg = "No file in jar named: "+fileName; LOG.warn(msg); throw new IOException(msg); } FileUtils.copyInputStreamToFile(is, tempLib); System.load(tempLib.getAbsolutePath()); } finally { FileUtils.deleteQuietly(tempDir); IOUtils.closeQuietly(is); } } public static String fileInJarToString(final String fileName) throws IOException { InputStream is = null; try { is = LanternUtils.class.getResourceAsStream("/" + fileName); return IOUtils.toString(is); } finally { IOUtils.closeQuietly(is); } } /** * Creates a typed object from the specified string. If the string is a * boolean, this returns a boolean, if an int, an int, etc. * * @param val The string. * @return A typed object. */ public static Object toTyped(final String val) { if (LanternUtils.isTrue(val)) { return true; } else if (LanternUtils.isFalse(val)) { return false; } else if (NumberUtils.isNumber(val)) { return Integer.parseInt(val); } return val; } /** * Prints request headers. * * @param request The request. */ public static void printRequestHeaders(final HttpServletRequest request) { LOG.info(getRequestHeaders(request).toString()); } /** * Gets request headers as a string. * * @param request The request. * @return The request headers as a string. */ public static String getRequestHeaders(final HttpServletRequest request) { final Enumeration<String> headers = request.getHeaderNames(); final StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append(request.getRequestURL().toString()); sb.append("\n"); while (headers.hasMoreElements()) { final String headerName = headers.nextElement(); sb.append(headerName); sb.append(": "); sb.append(request.getHeader(headerName)); sb.append("\n"); } return sb.toString(); } public static void zeroFill(char[] array) { if (array != null) { Arrays.fill(array, '\0'); } } public static void zeroFill(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } public static boolean isUnlimitedKeyStrength() { try { return Cipher.getMaxAllowedKeyLength("AES") == Integer.MAX_VALUE; } catch (final NoSuchAlgorithmException e) { LOG.error("No AES?", e); return false; } } public static String toEmail(final XMPPConnection conn) { final String jid = conn.getUser().trim(); return XmppUtils.jidToUser(jid); } public static boolean isAnonymizedGoogleTalkAddress(final String email) { final boolean isEmail = !email.contains(".talk.google.com"); /* if (isEmail) { LOG.debug("Allowing email {}", email); } else { LOG.debug("Is a JID {}", email); } */ return isEmail; } public static Point getScreenCenter(final int width, final int height) { final Toolkit toolkit = Toolkit.getDefaultToolkit(); final Dimension screenSize = toolkit.getScreenSize(); final int x = (screenSize.width - width) / 2; final int y = (screenSize.height - height) / 2; return new Point(x, y); } public static boolean waitForServer(final int port) { return waitForServer(port, 60 * 1000); } public static boolean waitForServer(final int port, final int millis) { return waitForServer("127.0.0.1", port, millis); } public static boolean waitForServer(final String host, final int port, final int millis) { return waitForServer(new InetSocketAddress(host, port), millis); } public static boolean waitForServer(InetSocketAddress address, int millis) { final long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < millis) { final Socket sock = new Socket(); try { sock.connect(address, 2000); sock.close(); return true; } catch (final IOException e) { } try { Thread.sleep(20); } catch (final InterruptedException e) { LOG.info("Interrupted?"); } } LOG.error("Never able to connect with local server on port {}! " + "Maybe couldn't bind? "+ThreadUtils.dumpStack(), address.getPort()); return false; } /** * Determines whether or not oauth data should be persisted to disk. It is * only persisted if we can do so safely and securely but also cleanly. * * Fixme: this should actually be a user preference refs #586 * * @return <code>true</code> if credentials should be persisted to disk, * otherwise <code>false</code>. */ public static boolean persistCredentials() { return true; } /** * Accesses the object to set a property on with a trivial json-pointer * syntax as in /object1/object2. * * Public for testing. Note this is actually not use in favor of * ModelMutables that consolidates all accessible methods. */ public static Object getTargetForPath(final Object root, final String path) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (!path.contains("/")) { return root; } final String curProp = StringUtils.substringBefore(path, "/"); final Object propObject; if (curProp.isEmpty()) { propObject = root; } else { propObject = PropertyUtils.getProperty(root, curProp); } final String nextProp = StringUtils.substringAfter(path, "/"); if (nextProp.contains("/")) { return getTargetForPath(propObject, nextProp); } return propObject; } public static void setFromPath(final Object root, final String path, final Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (!path.contains("/")) { PropertyUtils.setProperty(root, path, value); return; } final String curProp = StringUtils.substringBefore(path, "/"); final Object propObject; if (curProp.isEmpty()) { propObject = root; } else { propObject = PropertyUtils.getProperty(root, curProp); } final String nextProp = StringUtils.substringAfter(path, "/"); if (nextProp.contains("/")) { setFromPath(propObject, nextProp, value); return; } PropertyUtils.setProperty(propObject, nextProp, value); } public static boolean isLocalHost(final Socket sock) { return isLocalHost((InetSocketAddress) sock.getRemoteSocketAddress()); } public static boolean isLocalHost(final InetSocketAddress address) { return address.getAddress().isLoopbackAddress(); } /** * Returns whether or not the string is either true of false. If it's some * other random string, this returns false. * * @param str The string to test. * @return <code>true</code> if the string is either true or false * (or on or off), otherwise false. */ public static boolean isTrueOrFalse(final String str) { if (LanternUtils.isTrue(str)) { return true; } else if (LanternUtils.isFalse(str)) { return true; } return false; } /** * The completion of the native calls is dependent on OS process * scheduling, so we need to wait until files actually exist. * * @param file The file to wait for. */ public static void waitForFile(final File file) { int i = 0; while (!file.isFile() && i < 100) { try { Thread.sleep(80); i++; } catch (final InterruptedException e) { LOG.error("Interrupted?", e); } } if (!file.isFile()) { LOG.error("Still could not create file at: {}", file); } else { LOG.info("Successfully created file at: {}", file); } } public static void fullDelete(final File file) { file.deleteOnExit(); if (file.isFile() && !file.delete()) { LOG.error("Could not delete file {}!!", file); } } public static InetSocketAddress isa(final String host, final int port) { final InetAddress ia; try { ia = InetAddress.getByName(host); } catch (final UnknownHostException e) { LOG.error("Could not lookup host address at "+host, e); throw new Error("Bad host", e); } return new InetSocketAddress(ia, port); } public static URI newURI(final String userId) { try { return new URI(userId); } catch (URISyntaxException e) { LOG.error("Could not create URI from "+userId); throw new Error("Bad URI: "+userId); } } /** * We call this dynamically instead of using a constant because the API * PORT is set at startup, and we don't want to create a race condition * for retrieving it. * * @return The base URL for photos. */ public static String photoUrlBase() { return StaticSettings.getLocalEndpoint()+"/photo/"; } public static String defaultPhotoUrl() { return LanternUtils.photoUrlBase() + "?email=default"; } public static boolean fileContains(final File file, final String str) { InputStream fis = null; try { fis = new FileInputStream(file); final String text = IOUtils.toString(fis); return text.contains(str); } catch (final IOException e) { LOG.warn("Could not read file?", e); } finally { IOUtils.closeQuietly(fis); } return false; } /** * Modifies .desktop files on Ubuntu with out hack to set our icon. * * @param path The path to the file. */ public static void addStartupWMClass(final String path) { final File desktopFile = new File(path); if (!desktopFile.isFile()) { LOG.warn("No lantern desktop file at: {}", desktopFile); return; } final Collection<?> lines = Arrays.asList("StartupWMClass=127.0.0.1__"+ // We use the substring here to get rid of the leading "/" StaticSettings.getPrefix().substring(1)+"_index.html"); try { FileUtils.writeLines(desktopFile, "UTF-8", lines, true); } catch (final IOException e) { LOG.warn("Error writing to: "+desktopFile, e); } } public static String photoUrl(final String email) { try { return LanternUtils.photoUrlBase() + "?email=" + URLEncoder.encode(email, "UTF-8"); } catch (final UnsupportedEncodingException e) { LOG.error("Unsupported encoding?", e); throw new RuntimeException(e); } } public static String runCommand(final String cmd, final String... args) throws IOException { LOG.debug("Command: {}\nargs: {}", cmd, Arrays.asList(args)); final CommandLine command; if (SystemUtils.IS_OS_WINDOWS) { String[] cmdline = new String[args.length + 3]; cmdline[0] = "cmd.exe"; cmdline[1] = "/C"; cmdline[2] = cmd; for (int i=0; i<args.length; ++i) { cmdline[3+i] = args[i]; } command = new CommandLine(cmdline); } else { command = new CommandLine(cmd, args); } command.execute(); final String output = command.getStdOut(); if (!command.isSuccessful()) { final String msg = "Command failed!! Args: " + Arrays.asList(args) + " Result: " + output; LOG.error(msg); throw new IOException(msg); } return output; } public static void addCSPHeader(HttpServletResponse resp) { String[] paths = {"ws://127.0.0.1", "http://127.0.0.1", "ws://localhost", "http://localhost" }; List<String> policies = new ArrayList<String>(); for (String path : paths) { policies.add(path + ":" + StaticSettings.getApiPort()); } policies.add("http://" + Flashlight.STATS_ADDR); String localhost = StringUtils.join(policies, " "); resp.addHeader("Content-Security-Policy", "default-src " + localhost + " 'unsafe-inline' 'unsafe-eval'; " + "img-src data: } /** * Returns whether or not this Lantern is running as a fallback proxy. * * @return <code>true</code> if it's a fallback proxy, otherwise * <code>false</code>. */ public static boolean isFallbackProxy() { return amFallbackProxy; } public static void setFallbackProxy(final boolean fallbackProxy) { // To check whether this is set in time for it to be picked up. LOG.info("I am a fallback proxy"); amFallbackProxy = fallbackProxy; } public static String getFallbackKeystorePath() { return keystorePath; } public static void setFallbackKeystorePath(final String path) { LOG.info("Setting keystorePath to '" + path + "'"); keystorePath = path; } public static boolean isTesting() { final String prop = System.getProperty("testing"); return "true".equalsIgnoreCase(prop); } public static byte[] compress(final String str) { if (StringUtils.isBlank(str)) { throw new IllegalArgumentException("can compress empty string!"); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzip = null; try { gzip = new GZIPOutputStream(baos); gzip.write(str.getBytes("UTF-8")); gzip.close(); return baos.toByteArray(); } catch (final IOException e) { LOG.error("Could not write to byte array?", e); throw new Error("Could not write to byte array?", e); } finally { IOUtils.closeQuietly(gzip); } } /** * Sets the model -- this should be called very early in the overall * initialization sequence. * * @param model The model for application-wide settings. */ public static void setModel(final Model model) { LanternUtils.model = model; // If we're testing on CI, use the pro-configured refresh token. if (SystemUtils.IS_OS_LINUX && privatePropsFile != null && privatePropsFile.isFile()) { final Settings set = model.getSettings(); final String existing = set.getRefreshToken(); if (StringUtils.isNotBlank(existing)) { final String rt = privateProps.getProperty("refresh_token"); set.setRefreshToken(rt); } } } public static Model getModel() { if (model == null) { LOG.error("No model yet? Testing?"); } return model; } public static boolean isGet() { if (model == null) { LOG.error(REQUESTED_MODE_TOO_SOON); return true; } return model.getSettings().getMode() == Mode.get; } public static boolean isGive() { if (model == null) { LOG.error(REQUESTED_MODE_TOO_SOON); return false; } return model.getSettings().getMode() == Mode.give; } public static Certificate certFromBase64(String base64Cert) throws CertificateException { return certFromBytes(Base64.decodeBase64(base64Cert)); } public static Certificate certFromBytes(byte[] bytes) throws CertificateException { final InputStream is = new ByteArrayInputStream(bytes); try { final CertificateFactory cf = CertificateFactory .getInstance("X.509"); return cf.generateCertificate(is); } finally { IOUtils.closeQuietly(is); } } /** * Cargo culted from org.eclipse.jdt.launching.SocketUtil. * * @return */ public static int findFreePort() { ServerSocket socket = null; try { socket = new ServerSocket(0); return socket.getLocalPort(); } catch (IOException e) { } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } return -1; } /** * Finds a free port, returning the specified port if it's available. * * @param suggestedPort The preferred port to use. * @return A free port, which may or may not be the preferred port. */ public static int findFreePort(final int suggestedPort) { ServerSocket socket = null; try { socket = new ServerSocket(suggestedPort); return socket.getLocalPort(); } catch (IOException e) { return findFreePort(); } finally { IOUtils.closeQuietly(socket); } } public static String[] hostAndPortFrom(HttpRequest httpRequest) { String hostAndPort = ProxyUtils.parseHostAndPort(httpRequest); if (StringUtils.isBlank(hostAndPort)) { List<String> hosts = httpRequest.headers().getAll( HttpHeaders.Names.HOST); if (hosts != null && !hosts.isEmpty()) { hostAndPort = hosts.get(0); } } String[] result = new String[2]; String[] parsed = hostAndPort.split(":"); result[0] = parsed[0]; result[1] = parsed.length == 2 ? parsed[1] : null; return result; } /** * Method for finding an OS-specific file with the given name that will * reside in a different location in installed versions that it will in * dev versions. * * @param fileName The name of the file. * @return The correct file instance, normalizing across installed and * uninstalled versions and operating systems. */ public static File osSpecificExecutable(final String fileName) { final File installed; if (SystemUtils.IS_OS_WINDOWS) { installed = new File(fileName+".exe"); } else { installed = new File(fileName); } if (installed.isFile()) { return installed; } if (SystemUtils.IS_OS_MAC_OSX) { return new File("./install/osx", fileName); } if (SystemUtils.IS_OS_WINDOWS) { return new File("./install/win", fileName); } if (SystemUtils.OS_ARCH.contains("64")) { return new File("./install/linux_x86_64", fileName); } return new File("./install/linux_x86_32", fileName); } /** * Checks if FireFox is the user's default browser on Windows. As of this * writing, this is only tested on Windows 8.1 but should theoretically * work on other Windows versions as well. * * @return <code>true</code> if Firefox is the user's default browser, * otherwise <code>false</code>. */ public static boolean firefoxIsDefaultBrowser() { if (!SystemUtils.IS_OS_WINDOWS) { return false; } final String key = "Software\\Microsoft\\Windows\\Shell\\Associations" + "\\UrlAssociations\\http\\UserChoice"; final String name = "ProgId"; final String result = Registry.read(key, name); if (StringUtils.isBlank(result)) { LOG.error("Could not find browser registry entry on: {}, {}", SystemUtils.OS_NAME, SystemUtils.OS_VERSION); return false; } return result.toLowerCase().contains("firefox"); } /** * Sets oauth tokens. WARNING: This is not thread safe. Callers should * ensure they will not call this method from different threads * simultaneously. * * @param set The settings * @param refreshToken The refresh token * @param accessToken The access token * @param expiresInSeconds The number of seconds the access token expires in * @param modelIo The class for storing the tokens. */ public static void setOauth(final Settings set, final String refreshToken, final String accessToken, final long expiresInSeconds, final ModelIo modelIo) { if (StringUtils.isBlank(accessToken)) { LOG.warn("Null access {} token -- not logging in!", accessToken); return; } set.setAccessToken(accessToken); // Set our expiry time 30 seconds before the actual expiry time to // make sure we never cut this too close (for example checking the // expiry time and then making a request that itself takes 30 seconds // to connect). set.setExpiryTime(System.currentTimeMillis() + ((expiresInSeconds-30) * 1000)); set.setUseGoogleOAuth2(true); // Only set the refresh token if it's not null. OAuth endpoints will // often return blank refresh tokens if they expect you to just keep // using the same one. if (StringUtils.isNotBlank(refreshToken)) { set.setRefreshToken(refreshToken); Events.asyncEventBus().post(new RefreshTokenEvent(refreshToken)); } // Could be null for testing. if (modelIo != null) { modelIo.write(); } } /** * Extracts a file from the current classloader/jar executable to a * specified directory. * * @param path The path of the file in the jar * @param dir The desired directory to extract to. * @return The path to the extracted file copied to the file system. * @throws IOException If there's an error finding or copying the file. */ public static File extractExecutableFromJar(final String path, final File dir) throws IOException { final File newFile = extractFileFromJar(path); File oldFile = new File(dir, newFile.getName()); if (oldFile.exists()) { HashCode newHash = Files.hash(newFile, Hashing.sha256()); HashCode oldHash = Files.hash(oldFile, Hashing.sha256()); if (newHash.equals(oldHash)) { LOG.info("File {} is unchanged, leaving alone", oldFile.getAbsolutePath()); newFile.delete(); return oldFile; } // We need to delete the old file before trying to move the new file // in place over it. See // See https://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo(java.io.File) LOG.info("File {} is out of date, deleting", oldFile.getAbsolutePath()); if (!oldFile.delete()) { LOG.warn("Could not delete old file at {}", oldFile); } } else { File targetDir = oldFile.getParentFile(); LOG.info("Making target directory {}", targetDir.getAbsolutePath()); if (!targetDir.exists() && !targetDir.mkdirs()) { String msg = "Could not make target directory " + targetDir.getAbsolutePath(); LOG.error(msg); throw new IOException(msg); } } if (!newFile.canExecute() && !newFile.setExecutable(true)) { final String msg = "Could not make file executable at "+path; LOG.error(msg); throw new IOException(msg); } try { FileUtils.moveFile(newFile, oldFile); } catch (Exception e) { String msg = String.format( "Unable to move file to destination %1$s: %2$s", oldFile.getAbsolutePath(), e.getMessage()); LOG.error(msg); throw new IOException(msg); } return oldFile; } /** * Extracts a file from the current classloader/jar file to a temporary * directory. * * @param path The path of the file in the jar * @return The path to the extracted file copied to the file system. * @throws IOException If there's an error finding or copying the file. */ public static File extractFileFromJar(final String path) throws IOException { final File dir = Files.createTempDir(); return extractFileFromJar(path, dir); } /** * Extracts a file from the current classloader/jar file to the specified * directory. * * @param path The path of the file in the jar. * @param dir The directory to extract to. * @return The path to the extracted file copied to the file system. * @throws IOException If there's an error finding or copying the file. */ public static File extractFileFromJar(final String path, final File dir) throws IOException { if (!dir.isDirectory() && !dir.mkdirs()) { throw new IOException("Could not make temp dir at: "+path); } final String name = StringUtils.substringAfterLast(path, "/"); if (StringUtils.isBlank(name)) { throw new IllegalArgumentException("Bad path: "+path); } final File temp = new File(dir, name); if (temp.isFile()) { if (!temp.delete()) { LOG.error("Could not delete existing file at path {}", temp); } } InputStream is = null; OutputStream os = null; try { is = ClassLoader.getSystemResourceAsStream(path); if (is == null) { throw new IOException("No input at "+path); } os = new FileOutputStream(temp); IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } return temp; } }
package api.user; /** * User's stats. * * @author Tim */ public class Stats { /** The downloaded. */ private Number downloaded; /** The joined date. */ private String joinedDate; /** The last access. */ private String lastAccess; /** The ratio from the api. Must be a string to handle the case where ratio is infinity */ private String ratio; /** * When getRatio is called for the first time we parse the ratio string into this number * and then return it for future calls */ private Number r = null; /** The required ratio. */ private Number requiredRatio; /** The uploaded. */ private Number uploaded; /** * Gets the downloaded. * * @return the downloaded */ public Number getDownloaded() { return this.downloaded; } /** * Gets the joined date. * * @return the joined date */ public String getJoinedDate() { return this.joinedDate; } /** * Gets the last access. * * @return the last access */ public String getLastAccess() { return this.lastAccess; } /** * Gets the ratio. * * @return the ratio */ public Number getRatio() { //If the ratio was the infinity character change it to Infinity //so that it can be parsed if (r == null){ if (ratio.equalsIgnoreCase("\u221e")){ ratio = "Infinity"; } r = Double.parseDouble(ratio); } return r; } /** * Gets the required ratio. * * @return the required ratio */ public Number getRequiredRatio() { return this.requiredRatio; } /** * Gets the uploaded. * * @return the uploaded */ public Number getUploaded() { return this.uploaded; } /** * Gets the buffer. * * @return the buffer */ public double getBuffer() { if (getUploaded() != null && getDownloaded() != null) return getUploaded().doubleValue() - getDownloaded().doubleValue(); else return 0; } @Override public String toString() { return "Stats [getDownloaded=" + getDownloaded() + ", getJoinedDate=" + getJoinedDate() + ", getLastAccess=" + getLastAccess() + ", getRatio=" + getRatio() + ", getRequiredRatio=" + getRequiredRatio() + ", getUploaded=" + getUploaded() + ", getBuffer=" + getBuffer() + "]"; } }
package awesome.console; import awesome.console.config.AwesomeConsoleConfig; import awesome.console.match.FileLinkMatch; import awesome.console.match.URLLinkMatch; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.HyperlinkInfo; import com.intellij.execution.filters.HyperlinkInfoFactory; import com.intellij.ide.browsers.OpenUrlHyperlinkInfo; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AwesomeLinkFilter implements Filter { private static final Pattern FILE_PATTERN = Pattern.compile( "(?<link>(?<path>(\\.|~)?(?:[a-zA-Z]:\\\\|/)?[a-zA-Z0-9_][a-zA-Z0-9/\\-_.\\\\]*\\.[a-zA-Z0-9\\-_.]+)" + "(?:(?::|, line |\\()(?<row>\\d+)(?:[:,](?<col>\\d+)\\)?)?)?)" ); private static final Pattern URL_PATTERN = Pattern.compile( "(?<link>(?<protocol>(([a-zA-Z]+):)?(/|\\\\|~))(?<path>[-_.!~*\\\\'()a-zA-Z0-9;/?:@&=+$,% ); private static final int maxSearchDepth = 1; private final AwesomeConsoleConfig config; private final Map<String, List<VirtualFile>> fileCache; private final Map<String, List<VirtualFile>> fileBaseCache; private final Project project; private final List<String> srcRoots; private final Matcher fileMatcher; private final Matcher urlMatcher; private ProjectRootManager projectRootManager; public AwesomeLinkFilter(final Project project) { this.project = project; this.fileCache = new HashMap<>(); this.fileBaseCache = new HashMap<>(); projectRootManager = ProjectRootManager.getInstance(project); srcRoots = getSourceRoots(); config = AwesomeConsoleConfig.getInstance(); fileMatcher = FILE_PATTERN.matcher(""); urlMatcher = URL_PATTERN.matcher(""); createFileCache(); } @Nullable @Override public Result applyFilter(final String line, final int endPoint) { final List<ResultItem> results = new ArrayList<>(); final int startPoint = endPoint - line.length(); final List<String> chunks = splitLine(line); int offset = 0; for (final String chunk : chunks) { if (config.SEARCH_URLS) { results.addAll(getResultItemsUrl(chunk, startPoint + offset)); } results.addAll(getResultItemsFile(chunk, startPoint + offset)); offset += chunk.length(); } return new Result(results); } public List<String> splitLine(final String line) { final List<String> chunks = new ArrayList<>(); final int length = line.length(); if (!config.LIMIT_LINE_LENGTH || config.LINE_MAX_LENGTH >= length) { chunks.add(line); return chunks; } if (!config.SPLIT_ON_LIMIT) { chunks.add(line.substring(0, config.LINE_MAX_LENGTH)); return chunks; } int offset = 0; do { final String chunk = line.substring(offset, Math.min(length, offset + config.LINE_MAX_LENGTH)); chunks.add(chunk); offset += config.LINE_MAX_LENGTH; } while (offset < length - 1); return chunks; } public List<ResultItem> getResultItemsUrl(final String line, final int startPoint) { final List<ResultItem> results = new ArrayList<>(); final List<URLLinkMatch> matches = detectURLs(line); for (final URLLinkMatch match : matches) { final String file = getFileFromUrl(match.match); if (null != file && !new File(file).exists()) { continue; } results.add( new Result( startPoint + match.start, startPoint + match.end, new OpenUrlHyperlinkInfo(match.match)) ); } return results; } public String getFileFromUrl(final String url) { if (url.startsWith("/")) { return url; } final String fileUrl = "file: if (url.startsWith(fileUrl)) { return url.substring(fileUrl.length()); } return null; } public List<ResultItem> getResultItemsFile(final String line, final int startPoint) { final List<ResultItem> results = new ArrayList<>(); final HyperlinkInfoFactory hyperlinkInfoFactory = HyperlinkInfoFactory.getInstance(); List<FileLinkMatch> matches = detectPaths(line); for(FileLinkMatch match: matches) { String path = PathUtil.getFileName(match.path); List<VirtualFile> matchingFiles = fileCache.get(path); if (null == matchingFiles) { matchingFiles = getResultItemsFileFromBasename(path); if (null == matchingFiles || 0 >= matchingFiles.size()) { continue; } } if (0 >= matchingFiles.size()) { continue; } List<VirtualFile> strictMatchingFiles = strictFilesByPaths(matchingFiles, match); if (strictMatchingFiles.size() > 0) { matchingFiles = strictMatchingFiles; } final HyperlinkInfo linkInfo = hyperlinkInfoFactory.createMultipleFilesHyperlinkInfo( matchingFiles, match.linkedRow < 0 ? 0 : match.linkedRow - 1, project ); results.add(new Result( startPoint + match.start, startPoint + match.end, linkInfo) ); } return results; } private List<VirtualFile> strictFilesByPaths(final List<VirtualFile> matchingFiles, final FileLinkMatch match) { List<VirtualFile> strictMatchingFiles = new ArrayList<>(); for (VirtualFile matchedFile : matchingFiles) { String generalisedFilePath = generalisePath(matchedFile.getPath()); String generalisedMatchPath = generalisePath(match.path); if (generalisedFilePath.endsWith(generalisedMatchPath)) { strictMatchingFiles.add(matchedFile); } } return strictMatchingFiles; } private String generalisePath(final String path) { return path.replace('/', '.') .replace('\\', '.') .replace('~', ',') .replace("..",""); } public List<VirtualFile> getResultItemsFileFromBasename(final String match) { return getResultItemsFileFromBasename(match, 0); } public List<VirtualFile> getResultItemsFileFromBasename(final String match, final int depth) { final ArrayList<VirtualFile> matches = new ArrayList<>(); final char packageSeparator = '.'; final int index = match.lastIndexOf(packageSeparator); if (-1 >= index) { return matches; } final String basename = match.substring(index + 1); final String origin = match.substring(0, index); final String path = origin.replace(packageSeparator, File.separatorChar); if (0 >= basename.length()) { return matches; } if (!fileBaseCache.containsKey(basename)) { /* Try to search deeper down the rabbit hole */ if (depth <= maxSearchDepth) { return getResultItemsFileFromBasename(origin, depth + 1); } return matches; } for (final VirtualFile file : fileBaseCache.get(basename)) { final VirtualFile parent = file.getParent(); if (null == parent) { continue; } if (!matchSource(parent.getPath(), path)) { continue; } matches.add(file); } return matches; } private void createFileCache() { projectRootManager.getFileIndex().iterateContent( new AwesomeProjectFilesIterator(fileCache, fileBaseCache)); } private List<String> getSourceRoots() { final VirtualFile[] contentSourceRoots = projectRootManager.getContentSourceRoots(); final List<String> roots = new ArrayList<>(); for (final VirtualFile root : contentSourceRoots) { roots.add(root.getPath()); } return roots; } private boolean matchSource(final String parent, final String path) { for (final String srcRoot : srcRoots) { if ((srcRoot + File.separatorChar + path).equals(parent)) { return true; } } return false; } @NotNull public List<FileLinkMatch> detectPaths(@NotNull final String line) { fileMatcher.reset(line); final List<FileLinkMatch> results = new LinkedList<>(); while (fileMatcher.find()) { final String match = fileMatcher.group("link"); final String row = fileMatcher.group("row"); final String col = fileMatcher.group("col"); results.add(new FileLinkMatch(match, fileMatcher.group("path"), fileMatcher.start(), fileMatcher.end(), null != row ? Integer.parseInt(row) : 0, null != col ? Integer.parseInt(col) : 0)); } return results; } @NotNull public List<URLLinkMatch> detectURLs(@NotNull final String line) { urlMatcher.reset(line); final List<URLLinkMatch> results = new LinkedList<>(); while (urlMatcher.find()) { final String match = urlMatcher.group("link"); results.add(new URLLinkMatch(match, urlMatcher.start(), urlMatcher.end())); } return results; } }
package pathfinding.chemin; import java.util.LinkedList; import obstacles.memory.ObstaclesIteratorPresent; import obstacles.types.ObstacleCircular; import obstacles.types.ObstacleProximity; import obstacles.types.ObstacleRobot; import pathfinding.astar.arcs.ClothoidesComputer; import graphic.PrintBufferInterface; import graphic.printable.Couleur; import graphic.printable.Segment; import robot.Cinematique; import robot.CinematiqueObs; import serie.BufferOutgoingOrder; import serie.Ticket; import utils.Log; import utils.Log.Verbose; import utils.Vec2RO; import config.Config; import config.ConfigInfo; import container.Service; import container.dependances.HighPFClass; import exceptions.PathfindingException; public class CheminPathfinding implements Service, HighPFClass, CheminPathfindingInterface { protected Log log; private BufferOutgoingOrder out; private ObstaclesIteratorPresent iterObstacles; private IteratorCheminPathfinding iterChemin; private IteratorCheminPathfinding iterCheminPrint; private PrintBufferInterface buffer; private LinkedList<Ticket> tickets = new LinkedList<Ticket>(); private volatile CinematiqueObs[] chemin = new CinematiqueObs[256]; private volatile ObstacleCircular[] aff = new ObstacleCircular[256]; private volatile Segment[] affSeg = new Segment[256]; protected volatile int indexFirst = 0; // indice du point en cours protected volatile int indexLast = 0; // indice du prochain point de la // trajectoire (donc indexLast - 1 // est l'index du dernier point // accessible) private volatile boolean uptodate = true; // le chemin est-il complet private volatile boolean empty = true; private volatile boolean needRestart = false; // faut-il recalculer d'un // autre point ? private int margeNecessaire, margeInitiale, margeAvantCollision, margePreferable; private boolean graphic; public CheminPathfinding(Log log, BufferOutgoingOrder out, ObstaclesIteratorPresent iterator, PrintBufferInterface buffer, Config config) { this.log = log; this.out = out; this.iterObstacles = iterator; iterChemin = new IteratorCheminPathfinding(this); iterCheminPrint = new IteratorCheminPathfinding(this); this.buffer = buffer; int demieLargeurNonDeploye = config.getInt(ConfigInfo.LARGEUR_NON_DEPLOYE) / 2; int demieLongueurArriere = config.getInt(ConfigInfo.DEMI_LONGUEUR_NON_DEPLOYE_ARRIERE); int demieLongueurAvant = config.getInt(ConfigInfo.DEMI_LONGUEUR_NON_DEPLOYE_AVANT); int marge = config.getInt(ConfigInfo.DILATATION_OBSTACLE_ROBOT); margeNecessaire = (int) (config.getDouble(ConfigInfo.PF_MARGE_NECESSAIRE) / ClothoidesComputer.PRECISION_TRACE_MM); margePreferable = (int) (config.getDouble(ConfigInfo.PF_MARGE_PREFERABLE) / ClothoidesComputer.PRECISION_TRACE_MM); margeAvantCollision = (int) (config.getInt(ConfigInfo.PF_MARGE_AVANT_COLLISION) / ClothoidesComputer.PRECISION_TRACE_MM); margeInitiale = (int) (config.getInt(ConfigInfo.PF_MARGE_INITIALE) / ClothoidesComputer.PRECISION_TRACE_MM); graphic = config.getBoolean(ConfigInfo.GRAPHIC_TRAJECTORY_FINAL); for(int i = 0; i < chemin.length; i++) chemin[i] = new CinematiqueObs(demieLargeurNonDeploye, demieLongueurArriere, demieLongueurAvant, marge); } public boolean getCurrentMarcheAvant() { return chemin[indexFirst].enMarcheAvant; } public boolean getNextMarcheAvant() { return chemin[add(indexFirst, 1)].enMarcheAvant; } @Override public boolean needStop() { return empty || minus(indexLast, indexFirst) < margeNecessaire; } @Override public boolean aAssezDeMarge() { boolean out = uptodate || minus(indexLast, indexFirst) >= margePreferable; if(!out) log.warning("Replanification partielle nécessaire : " + minus(indexLast, indexFirst) + " points d'avance seulement.", Verbose.REPLANIF.masque); return out; } public synchronized void checkColliding(boolean all) { if(!empty && isColliding(all)) { uptodate = false; notify(); } } private synchronized boolean isColliding(boolean all) { iterChemin.reinit(); boolean assezDeMargeDepuisDepart = false; int nbMarge = 0; int firstPossible = add(indexFirst, margeInitiale); // le premier point // qu'on pourrait // accepter if(all) iterObstacles.reinit(); iterObstacles.save(); while(iterChemin.hasNext()) { CinematiqueObs cinem = iterChemin.next(); int current = iterChemin.getIndex(); ObstacleRobot a = cinem.obstacle; iterObstacles.load(); while(iterObstacles.hasNext()) { ObstacleProximity o = iterObstacles.next(); if(o.isColliding(a)) { log.debug("Collision en " + current + ". Actuel : " + indexFirst + " (soit environ " + ClothoidesComputer.PRECISION_TRACE_MM * (minus(current, indexFirst) - 0.5) + " mm avant impact)", Verbose.REPLANIF.masque); // on n'a pas assez de marge ! if(!assezDeMargeDepuisDepart) { log.warning("Pas assez de marge !", Verbose.REPLANIF.masque); indexLast = indexFirst; empty = true; } else { log.warning("Replanification nécessaire", Verbose.REPLANIF.masque); // on a assez de marge, on va faire de la indexLast = minus(current, Math.min(nbMarge, margeAvantCollision)); out.makeNextObsolete(chemin[minus(indexLast, 1)], minus(indexLast, 1)); log.debug("On raccourcit la trajectoire. IndexLast = " + indexLast, Verbose.REPLANIF.masque); needRestart = true; } while(iterObstacles.hasNext()) iterObstacles.next(); return true; } } // on peut replanifier if(assezDeMargeDepuisDepart) nbMarge++; if(current == firstPossible) assezDeMargeDepuisDepart = true; } return false; } public synchronized boolean isArrived() { log.debug("Test isArrived : " + uptodate + " " + indexFirst + " " + indexLast, Verbose.REPLANIF.masque); return uptodate && indexFirst == indexLast; } /** * Le chemin est-il vide ? * * @return */ public boolean isEmpty() { return empty; } private void addToEnd(CinematiqueObs c) { c.copy(chemin[indexLast]); indexLast = add(indexLast, 1); empty = false; if(indexLast == indexFirst) log.critical("Buffer trop petit !"); } public void waitTrajectoryTickets() throws InterruptedException { while(!tickets.isEmpty()) { Ticket first = tickets.getFirst(); first.attendStatus(); tickets.removeFirst(); } } @Override public void addToEnd(LinkedList<CinematiqueObs> points) throws PathfindingException { log.debug("Ajout de " + points.size() + " points. Marge : " + minus(add(indexLast, points.size()), indexFirst) + ". First : " + indexFirst + ", last = " + indexLast); if(!uptodate && minus(add(indexLast, points.size()), indexFirst) < margePreferable) throw new PathfindingException("Pas assez de points pour le bas niveau"); if(!points.isEmpty()) { int tmp = minus(indexLast, 1); for(CinematiqueObs p : points) addToEnd(p); if(isIndexValid(tmp)) points.addFirst(chemin[tmp]); // on renvoie ce point afin qu'il else tmp = add(tmp, 1); // on ne le renvoie pas Ticket[] ts = out.envoieArcCourbe(points, tmp); for(Ticket t : ts) tickets.add(t); if(graphic) updateAffichage(); checkColliding(true); // collisionnent pas } /* * iterCheminPrint.reinit(); * log.debug("Affichage du chemin actuel : ", Verbose.REPLANIF.masque); * while(iterCheminPrint.hasNext()) * log.debug(iterCheminPrint.getIndex()+" : "+iterCheminPrint.next(), * Verbose.REPLANIF.masque); */ } private boolean isIndexValid(int index) { return !empty && minus(index, indexFirst) < minus(indexLast, indexFirst); } protected CinematiqueObs get(int index) { if(isIndexValid(index) && !empty) return chemin[index]; return null; } public void clear() { uptodate = true; indexLast = indexFirst; empty = true; if(graphic) updateAffichage(); } @Override public synchronized void setUptodate() { uptodate = true; } public boolean isUptodate() { return uptodate; } public int getCurrentIndex() { return indexFirst; } public synchronized Cinematique setCurrentIndex(int indexTrajectory) { indexFirst = indexTrajectory; if(empty) indexLast = indexFirst; if(graphic) { if(affSeg[indexFirst] != null) { Segment s = affSeg[indexFirst].clone(); s.setColor(Couleur.JAUNE); buffer.add(s); } updateAffichage(); } if(isIndexValid(indexFirst)) return chemin[indexFirst]; return null; } @Override public Cinematique getLastValidCinematique() { if(!uptodate && needRestart && !empty) { needRestart = false; // la demande est partie return chemin[minus(indexLast, 1)]; } return null; } private void updateAffichage() { synchronized(buffer) { iterCheminPrint.reinit(); Vec2RO last = null; for(int i = 0; i < 256; i++) { if(aff[i] != null) { buffer.removeSupprimable(aff[i]); aff[i] = null; } if(affSeg[i] != null) { buffer.removeSupprimable(affSeg[i]); affSeg[i] = null; } } while(iterCheminPrint.hasNext()) { Cinematique a = iterCheminPrint.next(); if(last != null) { affSeg[iterCheminPrint.getIndex()] = new Segment(last, a.getPosition(), Couleur.TRAJECTOIRE); buffer.addSupprimable(affSeg[iterCheminPrint.getIndex()]); } aff[iterCheminPrint.getIndex()] = new ObstacleCircular(a.getPosition(), 8, Couleur.TRAJECTOIRE); last = a.getPosition(); buffer.addSupprimable(aff[iterCheminPrint.getIndex()]); } buffer.notify(); } } /** * Return indice1 - indice2 * * @param indice1 * @param indice2 * @return */ public final int minus(int indice1, int indice2) { return (indice1 - indice2 + 256) & 0xFF; } /** * Return indice1 + indice2 * * @param indice1 * @param indice2 * @return */ public final int add(int indice1, int indice2) { return (indice1 + indice2) & 0xFF; } public double getLastOrientation() { return chemin[minus(indexLast, 1)].orientationReelle; } public Cinematique getLastCinematique() { return chemin[minus(indexLast, 1)]; } }
package peergos.shared.corenode; import peergos.shared.*; import peergos.shared.cbor.*; import peergos.shared.crypto.hash.*; import peergos.shared.crypto.random.*; import peergos.shared.user.*; import peergos.shared.user.fs.*; import java.io.*; import java.util.*; import java.util.concurrent.*; public class TofuCoreNode implements CoreNode { public static final String KEY_STORE_NAME = ".keystore"; private final CoreNode source; private final TofuKeyStore tofu; private UserContext context; public TofuCoreNode(CoreNode source, TofuKeyStore tofu) { this.source = source; this.tofu = tofu; } public void setContext(UserContext context) { this.context = context; } private static String getStorePath(String username) { return "/" + username + "/" + KEY_STORE_NAME; } public static CompletableFuture<TofuKeyStore> load(String username, TrieNode root, NetworkAccess network, SafeRandom random) { if (username == null) return CompletableFuture.completedFuture(new TofuKeyStore()); return root.getByPath(getStorePath(username), network).thenCompose(fileOpt -> { if (! fileOpt.isPresent()) return CompletableFuture.completedFuture(new TofuKeyStore()); return fileOpt.get().getInputStream(network, random, x -> {}).thenCompose(reader -> { byte[] storeData = new byte[(int) fileOpt.get().getSize()]; return reader.readIntoArray(storeData, 0, storeData.length) .thenApply(x -> TofuKeyStore.fromCbor(CborObject.fromByteArray(storeData))); }); }); } private CompletableFuture<Boolean> commit() { return context.getUserRoot() .thenCompose(home -> { byte[] data = tofu.serialize(); AsyncReader.ArrayBacked dataReader = new AsyncReader.ArrayBacked(data); return home.uploadFileSection(KEY_STORE_NAME, dataReader, true, 0, (long) data.length, Optional.empty(), true, context.network, context.crypto.random, x -> {}, context.fragmenter(), home.generateChildLocationsFromSize(data.length, context.crypto.random)); }).thenApply(x -> true); } public CompletableFuture<Boolean> updateUser(String username) { return source.getChain(username) .thenCompose(chain -> tofu.updateChain(username, chain, context.network.dhtClient) .thenCompose(x -> commit())); } @Override public CompletableFuture<Optional<PublicKeyHash>> getPublicKeyHash(String username) { Optional<PublicKeyHash> local = tofu.getPublicKey(username); if (local.isPresent()) return CompletableFuture.completedFuture(local); return source.getChain(username) .thenCompose(chain -> tofu.updateChain(username, chain, context.network.dhtClient) .thenCompose(x -> commit())) .thenApply(x -> tofu.getPublicKey(username)); } @Override public CompletableFuture<String> getUsername(PublicKeyHash key) { Optional<String> local = tofu.getUsername(key); if (local.isPresent()) return CompletableFuture.completedFuture(local.get()); return source.getUsername(key) .thenCompose(username -> source.getChain(username) .thenCompose(chain -> tofu.updateChain(username, chain, context.network.dhtClient) .thenCompose(x -> commit()) .thenApply(x -> username))); } @Override public CompletableFuture<List<UserPublicKeyLink>> getChain(String username) { List<UserPublicKeyLink> localChain = tofu.getChain(username); if (! localChain.isEmpty()) return CompletableFuture.completedFuture(localChain); return source.getChain(username) .thenCompose(chain -> tofu.updateChain(username, chain, context.network.dhtClient) .thenCompose(x -> commit()) .thenApply(x -> tofu.getChain(username))); } @Override public CompletableFuture<Boolean> updateChain(String username, List<UserPublicKeyLink> chain) { return tofu.updateChain(username, chain, context.network.dhtClient) .thenCompose(x -> commit()) .thenCompose(x -> source.updateChain(username, chain)); } @Override public CompletableFuture<List<String>> getUsernames(String prefix) { return source.getUsernames(prefix); } @Override public void close() throws IOException {} }
// S y m b o l G l y p h B o a r d // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // package omr.glyph.ui; import omr.glyph.Glyph; import omr.glyph.Shape; import omr.selection.Selection; import omr.selection.SelectionHint; import omr.ui.field.LField; import omr.ui.field.LIntegerField; import static omr.ui.field.SpinnerUtilities.*; import omr.util.Logger; import omr.util.Predicate; import javax.swing.*; /** * Class <code>SymbolGlyphBoard</code> defines an extended glyph board, with an * additional symbol glyph spinner : <ul> * * <li>A <b>symbolSpinner</b> to browse through all glyphs that are considered * as symbols, that is built from aggregation of contiguous sections, or by * combination of other symbols. Glyphs whose shape is set to {@link * omr.glyph.Shape#NOISE}, that is too small glyphs, are not included in this * spinner. The symbolSpinner is thus a subset of the knownSpinner (which is * itself a subset of the globalSpinner). </ul> * * <dl> * <dt><b>Selection Inputs:</b></dt><ul> * <li>VERTICAL_GLYPH * </ul> * </dl> * * @author Herv&eacute; Bitteur * @version $Id$ */ public class SymbolGlyphBoard extends GlyphBoard { private static final Logger logger = Logger.getLogger( SymbolGlyphBoard.class); // Spinner just for symbol glyphs private JSpinner symbolSpinner; // Glyph characteristics private LField ledger = new LField( false, "Ledger", "Does this glyph intersect a legder"); private LIntegerField pitchPosition = new LIntegerField( false, "Pitch", "Logical pitch position"); private LIntegerField stems = new LIntegerField( false, "Stems", "Number of stems connected to this glyph"); // Glyph id for the very first symbol private int firstSymbolId; // Predicate for symbol glyphs private Predicate<Glyph> symbolPredicate = new Predicate<Glyph>() { public boolean check (Glyph glyph) { return (glyph != null) && (glyph.getId() >= firstSymbolId) && (glyph.getShape() != Shape.NOISE); } }; // SymbolGlyphBoard // /** * Create the symbol glyph board * * * @param builder the companion builder which handles the other UI entities * @param firstSymbolId id of the first glyph made as a symbol (as opposed * to sticks/glyphs elaborated during previous steps) * @param glyphSelection glyph selection as input * @param glyphIdSelection glyph_id selection as output */ public SymbolGlyphBoard (SymbolsBuilder builder, int firstSymbolId, Selection glyphSelection, Selection glyphIdSelection, Selection glyphSetSelection) { // For all glyphs super( "SymbolGlyphBoard", builder, glyphSelection, glyphIdSelection, glyphSetSelection); // Cache info this.firstSymbolId = firstSymbolId; // Symbols spinner symbolSpinner = makeGlyphSpinner(builder.getLag(), symbolPredicate); symbolSpinner.setName("symbolSpinner"); symbolSpinner.setToolTipText("Specific spinner for symbol glyphs"); defineSpecificLayout(); } // SymbolGlyphBoard // /** * Create a simplified symbol glyph board */ public SymbolGlyphBoard () { super("SymbolSimpleBoard", null); defineSpecificLayout(); } // update // /** * Call-back triggered when Glyph Selection has been modified * * @param selection the (Glyph) Selection * @param hint potential notification hint */ @Override public void update (Selection selection, SelectionHint hint) { // logger.info("SymbolGlyphBoard " + selection.getTag() // + " selfUpdating=" + selfUpdating); super.update(selection, hint); switch (selection.getTag()) { case VERTICAL_GLYPH : selfUpdating = true; Glyph glyph = (Glyph) selection.getEntity(); // Set symbolSpinner accordingly symbolSpinner.setValue( symbolPredicate.check(glyph) ? glyph.getId() : NO_VALUE); // Fill symbol characteristics if (glyph != null) { pitchPosition.setValue( (int) Math.rint(glyph.getPitchPosition())); ledger.setText(Boolean.toString(glyph.hasLedger())); stems.setValue(glyph.getStemNumber()); } else { ledger.setText(""); pitchPosition.setText(""); stems.setText(""); } selfUpdating = false; break; default : } } // defineSpecificLayout // /** * Define a specific layout for this Symbol GlyphBoard */ protected void defineSpecificLayout () { int r = 1; r += 2; if (glyphModel != null) { builder.addLabel("Id", cst.xy(1, r)); builder.add(globalSpinner, cst.xy(3, r)); builder.addLabel("Known", cst.xy(5, r)); builder.add(knownSpinner, cst.xy(7, r)); builder.addLabel("Symb", cst.xy(9, r)); builder.add(symbolSpinner, cst.xy(11, r)); } r += 2; // For glyph characteristics r += 2; builder.add(pitchPosition.getLabel(), cst.xy(1, r)); builder.add(pitchPosition.getField(), cst.xy(3, r)); builder.add(ledger.getLabel(), cst.xy(5, r)); builder.add(ledger.getField(), cst.xy(7, r)); builder.add(stems.getLabel(), cst.xy(9, r)); builder.add(stems.getField(), cst.xy(11, r)); } }
package org.jboss.tm; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; /** * A TransactionLocal is similar to ThreadLocal except it is keyed on the * Transactions. A transaction local variable is cleared after the transaction * completes. * * @author <a href="mailto:dain@daingroup.com">Dain Sundstrom</a> * @author <a href="mailto:bill@jboss.org">Bill Burke</a> * @author adrian@jboss.org * @version $Revision: 37459 $ */ public class TransactionLocal { /** * To simplify null values handling in the preloaded data pool we use * this value instead of 'null' */ private static final Object NULL_VALUE = new Object(); /** * The transaction manager is maintained by the system and * manges the assocation of transaction to threads. */ protected final TransactionManager transactionManager; /** * The delegate */ protected TransactionLocalDelegate delegate; public TransactionLocal() { transactionManager = TransactionManagerLocator.locateTransactionManager(); initDelegate(); } /** * Creates a transaction local variable. Using the given transaction manager * * @param tm the transaction manager */ public TransactionLocal(TransactionManager tm) { if (tm == null) throw new IllegalArgumentException("Null transaction manager"); this.transactionManager = tm; initDelegate(); } public void lock() throws InterruptedException { lock(getTransaction()); } public void lock(Transaction transaction) throws InterruptedException { // ignore when there is no transaction if (transaction == null) return; delegate.lock(this, transaction); } /** * Unlock the TransactionLocal using the current transaction */ public void unlock() { unlock(getTransaction()); } /** * Unlock the ThreadLocal using the provided transaction * * @param transaction the transaction */ public void unlock(Transaction transaction) { // ignore when there is no transaction if (transaction == null) return; delegate.unlock(this, transaction); } /** * Returns the initial value for this thransaction local. This method * will be called once per accessing transaction for each TransactionLocal, * the first time each transaction accesses the variable with get or set. * If the programmer desires TransactionLocal variables to be initialized to * some value other than null, TransactionLocal must be subclassed, and this * method overridden. Typically, an anonymous inner class will be used. * Typical implementations of initialValue will call an appropriate * constructor and return the newly constructed object. * * @return the initial value for this TransactionLocal */ protected Object initialValue() { return null; } /** * get the transaction local value. * * @param tx the transaction * @return the obejct */ protected Object getValue(Transaction tx) { return delegate.getValue(this, tx); } /** * put the value in the TransactionImpl map * * @param tx the transaction * @param value the value */ protected void storeValue(Transaction tx, Object value) { delegate.storeValue(this, tx, value); } /** * does Transaction contain object? * * @param tx the transaction * @return true if it has an object */ protected boolean containsValue(Transaction tx) { return delegate.containsValue(this, tx); } /** * Returns the value of this TransactionLocal variable associated with the * thread context transaction. Creates and initializes the copy if this is * the first time the method is called in a transaction. * * @return the value of this TransactionLocal */ public Object get() { return get(getTransaction()); } public Object get(Transaction transaction) { if (transaction == null) return initialValue(); Object value = getValue(transaction); // is we didn't get a value initalize this object with initialValue() if(value == null) { // get the initial value value = initialValue(); // if value is null replace it with the null value standin if(value == null) { value = NULL_VALUE; } // store the value try { storeValue(transaction, value); } catch(IllegalStateException e) { // depending on the delegate implementation it may be considered an error to // call storeValue after the tx has ended. Further, the tx ending may have // caused the disposal of a previously stored initial value. // for user convenience we ignore such errors and return the initialvalue here. return initialValue(); } } // if the value is the null standin return null if(value == NULL_VALUE) { return null; } // finall return the value return value; } /** * Sets the value of this TransactionLocal variable associtated with the * thread context transaction. This is only used to change the value from * the one assigned by the initialValue method, and many applications will * have no need for this functionality. * * @param value the value to be associated with the thread context * transactions's TransactionLocal */ public void set(Object value) { set(getTransaction(), value); } /** * Sets the value of this TransactionLocal variable associtated with the * specified transaction. This is only used to change the value from * the one assigned by the initialValue method, and many applications will * have no need for this functionality. * * @param transaction the transaction for which the value will be set * @param value the value to be associated with the thread context * transactions's TransactionLocal */ public void set(Transaction transaction, Object value) { if (transaction == null) throw new IllegalStateException("there is no transaction"); // If this transaction is unknown, register for synchroniztion callback, // and call initialValue to give subclasses a chance to do some // initialization. if(!containsValue(transaction)) { initialValue(); } // if value is null replace it with the null value standin if(value == null) { value = NULL_VALUE; } // finally store the value storeValue(transaction, value); } public Transaction getTransaction() { try { return transactionManager.getTransaction(); } catch(SystemException e) { throw new IllegalStateException("An error occured while getting the " + "transaction associated with the current thread: " + e); } } /** * Initialise the delegate */ protected void initDelegate() { if (transactionManager instanceof TransactionLocalDelegate) delegate = (TransactionLocalDelegate) transactionManager; else delegate = new TransactionLocalDelegateImpl(transactionManager); } }
package joshua.decoder.hypergraph; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import java.util.logging.Logger; import joshua.decoder.ff.state_maintenance.DPState; import joshua.decoder.ff.state_maintenance.StateComputer; /** * this class implement (1) HyperGraph-related data structures (Item and Hyper-edges) * * Note: to seed the kbest extraction, each deduction should have the best_cost properly set. We do * not require any list being sorted * * @author Zhifei Li, <zhifei.work@gmail.com> * @version $LastChangedDate$ */ public class HyperGraph { // pointer to goal HGNode public HGNode goalNode = null; public int numNodes = -1; public int numEdges = -1; public int sentID = -1; public int sentLen = -1; static final Logger logger = Logger.getLogger(HyperGraph.class.getName()); public HyperGraph(HGNode goalNode, int numNodes, int numEdges, int sentID, int sentLen) { this.goalNode = goalNode; this.numNodes = numNodes; this.numEdges = numEdges; this.sentID = sentID; this.sentLen = sentLen; } public double bestLogP() { return this.goalNode.bestHyperedge.bestDerivationLogP; } public static HyperGraph mergeTwoHyperGraphs(HyperGraph hg1, HyperGraph hg2) { List<HyperGraph> hgs = new ArrayList<HyperGraph>(); hgs.add(hg1); hgs.add(hg2); return mergeHyperGraphs(hgs); } public static HyperGraph mergeHyperGraphs(List<HyperGraph> hgs) { // Use the first hg to get i, j, lhs, sentID, sentLen. HyperGraph hg1 = hgs.get(0); int sentID = hg1.sentID; int sentLen = hg1.sentLen; // Create new goal node. int goalI = hg1.goalNode.i; int goalJ = hg1.goalNode.j; int goalLHS = hg1.goalNode.lhs; TreeMap<StateComputer, DPState> goalDPStates = null; double goalEstTotalLogP = -1; HGNode newGoalNode = new HGNode(goalI, goalJ, goalLHS, goalDPStates, null, goalEstTotalLogP);; // Attach all edges under old goal nodes into the new goal node. int numNodes = 0; int numEdges = 0; for (HyperGraph hg : hgs) { // Sanity check if the hgs belongs to the same source input. if (hg.sentID != sentID || hg.sentLen != sentLen || hg.goalNode.i != goalI || hg.goalNode.j != goalJ || hg.goalNode.lhs != goalLHS) { logger.severe("hg belongs to different source sentences, must be wrong"); System.exit(1); } newGoalNode.addHyperedgesInNode(hg.goalNode.hyperedges); numNodes += hg.numNodes; numEdges += hg.numEdges; } numNodes = numNodes - hgs.size() + 1; return new HyperGraph(newGoalNode, numNodes, numEdges, sentID, sentLen); } // // }
package kg.apc.jmeter.vizualizers; // TODO: rows in settings should have color markers for better experience import kg.apc.jmeter.graphs.AbstractOverTimeVisualizer; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import kg.apc.jmeter.JMeterPluginsUtils; import kg.apc.charting.AbstractGraphRow; import kg.apc.jmeter.gui.ButtonPanelAddCopyRemove; import kg.apc.jmeter.perfmon.AgentConnector; import kg.apc.jmeter.perfmon.PerfMonCollector; import kg.apc.jmeter.perfmon.PerfMonSampleResult; import org.apache.jmeter.gui.util.PowerTableModel; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.property.CollectionProperty; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.testelement.property.NullProperty; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * * @author APC */ public class PerfMonGui extends AbstractOverTimeVisualizer { private static final Logger log = LoggingManager.getLoggerForClass(); private PowerTableModel tableModel; private JTable grid; private JComboBox metricTypesBox; private JTextArea errorTextArea; private JScrollPane errorPane; public static final String[] columnIdentifiers = new String[]{ "Host / IP", "Port", "Metric to collect", "(reserved field)"// "Metric parameter (see help)" }; public static final Class[] columnClasses = new Class[]{ String.class, String.class, String.class, String.class }; private static String[] defaultValues = new String[]{ "localhost", "4444", "CPU", "" }; public PerfMonGui() { super(); setGranulation(1000); graphPanel.getGraphObject().setYAxisLabel("Performance Metrics"); graphPanel.getGraphObject().setExpendRows(true); } @Override protected JSettingsPanel createSettingsPanel() { return new JSettingsPanel(this, JSettingsPanel.GRADIENT_OPTION | JSettingsPanel.LIMIT_POINT_OPTION | JSettingsPanel.MAXY_OPTION | JSettingsPanel.RELATIVE_TIME_OPTION); } @Override public String getWikiPage() { return "PerfMon"; } @Override public String getLabelResource() { return getClass().getSimpleName(); } @Override public String getStaticLabel() { return JMeterPluginsUtils.prefixLabel("PerfMon Metrics Collector"); } @Override protected JPanel getGraphPanelContainer() { JPanel panel = new JPanel(new BorderLayout()); JPanel innerTopPanel = new JPanel(new BorderLayout()); errorPane = new JScrollPane(); errorPane.setMinimumSize(new Dimension(100, 50)); errorPane.setPreferredSize(new Dimension(100, 50)); errorTextArea = new JTextArea(); errorTextArea.setForeground(Color.red); errorTextArea.setBackground(new Color(255, 255, 153)); errorTextArea.setEditable(false); errorPane.setViewportView(errorTextArea); registerPopup(); innerTopPanel.add(createConnectionsPanel(), BorderLayout.CENTER); innerTopPanel.add(errorPane, BorderLayout.SOUTH); panel.add(innerTopPanel, BorderLayout.NORTH); errorPane.setVisible(false); return panel; } private void addErrorMessage(String msg) { errorPane.setVisible(true); SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); String newLine = ""; if(errorTextArea.getText().length() != 0) newLine = "\n"; errorTextArea.setText(errorTextArea.getText() + newLine + formatter.format(new Date()) + " - ERROR: " + msg); errorTextArea.setCaretPosition(errorTextArea.getDocument().getLength()); updateGui(); } public void clearErrorMessage() { errorTextArea.setText(""); errorPane.setVisible(false); } private void registerPopup() { JPopupMenu popup = new JPopupMenu(); JMenuItem hideMessagesMenu = new JMenuItem("Hide Error Panel"); hideMessagesMenu.addActionListener(new HideAction()); popup.add(hideMessagesMenu); errorTextArea.setComponentPopupMenu(popup); } @Override public void clearData() { clearErrorMessage(); super.clearData(); } private Component createConnectionsPanel() { JPanel panel = new JPanel(new BorderLayout(5, 5)); panel.setBorder(BorderFactory.createTitledBorder("Servers to Monitor (ServerAgent must be started, see help)")); panel.setPreferredSize(new Dimension(150, 150)); JScrollPane scroll = new JScrollPane(createGrid()); scroll.setPreferredSize(scroll.getMinimumSize()); panel.add(scroll, BorderLayout.CENTER); panel.add(new ButtonPanelAddCopyRemove(grid, tableModel, defaultValues), BorderLayout.SOUTH); metricTypesBox=new JComboBox(AgentConnector.metrics.toArray()); grid.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(metricTypesBox)); return panel; } private JTable createGrid() { grid = new JTable(); createTableModel(); grid.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); grid.setMinimumSize(new Dimension(200, 100)); return grid; } private void createTableModel() { tableModel = new PowerTableModel(columnIdentifiers, columnClasses); grid.setModel(tableModel); } @Override public TestElement createTestElement() { TestElement te = new PerfMonCollector(); modifyTestElement(te); te.setComment(JMeterPluginsUtils.getWikiLinkText(getWikiPage())); return te; } @Override public void modifyTestElement(TestElement te) { super.modifyTestElement(te); if (grid.isEditing()) { grid.getCellEditor().stopCellEditing(); } if (te instanceof PerfMonCollector) { PerfMonCollector pmte = (PerfMonCollector) te; CollectionProperty rows = JMeterPluginsUtils.tableModelRowsToCollectionProperty(tableModel, PerfMonCollector.DATA_PROPERTY); pmte.setData(rows); } super.configureTestElement(te); } @Override public void configure(TestElement te) { super.configure(te); PerfMonCollector pmte = (PerfMonCollector) te; JMeterProperty perfmonValues = pmte.getData(); if (!(perfmonValues instanceof NullProperty)) { JMeterPluginsUtils.collectionPropertyToTableModelRows((CollectionProperty) perfmonValues, tableModel); } else { log.warn("Received null property instead of collection"); } } @Override public void add(SampleResult res) { if(res.isSuccessful()) { super.add(res); addThreadGroupRecord(res.getSampleLabel(), normalizeTime(res.getEndTime()), ((PerfMonSampleResult)res).getValue()); updateGui(null); } else { addErrorMessage(res.getResponseMessage()); } } private void addThreadGroupRecord(String threadGroupName, long time, double value) { AbstractGraphRow row = model.get(threadGroupName); if (row == null) { row = getNewRow(model, AbstractGraphRow.ROW_AVERAGES, threadGroupName, AbstractGraphRow.MARKER_SIZE_NONE, false, false, false, true, true); } row.add(time, value); } private class HideAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { errorPane.setVisible(false); updateGui(); } } }
// JSBuiltInFunctions.java package ed.js.engine; import java.io.*; import java.util.*; import com.twmacinta.util.*; import ed.js.*; import ed.js.func.*; import ed.io.*; import ed.net.*; public class JSBuiltInFunctions { public static class print extends JSFunctionCalls1 { print(){ this( true ); } print( boolean newLine ){ super(); _newLine = newLine; } public Object call( Scope scope , Object foo , Object extra[] ){ if ( _newLine ) System.out.println( foo ); else System.out.print( foo ); return null; } final boolean _newLine; } public static class NewObject extends JSFunctionCalls0 { NewObject(){ super(); } public Object call( Scope scope , Object extra[] ){ return new JSObjectBase(); } } public static class NewArray extends JSFunctionCalls1 { NewArray(){ super(); } public JSObject newOne(){ return new JSArray(); } public Object call( Scope scope , Object a , Object[] extra ){ int len = 0; if ( extra == null || extra.length == 0 ){ if ( a instanceof Number ) len = ((Number)a).intValue(); } else { len = 1 + extra.length; } JSArray arr = new JSArray( len ); if ( extra != null && extra.length > 0 ){ arr.setInt( 0 , a ); for ( int i=0; i<extra.length; i++) arr.setInt( 1 + i , extra[i] ); } return arr; } } public static class NewDate extends JSFunctionCalls1 { public Object call( Scope scope , Object t , Object extra[] ){ if ( t == null ) return new JSDate(); if ( ! ( t instanceof Number ) ) return new JSDate(); return new JSDate( ((Number)t).longValue() ); } } public static class CrID extends JSFunctionCalls1 { public Object call( Scope scope , Object idString , Object extra[] ){ if ( idString == null ) return ed.db.ObjectId.get(); return new ed.db.ObjectId( idString.toString() ); } } public static class isXXX extends JSFunctionCalls1 { isXXX( Class c ){ _c = c; } public Object call( Scope scope , Object o , Object extra[] ){ return _c.isInstance( o ); } final Class _c; } public static class isXXXs extends JSFunctionCalls1 { isXXXs( Class ... c ){ _c = c; } public Object call( Scope scope , Object o , Object extra[] ){ for ( int i=0; i<_c.length; i++ ) if ( _c[i].isInstance( o ) ) return true; return false; } final Class _c[]; } public static class sysexec extends JSFunctionCalls1 { static String[] fix( String s ){ String base[] = s.split( "\\s+" ); List<String> fixed = new ArrayList(); boolean changed = false; for ( int i=0; i<base.length; i++ ){ if ( ! base[i].startsWith( "\"" ) ){ fixed.add( base[i] ); continue; } int end = i; while( end < base.length && ! base[end].endsWith( "\"" ) ) end++; String foo = base[i++].substring( 1 ); for ( ; i<=end && i < base.length; i++ ) foo += " " + base[i]; i if ( foo.endsWith( "\"" ) ) foo = foo.substring( 0 , foo.length() - 1 ); fixed.add( foo ); changed = true; } if ( changed ){ System.out.println( fixed ); base = new String[fixed.size()]; for ( int i=0; i<fixed.size(); i++ ) base[i] = fixed.get(i); } return base; } public Object call( Scope scope , Object o , Object extra[] ){ if ( o == null ) return null; // TODO: security File root = scope.getRoot(); if ( root == null ) throw new JSException( "no root" ); String cmd[] = fix( o.toString() ); String env[] = new String[]{}; String toSend = null; if ( extra != null && extra.length > 0 ) toSend = extra[0].toString(); if ( extra != null && extra.length > 1 && extra[1] instanceof JSObject ){ JSObject foo = (JSObject)extra[1]; env = new String[ foo.keySet().size() ]; int pos = 0; for ( String name : foo.keySet() ){ Object val = foo.get( name ); if ( val == null ) val = ""; env[pos++] = name + "=" + val.toString(); } } try { Process p = Runtime.getRuntime().exec( cmd , env , root ); if ( toSend != null ){ OutputStream out = p.getOutputStream(); out.write( toSend.getBytes() ); out.close(); } JSObject res = new JSObjectBase(); res.set( "out" , StreamUtil.readFully( p.getInputStream() ) ); res.set( "err" , StreamUtil.readFully( p.getErrorStream() ) ); return res; } catch ( Throwable t ){ throw new JSException( t.toString() , t ); } } } static Scope _myScope = new Scope( "Built-Ins" , null ); static { _myScope.put( "sysexec" , new sysexec() , true ); _myScope.put( "print" , new print() , true ); _myScope.put( "printnoln" , new print( false ) , true ); _myScope.put( "SYSOUT" , new print() , true ); _myScope.put( "Object" , new NewObject() , true ); _myScope.put( "Array" , new NewArray() , true ); _myScope.put( "Date" , JSDate._cons , true ); _myScope.put( "String" , JSString._cons , true ); _myScope.put( "RegExp" , JSRegex._cons , true ); _myScope.put( "Math" , JSMath.getInstance() , true ); _myScope.put( "CrID" , new CrID() , true ); _myScope.put( "Base64" , new ed.util.Base64() , true ); _myScope.put( "download" , HttpDownload.DOWNLOAD , true ); _myScope.put( "JSCaptcha" , new JSCaptcha() , true ); _myScope.put( "parseBool" , new JSFunctionCalls1(){ public Object call( Scope scope , Object b , Object extra[] ){ if ( b == null ) return false; String s = b.toString(); if ( s.length() == 0 ) return false; char c = s.charAt( 0 ); return c == 't' || c == 'T'; } } , true ); _myScope.put( "md5" , new JSFunctionCalls1(){ public Object call( Scope scope , Object b , Object extra[] ){ synchronized ( _myMd5 ){ _myMd5.Init(); _myMd5.Update( b.toString() ); return new JSString( _myMd5.asHex() ); } } private final MD5 _myMd5 = new MD5(); } , true ); _myScope.put( "isArray" , new isXXX( JSArray.class ) , true ); _myScope.put( "isNumber" , new isXXX( Number.class ) , true ); _myScope.put( "isObject" , new isXXX( JSObject.class ) , true ); _myScope.put( "isDate" , new isXXX( JSDate.class ) , true ); _myScope.put( "isString" , new isXXXs( String.class , JSString.class ) , true ); JSON.init( _myScope ); } }
package at.ac.tuwien.kr.alpha; import at.ac.tuwien.kr.alpha.antlr.ASPCore2Lexer; import at.ac.tuwien.kr.alpha.antlr.ASPCore2Parser; import at.ac.tuwien.kr.alpha.common.AnswerSet; import at.ac.tuwien.kr.alpha.grounder.Grounder; import at.ac.tuwien.kr.alpha.grounder.GrounderFactory; import at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram; import at.ac.tuwien.kr.alpha.grounder.parser.ParsedTreeVisitor; import at.ac.tuwien.kr.alpha.grounder.transformation.IdentityProgramTransformation; import at.ac.tuwien.kr.alpha.solver.Solver; import at.ac.tuwien.kr.alpha.solver.SolverFactory; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.RecognitionException; import org.apache.commons.cli.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * Main entry point for Alpha. */ public class Main { private static final Log LOG = LogFactory.getLog(Main.class); private static final String OPT_INPUT = "input"; private static final String OPT_HELP = "help"; private static final String OPT_NUM_AS = "numAS"; private static final String OPT_GROUNDER = "grounder"; private static final String OPT_SOLVER = "solver"; private static final String DEFAULT_GROUNDER = "dummy"; private static final String DEFAULT_SOLVER = "leutgeb"; private static CommandLine commandLine; public static void main(String[] args) { final Options options = new Options(); Option numAnswerSetsOption = new Option("n", OPT_NUM_AS, true, "the number of Answer Sets to compute"); numAnswerSetsOption.setArgName("number"); numAnswerSetsOption.setRequired(true); numAnswerSetsOption.setArgs(1); numAnswerSetsOption.setType(Number.class); options.addOption(numAnswerSetsOption); Option inputOption = new Option("i", OPT_INPUT, true, "read the ASP program from this file"); inputOption.setArgName("file"); inputOption.setRequired(true); inputOption.setArgs(1); inputOption.setType(FileInputStream.class); options.addOption(inputOption); Option helpOption = new Option("h", OPT_HELP, false, "show this help"); options.addOption(helpOption); Option grounderOption = new Option("g", OPT_GROUNDER, false, "name of the grounder implementation to use"); options.addOption(grounderOption); Option solverOption = new Option("s", OPT_SOLVER, false, "name of the solver implementation to use"); options.addOption(solverOption); try { commandLine = new DefaultParser().parse(options, args); } catch (ParseException e) { System.err.println(e.getMessage()); System.exit(1); return; } if (commandLine.hasOption(OPT_HELP)) { HelpFormatter formatter = new HelpFormatter(); // TODO(flowlo): This is quite optimistic. How do we know that the program // really was invoked as "java -jar ..."? formatter.printHelp("java -jar alpha.jar", options); System.exit(0); return; } int limit = -1; try { limit = ((Number)commandLine.getParsedOptionValue(OPT_NUM_AS)).intValue(); } catch (ParseException e) { bailOut("Failed to parse number of answer sets requested."); } if (limit < 1) { bailOut("Number of Answer Sets Requested must be a positive integer."); } ParsedProgram program = null; try { program = parseVisit(new FileInputStream(commandLine.getOptionValue(OPT_INPUT))); } catch (RecognitionException e) { bailOut("Error while parsing input ASP program, see errors above."); } catch (FileNotFoundException e) { bailOut(e.getMessage()); } catch (IOException e) { bailOut(e); } // Apply program transformations/rewritings (currently none). IdentityProgramTransformation programTransformation = new IdentityProgramTransformation(); ParsedProgram transformedProgram = programTransformation.transform(program); Grounder grounder = GrounderFactory.getInstance( commandLine.getOptionValue(OPT_GROUNDER, DEFAULT_GROUNDER), transformedProgram ); // TODO(flowlo): Add meaningful filter here, probably by interpreting some flag. Solver solver = SolverFactory.getInstance( commandLine.getOptionValue(OPT_SOLVER, DEFAULT_SOLVER), grounder, p -> true ); int answerSetCount = 0; while (true) { AnswerSet as = solver.get(); if (as == null || answerSetCount == limit) { break; } answerSetCount++; System.out.println(as); } /*Stream.generate(solver) .limit(limit) .forEach(System.out::println);*/ } private static void bailOut(Object o) { LOG.fatal(o); System.exit(1); } static ParsedProgram parseVisit(InputStream is) throws IOException { final ASPCore2Parser parser = new ASPCore2Parser( new CommonTokenStream( new ASPCore2Lexer( new ANTLRInputStream(is) ) ) ); final SwallowingErrorListener errorListener = new SwallowingErrorListener(); parser.addErrorListener(errorListener); // Parse program ASPCore2Parser.ProgramContext programContext = parser.program(); // If the our SwallowingErrorListener has handled some exception during parsing // just re-throw that exception. // At this time, error messages will be already printed out to standard error // because ANTLR by default adds an org.antlr.v4.runtime.ConsoleErrorListener // to every parser. // That ConsoleErrorListener will print useful messages, but not report back to // our code. // org.antlr.v4.runtime.BailErrorStrategy cannot be used here, because it would // abruptly stop parsing as soon as the first error is reached (i.e. no recovery // is attempted) and the user will only see the first error encountered. if (errorListener.getRecognitionException() != null) { throw errorListener.getRecognitionException(); } // Construct internal program representation. ParsedTreeVisitor visitor = new ParsedTreeVisitor(); return (ParsedProgram) visitor.visitProgram(programContext); } }
package biweekly.io.xml; import static biweekly.io.xml.XCalNamespaceContext.XCAL_NS; import static biweekly.io.xml.XCalQNames.COMPONENTS; import static biweekly.io.xml.XCalQNames.ICALENDAR; import static biweekly.io.xml.XCalQNames.PARAMETERS; import static biweekly.io.xml.XCalQNames.PROPERTIES; import static biweekly.io.xml.XCalQNames.VCALENDAR; import java.io.BufferedInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import javax.xml.namespace.QName; import javax.xml.transform.ErrorListener; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import biweekly.ICalVersion; import biweekly.ICalendar; import biweekly.Warning; import biweekly.component.ICalComponent; import biweekly.io.CannotParseException; import biweekly.io.ParseContext; import biweekly.io.SkipMeException; import biweekly.io.StreamReader; import biweekly.io.TimezoneInfo; import biweekly.io.scribe.component.ICalComponentScribe; import biweekly.io.scribe.property.ICalPropertyScribe; import biweekly.parameter.ICalParameters; import biweekly.property.ICalProperty; import biweekly.property.Version; import biweekly.property.Xml; import biweekly.util.XmlUtils; public class XCalReader extends StreamReader { private final Source source; private final Closeable stream; private volatile ICalendar readICal; private volatile TransformerException thrown; private final ReadThread thread = new ReadThread(); private final Object lock = new Object(); private final BlockingQueue<Object> readerBlock = new ArrayBlockingQueue<Object>(1); private final BlockingQueue<Object> threadBlock = new ArrayBlockingQueue<Object>(1); /** * @param str the string to read from */ public XCalReader(String str) { this(new StringReader(str)); } /** * @param in the input stream to read from */ public XCalReader(InputStream in) { source = new StreamSource(in); stream = in; } /** * @param file the file to read from * @throws FileNotFoundException if the file doesn't exist */ public XCalReader(File file) throws FileNotFoundException { this(new BufferedInputStream(new FileInputStream(file))); } /** * @param reader the reader to read from */ public XCalReader(Reader reader) { source = new StreamSource(reader); stream = reader; } /** * @param node the DOM node to read from */ public XCalReader(Node node) { source = new DOMSource(node); stream = null; } @Override protected ICalendar _readNext() throws IOException { readICal = null; warnings.clear(); context = new ParseContext(); tzinfo = new TimezoneInfo(); thrown = null; if (!thread.started) { thread.start(); } else { if (thread.finished || thread.closed) { return null; } try { threadBlock.put(lock); } catch (InterruptedException e) { return null; } } //wait until thread reads xCard try { readerBlock.take(); } catch (InterruptedException e) { return null; } if (thrown != null) { throw new IOException(thrown); } return readICal; } private class ReadThread extends Thread { private final SAXResult result; private final Transformer transformer; private volatile boolean finished = false, started = false, closed = false; public ReadThread() { setName(getClass().getSimpleName()); //create the transformer try { transformer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e) { //shouldn't be thrown because it's a simple configuration throw new RuntimeException(e); } //prevent error messages from being printed to stderr transformer.setErrorListener(new NoOpErrorListener()); result = new SAXResult(new ContentHandlerImpl()); } @Override public void run() { started = true; try { transformer.transform(source, result); } catch (TransformerException e) { if (!thread.closed) { thrown = e; } } finally { finished = true; try { readerBlock.put(lock); } catch (InterruptedException e) { //ignore } } } } private class ContentHandlerImpl extends DefaultHandler { private final Document DOC = XmlUtils.createDocument(); private final XCalStructure structure = new XCalStructure(); private final StringBuilder characterBuffer = new StringBuilder(); private final LinkedList<ICalComponent> componentStack = new LinkedList<ICalComponent>(); private Element propertyElement, parent; private QName paramName; private ICalComponent curComponent; private ICalParameters parameters; @Override public void characters(char[] buffer, int start, int length) throws SAXException { characterBuffer.append(buffer, start, length); } @Override public void startElement(String namespace, String localName, String qName, Attributes attributes) throws SAXException { QName qname = new QName(namespace, localName); String textContent = emptyCharacterBuffer(); if (structure.isEmpty()) { //<icalendar> if (ICALENDAR.equals(qname)) { structure.push(ElementType.icalendar); } return; } ElementType parentType = structure.peek(); ElementType typeToPush = null; if (parentType != null) { switch (parentType) { case icalendar: //<vcalendar> if (VCALENDAR.equals(qname)) { ICalComponentScribe<? extends ICalComponent> scribe = index.getComponentScribe(localName, ICalVersion.V2_0); ICalComponent component = scribe.emptyInstance(); curComponent = component; readICal = (ICalendar) component; typeToPush = ElementType.component; } break; case component: if (PROPERTIES.equals(qname)) { //<properties> typeToPush = ElementType.properties; } else if (COMPONENTS.equals(qname)) { //<components> componentStack.add(curComponent); curComponent = null; typeToPush = ElementType.components; } break; case components: //start component element if (XCAL_NS.equals(namespace)) { ICalComponentScribe<? extends ICalComponent> scribe = index.getComponentScribe(localName, ICalVersion.V2_0); curComponent = scribe.emptyInstance(); ICalComponent parent = componentStack.getLast(); parent.addComponent(curComponent); typeToPush = ElementType.component; } break; case properties: //start property element propertyElement = createElement(namespace, localName, attributes); parameters = new ICalParameters(); parent = propertyElement; typeToPush = ElementType.property; break; case property: //<parameters> if (PARAMETERS.equals(qname)) { typeToPush = ElementType.parameters; } break; case parameters: //inside of <parameters> if (XCAL_NS.equals(namespace)) { paramName = qname; typeToPush = ElementType.parameter; } break; case parameter: //inside of a parameter element if (XCAL_NS.equals(namespace)) { typeToPush = ElementType.parameterValue; } break; case parameterValue: //should never have child elements break; } } //append element to property element if (propertyElement != null && typeToPush != ElementType.property && typeToPush != ElementType.parameters && !structure.isUnderParameters()) { if (textContent.length() > 0) { parent.appendChild(DOC.createTextNode(textContent)); } Element element = createElement(namespace, localName, attributes); parent.appendChild(element); parent = element; } structure.push(typeToPush); } @Override public void endElement(String namespace, String localName, String qName) throws SAXException { String textContent = emptyCharacterBuffer(); if (structure.isEmpty()) { //no <icalendar> elements were read yet return; } ElementType type = structure.pop(); if (type == null && (propertyElement == null || structure.isUnderParameters())) { //it's a non-xCal element return; } if (type != null) { switch (type) { case parameterValue: parameters.put(paramName.getLocalPart(), textContent); break; case parameter: //do nothing break; case parameters: //do nothing break; case property: context.getWarnings().clear(); propertyElement.appendChild(DOC.createTextNode(textContent)); //unmarshal property and add to parent component QName propertyQName = new QName(propertyElement.getNamespaceURI(), propertyElement.getLocalName()); String propertyName = localName; ICalPropertyScribe<? extends ICalProperty> scribe = index.getPropertyScribe(propertyQName); try { ICalProperty property = scribe.parseXml(propertyElement, parameters, context); if (property instanceof Version && curComponent instanceof ICalendar) { Version versionProp = (Version) property; ICalVersion version = versionProp.toICalVersion(); if (version != null) { ICalendar ical = (ICalendar) curComponent; ical.setVersion(version); context.setVersion(version); propertyElement = null; break; } } curComponent.addProperty(property); for (Warning warning : context.getWarnings()) { warnings.add(null, propertyName, warning); } } catch (SkipMeException e) { warnings.add(null, propertyName, 22, e.getMessage()); } catch (CannotParseException e) { warnings.add(null, propertyName, 16, e.getMessage()); scribe = index.getPropertyScribe(Xml.class); ICalProperty property = scribe.parseXml(propertyElement, parameters, context); curComponent.addProperty(property); } propertyElement = null; break; case component: curComponent = null; //</vcalendar> if (VCALENDAR.getNamespaceURI().equals(namespace) && VCALENDAR.getLocalPart().equals(localName)) { //wait for readNext() to be called again try { readerBlock.put(lock); threadBlock.take(); } catch (InterruptedException e) { throw new SAXException(e); } return; } break; case properties: break; case components: curComponent = componentStack.removeLast(); break; case icalendar: break; } } //append element to property element if (propertyElement != null && type != ElementType.property && type != ElementType.parameters && !structure.isUnderParameters()) { if (textContent.length() > 0) { parent.appendChild(DOC.createTextNode(textContent)); } parent = (Element) parent.getParentNode(); } } private String emptyCharacterBuffer() { String textContent = characterBuffer.toString(); characterBuffer.setLength(0); return textContent; } private Element createElement(String namespace, String localName, Attributes attributes) { Element element = DOC.createElementNS(namespace, localName); applyAttributesTo(element, attributes); return element; } private void applyAttributesTo(Element element, Attributes attributes) { for (int i = 0; i < attributes.getLength(); i++) { String qname = attributes.getQName(i); if (qname.startsWith("xmlns:")) { continue; } String name = attributes.getLocalName(i); String value = attributes.getValue(i); element.setAttribute(name, value); } } } private enum ElementType { //a value is missing for "vcalendar" because it is treated as a "component" //enum values are lower-case so they won't get confused with the "XCalQNames" variable names icalendar, components, properties, component, property, parameters, parameter, parameterValue; } /** * <p> * Keeps track of the structure of an xCal XML document. * </p> * * <p> * Note that this class is here because you can't just do QName comparisons * on a one-by-one basis. The location of an XML element within the XML * document is important too. It's possible for two elements to have the * same QName, but be treated differently depending on their location (e.g. * the {@code <duration>} property has a {@code <duration>} data type) * </p> */ private static class XCalStructure { private final List<ElementType> stack = new ArrayList<ElementType>(); /** * Pops the top element type off the stack. * @return the element type or null if the stack is empty */ public ElementType pop() { return isEmpty() ? null : stack.remove(stack.size() - 1); } /** * Looks at the top element type. * @return the top element type or null if the stack is empty */ public ElementType peek() { return isEmpty() ? null : stack.get(stack.size() - 1); } /** * Adds an element type to the stack. * @param type the type to add or null if the XML element is not an xCal * element */ public void push(ElementType type) { stack.add(type); } /** * Determines if the leaf node is under a {@code <parameters>} element. * @return true if it is, false if not */ public boolean isUnderParameters() { //get the first non-null type ElementType nonNull = null; for (int i = stack.size() - 1; i >= 0; i ElementType type = stack.get(i); if (type != null) { nonNull = type; break; } } //@formatter:off return nonNull == ElementType.parameters || nonNull == ElementType.parameter || nonNull == ElementType.parameterValue; //@formatter:on } /** * Determines if the stack is empty * @return true if the stack is empty, false if not */ public boolean isEmpty() { return stack.isEmpty(); } } /** * An implementation of {@link ErrorListener} that doesn't do anything. */ private static class NoOpErrorListener implements ErrorListener { public void error(TransformerException e) { //do nothing } public void fatalError(TransformerException e) { //do nothing } public void warning(TransformerException e) { //do nothing } } /** * Closes the underlying input stream. */ public void close() throws IOException { if (thread.isAlive()) { thread.closed = true; thread.interrupt(); } if (stream != null) { stream.close(); } } }
package com.abhiesa.blog; /** * @author abhiesa * @since 28/05/17. */ public abstract class Singleton { public static final Multiton MULTITON = new Multiton(); public Singleton() { } }
package com.akiban.ais.model; import java.io.Serializable; import java.util.*; public abstract class Table implements Serializable, ModelNames, Traversable, HasGroup { public abstract boolean isUserTable(); public String toString() { return tableName.toString(); } public static Table create(AkibanInformationSchema ais, Map<String, Object> map) { String tableType = (String) map.get(table_tableType); String schemaName = (String) map.get(table_schemaName); String tableName = (String) map.get(table_tableName); Integer tableId = (Integer) map.get(table_tableId); String groupName = (String) map.get(table_groupName); Table table = null; if (tableType.equals("USER")) { table = UserTable.create(ais, schemaName, tableName, tableId); } else if (tableType.equals("GROUP")) { table = GroupTable.create(ais, schemaName, tableName, tableId); } if (table != null && groupName != null) { Group group = ais.getGroup(groupName); table.setGroup(group); } assert table != null; table.migrationUsage = MigrationUsage.values()[(Integer) map.get(table_migrationUsage)]; return table; } public final Map<String, Object> map() { Map<String, Object> map = new HashMap<String, Object>(); map.put(table_tableType, isGroupTable() ? "GROUP" : "USER"); map.put(table_schemaName, getName().getSchemaName()); map.put(table_tableName, getName().getTableName()); map.put(table_tableId, getTableId()); map.put(table_groupName, getGroup() == null ? null : getGroup().getName()); map.put(table_migrationUsage, migrationUsage.ordinal()); return map; } protected Table(AkibanInformationSchema ais, String schemaName, String tableName, Integer tableId) { this.ais = ais; this.tableName = new TableName(schemaName, tableName); this.tableId = tableId; } public AkibanInformationSchema getAIS() { return ais; } public boolean isGroupTable() { return !isUserTable(); } public Integer getTableId() { return tableId; } /** * Temporary mutator so that prototype AIS management can renumber all * the tables once created. Longer term we want to give the table * its ID when generated. * * @param tableId */ public void setTableId(final int tableId) { this.tableId = tableId; } public TableName getName() { return tableName; } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } public Column getColumn(String columnName) { return columnMap.get(columnName.toLowerCase()); } public Column getColumn(Integer position) { return getColumns().get(position); } public List<Column> getColumns() { ensureColumnsUpToDate(); return removeInternalColumns(columns); } public List<Column> getColumnsIncludingInternal() { ensureColumnsUpToDate(); return columns; } public Collection<Index> getIndexes() { return Collections.unmodifiableCollection(internalGetIndexMap().values()); } public Index getIndex(String indexName) { return internalGetIndexMap().get(indexName.toLowerCase()); } public CharsetAndCollation getCharsetAndCollation() { return charsetAndCollation == null ? ais.getCharsetAndCollation() : charsetAndCollation; } public void setCharsetAndCollation(CharsetAndCollation charsetAndCollation) { this.charsetAndCollation = charsetAndCollation; } public void setCharset(String charset) { if (charset != null) { this.charsetAndCollation = CharsetAndCollation.intern(charset, getCharsetAndCollation().collation()); } } public void setCollation(String collation) { if (collation != null) { this.charsetAndCollation = CharsetAndCollation.intern(getCharsetAndCollation().charset(), collation); } } protected void addColumn(Column column) { columnMap.put(column.getName().toLowerCase(), column); columnsStale = true; } protected void addIndex(Index index) { Map<String, Index> old; Map<String, Index> withNewIndex; do { old = internalGetIndexMap(); withNewIndex = new TreeMap<String, Index>(old); withNewIndex.put(index.getIndexName().getName().toLowerCase(), index); } while(!internalIndexMapCAS(old, withNewIndex)); } void clearIndexes() { while (!internalIndexMapCAS(internalGetIndexMap(), Collections.<String,Index>emptyMap())) { // try again } } protected void dropColumns() { columnMap.clear(); columnsStale = true; } protected Table() { // XXX: GWT requires empty constructor } // For use by this package void setTableName(TableName tableName) { this.tableName = tableName; } public void removeIndexes(Collection<Index> indexesToDrop) { Map<String, Index> old; Map<String, Index> remaining; do { old = internalGetIndexMap(); remaining = new TreeMap<String, Index>( old ); remaining.values().removeAll(indexesToDrop); } while (!internalIndexMapCAS(old, remaining)); } /** * <p>Our intended migration policy; the grouping algorithm must also take these values into account.</p> * <p/> * <p>The enums {@linkplain #KEEP_ENGINE} and {@linkplain #INCOMPATIBLE} have similar effects on grouping and * migration: tables marked with these values will not be included in any groups, and during migration, their * storage engine is not changed to AkibanDb. The difference between the two enums is that {@linkplain #KEEP_ENGINE} * is set by the user and can later be changed to {@linkplain #AKIBAN_STANDARD} or * {@linkplain @#AKIBAN_LOOKUP_TABLE}; on the other hand, {@linkplain #INCOMPATIBLE} is set during analysis and * signifies that migration will not work for this table. The user should not be able to set this flag, and if * this flag is set, the user should not be able to change it.</p> */ public enum MigrationUsage { /** * Migrate this table to AkibanDb, grouping it as a standard user table. This is just a normal migration. */ AKIBAN_STANDARD, /** * Migrate this table to AkibanDb, but as a lookup table. Lookup tables are grouped alone. */ AKIBAN_LOOKUP_TABLE, /** * User wants to keep this table's engine as-is; don't migrate it to AkibanDb. */ KEEP_ENGINE, /** * This table can't be migrated to AkibanDb. */ INCOMPATIBLE; /** * Returns whether this usage requires an AkibanDB engine. * * @return whether this enum is one that requires AkibanDB */ public boolean isAkiban() { return (this == AKIBAN_STANDARD) || (this == AKIBAN_LOOKUP_TABLE); } /** * <p>Returns whether this usage requires that the table participate in grouping.</p> * <p/> * <p>Tables participate in grouping if they're AkibanDB (see {@linkplain #isAkiban()} <em>and</em> * are not lookups.</p> * * @return */ public boolean includeInGrouping() { return this == AKIBAN_STANDARD; } } public void checkIntegrity(List<String> out) { if (tableName == null) { out.add("table had null table name" + table); } for (Map.Entry<String, Column> entry : columnMap.entrySet()) { String name = entry.getKey(); Column column = entry.getValue(); if (column == null) { out.add("null column for name: " + name); } else if (name == null) { out.add("null name for column: " + column); } else if (!name.equals(column.getName())) { out.add("name mismatch, expected <" + name + "> for column " + column); } } if (!columnsStale) { for (Column column : columns) { if (column == null) { out.add("null column in columns list"); } else if (!columnMap.containsKey(column.getName())) { out.add("columns not stale, but map didn't contain column: " + column.getName()); } } } for (Map.Entry<String, Index> entry : internalGetIndexMap().entrySet()) { String name = entry.getKey(); Index index = entry.getValue(); if (name == null) { out.add("null name for index: " + index); } else if (index == null) { out.add("null index for name: " + name); } else if (index.getTable() != this) { out.add("table's index.getTable() wasn't the table" + index + " <--> " + this); } if (index != null) { for (IndexColumn indexColumn : index.getColumns()) { if (!index.equals(indexColumn.getIndex())) { out.add("index's indexColumn.getIndex() wasn't index: " + indexColumn); } Column column = indexColumn.getColumn(); if (!columnMap.containsKey(column.getName())) { out.add("index referenced a column not in the table: " + column); } } } } } public String getEngine() { return engine; } Map<String, Column> getColumnMap() { return columnMap; } public void rowDef(Object rowDef) { assert rowDef.getClass().getName().equals("com.akiban.server.RowDef") : rowDef.getClass(); this.rowDef = rowDef; } public Object rowDef() { return rowDef; } private void ensureColumnsUpToDate() { if (columnsStale) { columns.clear(); columns.addAll(columnMap.values()); Collections.sort(columns, new Comparator<Column>() { @Override public int compare(Column x, Column y) { return x.getPosition() - y.getPosition(); } }); columnsStale = false; } } private static List<Column> removeInternalColumns(List<Column> columns) { List<Column> declaredColumns = new ArrayList<Column>(columns); for (Iterator<Column> iterator = declaredColumns.iterator(); iterator.hasNext();) { Column column = iterator.next(); if (column.isAkibanPKColumn()) { iterator.remove(); } } return declaredColumns; } private Map<String, Index> internalGetIndexMap() { return indexMap; } private boolean internalIndexMapCAS(Map<String, Index> expected, Map<String, Index> update) { // GWT-friendly CAS synchronized (LOCK) { if (indexMap != expected) { return false; } indexMap = update; return true; } } // State protected AkibanInformationSchema ais; protected Group group; protected TableName tableName; private Integer tableId; private boolean columnsStale = true; private List<Column> columns = new ArrayList<Column>(); private volatile Map<String, Index> indexMap = Collections.emptyMap(); private Map<String, Column> columnMap = new TreeMap<String, Column>(); private CharsetAndCollation charsetAndCollation; protected MigrationUsage migrationUsage = MigrationUsage.AKIBAN_STANDARD; protected String engine; private final Object LOCK = new Object(); // It really is a RowDef, but declaring it that way creates trouble for AIS. We don't want to pull in // all the RowDef stuff and have it visible to GWT. private transient /*RowDef*/ Object rowDef; }
package com.apruve.models; import java.net.URL; import java.util.List; import javax.ws.rs.core.GenericType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang3.StringUtils; import com.apruve.ApruveClient; import com.apruve.ApruveResponse; import com.apruve.JsonUtil; /** * @author Robert Nelson * @since 0.2.0 */ @XmlRootElement public class LineItem { protected static final String LINE_ITEM_PATH = PaymentRequest.PAYMENT_REQUESTS_PATH + "%reqId/line_items/"; private String id; @XmlElement(name="payment_request_id") private String paymentRequestId; private String title; @XmlElement(name="amount_cents") private Integer amountCents; @XmlElement(name="price_ea_cents") private Integer priceEachCents; private Integer quantity; @XmlElement(name="merchant_notes") private String merchantNotes; private String description; @XmlElement(name="variant_info") private String variantInfo; private String sku; private String vendor; @XmlElement(name="view_product_url") private URL viewProductUrl; @XmlElement(name="plan_code") private String planCode; @XmlElement(name="line_item_api_url") private URL apiUrl; @XmlElement(name="subscription_url") private URL subscriptionUrl; protected LineItem() { // Required for JAXB } public LineItem(String title) { this.title = title; } protected String toValueString() { StringBuilder buf = new StringBuilder(); buf.append(this.getTitle()); buf.append(this.subscriptionValues()); if (this.getAmountCents() != null) buf.append(this.getAmountCents()); if (this.getPriceEachCents() != null) buf.append(this.getPriceEachCents()); if (this.getQuantity() != null) buf.append(this.getQuantity()); buf.append(StringUtils.defaultString(this.getDescription())); buf.append(StringUtils.defaultString(this.getVariantInfo())); buf.append(StringUtils.defaultString(this.getSku())); buf.append(StringUtils.defaultString(this.getVendor())); if (this.getViewProductUrl() != null) { buf.append(this.getViewProductUrl().toString()); } return buf.toString(); } protected String subscriptionValues() { return ""; } public static ApruveResponse<List<LineItem>> getAll(String paymentRequestId) { return ApruveClient.getInstance().index(getLineItemsPath(paymentRequestId), new GenericType<List<LineItem>>() {}); } public static ApruveResponse<? extends LineItem> get(String paymentRequestId, String lineItemId) { return ApruveClient.getInstance().get(getLineItemsPath(paymentRequestId) + lineItemId, LineItem.class); } public String toJson() { return JsonUtil.getInstance().toJson(this); } @Override public String toString() { return toJson(); } /** * @return the title */ public String getTitle() { return title; } /** * @param title * the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the amountCents */ public Integer getAmountCents() { return amountCents; } /** * @param amountCents * the amountCents to set */ public void setAmountCents(Integer amountCents) { this.amountCents = amountCents; } /** * @return the priceEachCents */ public Integer getPriceEachCents() { return priceEachCents; } /** * @param priceEachCents * the priceEachCents to set */ public void setPriceEachCents(Integer priceEachCents) { this.priceEachCents = priceEachCents; } /** * @return the quantity */ public Integer getQuantity() { return quantity; } /** * @param quantity * the quantity to set */ public void setQuantity(Integer quantity) { this.quantity = quantity; } public String getMerchantNotes() { return merchantNotes; } public void setMerchantNotes(String merchantNotes){ this.merchantNotes = merchantNotes; } /** * @return the description */ public String getDescription() { return description; } /** * @param description * the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the variantInfo */ public String getVariantInfo() { return variantInfo; } /** * @param variantInfo * the variantInfo to set */ public void setVariantInfo(String variantInfo) { this.variantInfo = variantInfo; } /** * @return the sku */ public String getSku() { return sku; } /** * @param sku * the sku to set */ public void setSku(String sku) { this.sku = sku; } /** * @return the vendor */ public String getVendor() { return vendor; } /** * @param vendor * the vendor to set */ public void setVendor(String vendor) { this.vendor = vendor; } /** * @return the viewProductUrl */ public URL getViewProductUrl() { return viewProductUrl; } /** * @param viewProductUrl * the viewProductUrl to set */ public void setViewProductUrl(URL viewProductUrl) { this.viewProductUrl = viewProductUrl; } public String getPlanCode() { return planCode; } public void setPlanCode(String planCode) { this.planCode = planCode; } public URL getSubscriptionUrl() { return subscriptionUrl; } public void setSubscriptionUrl(URL subscriptionUrl) { this.subscriptionUrl = subscriptionUrl; } public URL getApiUrl() { return apiUrl; } public void setApiUrl(URL apiUrl) { this.apiUrl = apiUrl; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPaymentRequestId() { return paymentRequestId; } public void setPaymentRequestId(String paymentRequestId) { this.paymentRequestId = paymentRequestId; } public static String getLineItemsPath(String paymentRequestId) { return LINE_ITEM_PATH.replace("%reqId", paymentRequestId); } }
package com.blade.mvc.http; import com.blade.kit.JsonKit; import com.blade.kit.StringKit; import com.blade.kit.WebKit; import com.blade.mvc.WebContext; import com.blade.mvc.handler.RouteActionArguments; import com.blade.mvc.multipart.FileItem; import com.blade.mvc.route.Route; import com.blade.server.netty.HttpConst; import io.netty.buffer.ByteBuf; import io.netty.util.CharsetUtil; import lombok.NonNull; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import static com.blade.kit.WebKit.UNKNOWN_MAGIC; /** * Http Request * * @author biezhi * 2017/5/31 */ public interface Request { /** * init request path parameters * * @param route route object * @return Return request */ Request initPathParams(Route route); /** * Get client host. * * @return Return client request host */ String host(); /** * Get client remote address. e.g: 102.331.234.11:38227 * * @return Return client ip and port */ String remoteAddress(); /** * Get request uri * * @return Return request uri */ String uri(); /** * Get request url * * @return request url */ String url(); /** * Get request user-agent * * @return return user-agent */ default String userAgent() { return header(HttpConst.USER_AGENT); } /** * Get request http protocol * * @return Return protocol */ String protocol(); /** * Get current application contextPath, default is "/" * * @return Return contextPath */ default String contextPath() { return WebContext.contextPath(); } /** * Get current request Path params, like /users/:uid * * @return Return parameters on the path Map */ Map<String, String> pathParams(); /** * Get a URL parameter * * @param name Parameter name * @return Return parameter value */ default String pathString(@NonNull String name) { return pathParams().get(name); } /** * Return a URL parameter for a Int type * * @param name Parameter name * @return Return Int parameter value */ default Integer pathInt(@NonNull String name) { String val = pathString(name); return StringKit.isNotEmpty(val) ? Integer.parseInt(val) : null; } /** * Return a URL parameter for a Long type * * @param name Parameter name * @return Return Long parameter value */ default Long pathLong(@NonNull String name) { String val = pathString(name); return StringKit.isNotEmpty(val) ? Long.parseLong(val) : null; } String queryString(); /** * Get current request query parameters * * @return Return request query Map */ Map<String, List<String>> parameters(); /** * Get current request query parameter names * * @return Return request query names * @since 2.0.8-RELEASE */ Set<String> parameterNames(); /** * Get current request query parameter values * * @param paramName param name * @return Return request query values * @since 2.0.8-RELEASE */ List<String> parameterValues(String paramName); /** * Get a request parameter * * @param name Parameter name * @return Return request parameter value */ default Optional<String> query(@NonNull String name) { List<String> values = parameters().get(name); if (null != values && values.size() > 0) return Optional.of(values.get(0)); return Optional.empty(); } /** * Get a request parameter, if NULL is returned to defaultValue * * @param name parameter name * @param defaultValue default String value * @return Return request parameter values */ default String query(@NonNull String name, @NonNull String defaultValue) { Optional<String> value = query(name); return value.orElse(defaultValue); } /** * Returns a request parameter for a Int type * * @param name Parameter name * @return Return Int parameter values */ default Optional<Integer> queryInt(@NonNull String name) { Optional<String> value = query(name); return value.map(Integer::parseInt); } /** * Returns a request parameter for a Int type * * @param name Parameter name * @param defaultValue default int value * @return Return Int parameter values */ default int queryInt(@NonNull String name, int defaultValue) { Optional<String> value = query(name); return value.map(Integer::parseInt).orElse(defaultValue); } /** * Returns a request parameter for a Long type * * @param name Parameter name * @return Return Long parameter values */ default Optional<Long> queryLong(@NonNull String name) { Optional<String> value = query(name); return value.map(Long::parseLong); } /** * Returns a request parameter for a Long type * * @param name Parameter name * @param defaultValue default long value * @return Return Long parameter values */ default long queryLong(@NonNull String name, long defaultValue) { Optional<String> value = query(name); return value.map(Long::parseLong).orElse(defaultValue); } /** * Returns a request parameter for a Double type * * @param name Parameter name * @return Return Double parameter values */ default Optional<Double> queryDouble(@NonNull String name) { Optional<String> value = query(name); return value.map(Double::parseDouble); } /** * Returns a request parameter for a Double type * * @param name Parameter name * @param defaultValue default double value * @return Return Double parameter values */ default double queryDouble(@NonNull String name, Double defaultValue) { Optional<String> value = query(name); return value.map(Double::parseDouble).orElse(defaultValue); } default Optional<Boolean> queryBoolean(@NonNull String name) { Optional<String> value = query(name); return value.map(Boolean::valueOf); } default boolean queryBoolean(@NonNull String name, Boolean defaultValue) { Optional<String> value = query(name); return value.map(Boolean::valueOf).orElse(defaultValue); } /** * Get current request http method. e.g: GET * * @return Return request method */ String method(); /** * Get current request HttpMethod. e.g: HttpMethod.GET * * @return Return HttpMethod */ HttpMethod httpMethod(); /** * @return whether the current request is a compressed request of GZIP * @since 2.0.9.BETA1 */ boolean useGZIP(); /** * Get client ip address * * @return Return server remote address */ default String address() { String address = WebKit.ipAddress(this); if (StringKit.isBlank(address) || UNKNOWN_MAGIC.equalsIgnoreCase(address)) { address = remoteAddress().split(":")[0]; } if (StringKit.isBlank(address)) { address = "Unknown"; } return address; } /** * Get current request session, if null then create * * @return Return current session */ Session session(); /** * Get current request contentType. e.g: "text/html; charset=utf-8" * * @return Return contentType */ default String contentType() { String contentType = header(HttpConst.CONTENT_TYPE_STRING); return null != contentType ? contentType : "Unknown"; } /** * Get current request is https. * * @return Return whether to use the SSL connection */ boolean isSecure(); /** * Get current request is ajax. According to the header "x-requested-with" * * @return Return current request is a AJAX request */ default boolean isAjax() { return "XMLHttpRequest".equals(header("X-Requested-With")) || "XMLHttpRequest".equals(header("x-requested-with")); } /** * Determine if this request is a FORM form request * <p> * According to header content-type contains "form" * * @return is form request */ default boolean isFormRequest() { return this.header(HttpConst.CONTENT_TYPE_STRING).toLowerCase().contains("form"); } /** * Determine if this request is a json request * <p> * According to header content-type contains "json" * * @return is json request */ default boolean isJsonRequest() { return this.header(HttpConst.CONTENT_TYPE_STRING).toLowerCase().contains("json"); } /** * Gets the current request is the head of the IE browser * * @return return current request is IE browser */ default boolean isIE() { String ua = userAgent(); return ua.contains("MSIE") || ua.contains("TRIDENT"); } /** * Get current request cookies * * @return return cookies */ Map<String, Cookie> cookies(); /** * Get String Cookie Value * * @param name cookie name * @return Return Cookie Value */ default String cookie(@NonNull String name) { Cookie cookie = cookies().get(name); return null != cookie ? cookie.value() : null; } /** * Get raw cookie by cookie name * * @param name cookie name * @return return Optional<Cookie> */ Cookie cookieRaw(String name); /** * Get String Cookie Value * * @param name cookie name * @param defaultValue default cookie value * @return Return Cookie Value */ default String cookie(@NonNull String name, @NonNull String defaultValue) { String cookie = cookie(name); return null != cookie ? cookie : defaultValue; } /** * Add a cookie to the request * * @param cookie cookie raw * @return return Request instance */ Request cookie(Cookie cookie); /** * Get current request headers. * * @return Return header information Map */ Map<String, String> headers(); /** * Get header information * * @param name Parameter name * @return Return header information */ default String header(@NonNull String name) { String header = ""; if (headers().containsKey(name)) { header = headers().get(name); } else if (headers().containsKey(name.toLowerCase())) { header = headers().get(name.toLowerCase()); } return header; } /** * Get header information * * @param name Parameter name * @param defaultValue default header value * @return Return header information */ default String header(@NonNull String name, @NonNull String defaultValue) { String value = header(name); return value.length() > 0 ? value : defaultValue; } /** * Get current request is KeepAlive, HTTP1.1 is true. * * @return return current request connection keepAlive */ boolean keepAlive(); /** * Bind form parameter to model * * @param modelClass model class type * @param <T> */ default <T> T bindWithForm(Class<T> modelClass) { return RouteActionArguments.parseModel(modelClass, this, null); } /** * Bind body parameter to model * * @param modelClass model class type * @param <T> */ default <T> T bindWithBody(Class<T> modelClass) { String json = this.bodyToString(); return StringKit.isNotEmpty(json) ? JsonKit.formJson(json, modelClass) : null; } /** * Get current request attributes * * @return Return all Attribute in Request */ Map<String, Object> attributes(); /** * Setting Request Attribute * * @param name attribute name * @param value attribute Value * @return set attribute value and return current request instance */ default Request attribute(@NonNull String name, Object value) { this.attributes().put(name, value); return this; } /** * Get a Request Attribute * * @param name Parameter name * @return Return parameter value */ default <T> T attribute(String name) { if (null == name) return null; Object object = attributes().get(name); return null != object ? (T) object : null; } /** * Get current request all fileItems * * @return return request file items */ Map<String, FileItem> fileItems(); /** * get file item by request part name * * @param name * @return return Optional<FileItem> */ default Optional<FileItem> fileItem(@NonNull String name) { return Optional.ofNullable(fileItems().get(name)); } /** * @return return whether Chunk content has been read * @since 2.0.11 */ boolean chunkIsEnd(); boolean isMultipart(); /** * Get current request body as ByteBuf * * @return Return request body */ ByteBuf body(); /** * Get current request body as string * * @return return request body to string */ default String bodyToString() { return this.body().toString(CharsetUtil.UTF_8); } }
package com.conveyal.gtfs; import com.conveyal.gtfs.error.GTFSError; import com.conveyal.gtfs.model.*; import com.conveyal.gtfs.model.Calendar; import com.conveyal.gtfs.validator.DuplicateStopsValidator; import com.conveyal.gtfs.validator.GTFSValidator; import com.conveyal.gtfs.validator.HopSpeedsReasonableValidator; import com.conveyal.gtfs.validator.MisplacedStopValidator; import com.conveyal.gtfs.validator.MissingStopCoordinatesValidator; import com.conveyal.gtfs.validator.NamesValidator; import com.conveyal.gtfs.validator.OverlappingTripsValidator; import com.conveyal.gtfs.validator.ReversedTripsValidator; import com.conveyal.gtfs.validator.TripTimesValidator; import com.conveyal.gtfs.validator.UnusedStopValidator; import com.conveyal.gtfs.stats.FeedStats; import com.conveyal.gtfs.validator.service.GeoUtils; import com.google.common.collect.*; import com.google.common.eventbus.EventBus; import com.vividsolutions.jts.algorithm.ConvexHull; import com.vividsolutions.jts.geom.*; import com.vividsolutions.jts.index.strtree.STRtree; import com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier; import org.geotools.referencing.GeodeticCalculator; import org.mapdb.BTreeMap; import org.mapdb.Bind; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.Fun; import org.mapdb.Fun.Tuple2; import org.mapdb.Serializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.time.ZoneId; import java.util.*; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentNavigableMap; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import static com.conveyal.gtfs.util.Util.human; /** * All entities must be from a single feed namespace. * Composed of several GTFSTables. */ public class GTFSFeed implements Cloneable, Closeable { private static final Logger LOG = LoggerFactory.getLogger(GTFSFeed.class); private DB db; public String feedId = null; // TODO make all of these Maps MapDBs so the entire GTFSFeed is persistent and uses constant memory /* Some of these should be multimaps since they don't have an obvious unique key. */ public final Map<String, Agency> agency; public final Map<String, FeedInfo> feedInfo; public final NavigableSet<Tuple2<String, Frequency>> frequencies; public final Map<String, Route> routes; public final Map<String, Stop> stops; public final Map<String, Transfer> transfers; public final Map<String, Trip> trips; public final Set<String> transitIds = new HashSet<>(); /** CRC32 of the GTFS file this was loaded from */ public long checksum; /* Map from 2-tuples of (shape_id, shape_pt_sequence) to shape points */ public final ConcurrentNavigableMap<Tuple2<String, Integer>, ShapePoint> shape_points; /* Map from 2-tuples of (trip_id, stop_sequence) to stoptimes. */ public final BTreeMap<Tuple2, StopTime> stop_times; public final ConcurrentMap<String, Long> stopCountByStopTime; public final NavigableSet<Tuple2<String, Tuple2>> stopStopTimeSet; /* A fare is a fare_attribute and all fare_rules that reference that fare_attribute. */ public final Map<String, Fare> fares; /* A service is a calendar entry and all calendar_dates that modify that calendar entry. */ public final Map<String, Service> services; /* A place to accumulate errors while the feed is loaded. Tolerate as many errors as possible and keep on loading. */ public final NavigableSet<GTFSError> errors; /* Stops spatial index which gets built lazily by getSpatialIndex() */ private transient STRtree spatialIndex; /* Convex hull of feed (based on stops) built lazily by getConvexHull() */ private transient Polygon convexHull; /* Merged stop buffers polygon built lazily by getMergedBuffers() */ private transient Geometry mergedBuffers; /* Create geometry factory to produce LineString geometries. */ GeometryFactory gf = new GeometryFactory(); /* Map routes to associated trip patterns. */ // TODO: Hash Multimapping in guava (might need dependency). public final Map<String, Pattern> patterns; // TODO bind this to map above so that it is kept up to date automatically public final Map<String, String> tripPatternMap; private boolean loaded = false; /* A place to store an event bus that is passed through constructor. */ public transient EventBus eventBus; /** * The order in which we load the tables is important for two reasons. * 1. We must load feed_info first so we know the feed ID before loading any other entities. This could be relaxed * by having entities point to the feed object rather than its ID String. * 2. Referenced entities must be loaded before any entities that reference them. This is because we check * referential integrity while the files are being loaded. This is done on the fly during loading because it allows * us to associate a line number with errors in objects that don't have any other clear identifier. * * Interestingly, all references are resolvable when tables are loaded in alphabetical order. */ public void loadFromFile(ZipFile zip, String fid) throws Exception { if (this.loaded) throw new UnsupportedOperationException("Attempt to load GTFS into existing database"); // NB we don't have a single CRC for the file, so we combine all the CRCs of the component files. NB we are not // simply summing the CRCs because CRCs are (I assume) uniformly randomly distributed throughout the width of a // long, so summing them is a convolution which moves towards a Gaussian with mean 0 (i.e. more concentrated // probability in the center), degrading the quality of the hash. Instead we XOR. Assuming each bit is independent, // this will yield a nice uniformly distributed result, because when combining two bits there is an equal // probability of any input, which means an equal probability of any output. At least I think that's all correct. // Repeated XOR is not commutative but zip.stream returns files in the order they are in the central directory // of the zip file, so that's not a problem. checksum = zip.stream().mapToLong(ZipEntry::getCrc).reduce((l1, l2) -> l1 ^ l2).getAsLong(); db.getAtomicLong("checksum").set(checksum); new FeedInfo.Loader(this).loadTable(zip); // maybe we should just point to the feed object itself instead of its ID, and null out its stoptimes map after loading if (fid != null) { feedId = fid; LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else if (feedId == null || feedId.isEmpty()) { feedId = new File(zip.getName()).getName().replaceAll("\\.zip$", ""); LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else { LOG.info("Feed ID is '{}'.", feedId); } db.getAtomicString("feed_id").set(feedId); new Agency.Loader(this).loadTable(zip); // calendars and calendar dates are joined into services. This means a lot of manipulating service objects as // they are loaded; since mapdb keys/values are immutable, load them in memory then copy them to MapDB once // we're done loading them Map<String, Service> serviceTable = new HashMap<>(); new Calendar.Loader(this, serviceTable).loadTable(zip); new CalendarDate.Loader(this, serviceTable).loadTable(zip); this.services.putAll(serviceTable); serviceTable = null; // free memory // Same deal Map<String, Fare> fares = new HashMap<>(); new FareAttribute.Loader(this, fares).loadTable(zip); new FareRule.Loader(this, fares).loadTable(zip); this.fares.putAll(fares); fares = null; // free memory new Route.Loader(this).loadTable(zip); new ShapePoint.Loader(this).loadTable(zip); new Stop.Loader(this).loadTable(zip); new Transfer.Loader(this).loadTable(zip); new Trip.Loader(this).loadTable(zip); new Frequency.Loader(this).loadTable(zip); new StopTime.Loader(this).loadTable(zip); // comment out this line for quick testing using NL feed LOG.info("{} errors", errors.size()); for (GTFSError error : errors) { LOG.info("{}", error); LOG.info("{}", error); } Bind.histogram(stop_times, stopCountByStopTime, (key, stopTime) -> stopTime.stop_id); Bind.secondaryKeys(stop_times, stopStopTimeSet, (key, stopTime) -> new String[] {stopTime.stop_id}); loaded = true; } public void loadFromFile(ZipFile zip) throws Exception { loadFromFile(zip, null); } public void toFile (String file) { try { File out = new File(file); OutputStream os = new FileOutputStream(out); ZipOutputStream zip = new ZipOutputStream(os); // write everything // TODO: fare attributes, fare rules, shapes // don't write empty feed_info.txt if (!this.feedInfo.isEmpty()) new FeedInfo.Writer(this).writeTable(zip); new Agency.Writer(this).writeTable(zip); new Calendar.Writer(this).writeTable(zip); new CalendarDate.Writer(this).writeTable(zip); new Frequency.Writer(this).writeTable(zip); new Route.Writer(this).writeTable(zip); new Stop.Writer(this).writeTable(zip); new ShapePoint.Writer(this).writeTable(zip); new Transfer.Writer(this).writeTable(zip); new Trip.Writer(this).writeTable(zip); new StopTime.Writer(this).writeTable(zip); zip.close(); LOG.info("GTFS file written"); } catch (Exception e) { LOG.error("Error saving GTFS: {}", e.getMessage()); throw new RuntimeException(e); } } // public void validate (EventBus eventBus, GTFSValidator... validators) { // if (eventBus == null) { // for (GTFSValidator validator : validators) { // validator.getClass().getSimpleName(); // validator.validate(this, false); public void validate (boolean repair, GTFSValidator... validators) { long startValidation = System.currentTimeMillis(); for (GTFSValidator validator : validators) { try { long startValidator = System.currentTimeMillis(); validator.validate(this, repair); long endValidator = System.currentTimeMillis(); long diff = endValidator - startValidator; LOG.info("{} finished in {} milliseconds.", validator.getClass().getSimpleName(), diff); } catch (Exception e) { LOG.error("Could not run {} validator.", validator.getClass().getSimpleName()); // LOG.error(e.toString()); e.printStackTrace(); } } long endValidation = System.currentTimeMillis(); long total = endValidation - startValidation; LOG.info("{} validators completed in {} milliseconds.", validators.length, total); } // validate function call that should explicitly list each validator to run on GTFSFeed public void validate () { validate(false, new DuplicateStopsValidator(), new HopSpeedsReasonableValidator(), new MisplacedStopValidator(), new MissingStopCoordinatesValidator(), new NamesValidator(), new OverlappingTripsValidator(), new ReversedTripsValidator(), new TripTimesValidator(), new UnusedStopValidator() ); } public void validateAndRepair () { validate(true, new DuplicateStopsValidator(), new HopSpeedsReasonableValidator(), new MisplacedStopValidator(), new MissingStopCoordinatesValidator(), new NamesValidator(), new OverlappingTripsValidator(), new ReversedTripsValidator(), new TripTimesValidator(), new UnusedStopValidator() ); } public FeedStats calculateStats() { FeedStats feedStats = new FeedStats(this); return feedStats; } public static GTFSFeed fromFile(String file) { return fromFile(file, null); } public static GTFSFeed fromFile(String file, String feedId) { GTFSFeed feed = new GTFSFeed(); ZipFile zip; try { zip = new ZipFile(file); if (feedId == null) { feed.loadFromFile(zip); } else { feed.loadFromFile(zip, feedId); } zip.close(); return feed; } catch (Exception e) { LOG.error("Error loading GTFS: {}", e.getMessage()); throw new RuntimeException(e); } } /** * For the given trip ID, fetch all the stop times in order of increasing stop_sequence. * This is an efficient iteration over a tree map. */ public Iterable<StopTime> getOrderedStopTimesForTrip (String trip_id) { Map<Fun.Tuple2, StopTime> tripStopTimes = stop_times.subMap( Fun.t2(trip_id, null), Fun.t2(trip_id, Fun.HI) ); return tripStopTimes.values(); } public STRtree getSpatialIndex () { if (this.spatialIndex == null) { synchronized (this) { if (this.spatialIndex == null) { // build spatial index STRtree stopIndex = new STRtree(); for(Stop stop : this.stops.values()) { try { if (Double.isNaN(stop.stop_lat) || Double.isNaN(stop.stop_lon)) { continue; } Coordinate stopCoord = new Coordinate(stop.stop_lat, stop.stop_lon); stopIndex.insert(new Envelope(stopCoord), stop); } catch (Exception e) { e.printStackTrace(); } } try { stopIndex.build(); this.spatialIndex = stopIndex; } catch (Exception e) { e.printStackTrace(); } } } } return this.spatialIndex; } /** Get the shape for the given shape ID */ public Shape getShape (String shape_id) { Shape shape = new Shape(this, shape_id); return shape.shape_dist_traveled.length > 0 ? shape : null; } /** * For the given trip ID, fetch all the stop times in order, and interpolate stop-to-stop travel times. */ public Iterable<StopTime> getInterpolatedStopTimesForTrip (String trip_id) throws FirstAndLastStopsDoNotHaveTimes { // clone stop times so as not to modify base GTFS structures StopTime[] stopTimes = StreamSupport.stream(getOrderedStopTimesForTrip(trip_id).spliterator(), false) .map(st -> st.clone()) .toArray(i -> new StopTime[i]); // avoid having to make sure that the array has length below. if (stopTimes.length == 0) return Collections.emptyList(); // first pass: set all partially filled stop times for (StopTime st : stopTimes) { if (st.arrival_time != Entity.INT_MISSING && st.departure_time == Entity.INT_MISSING) { st.departure_time = st.arrival_time; } if (st.arrival_time == Entity.INT_MISSING && st.departure_time != Entity.INT_MISSING) { st.arrival_time = st.departure_time; } } // quick check: ensure that first and last stops have times. // technically GTFS requires that both arrival_time and departure_time be filled at both the first and last stop, // but we are slightly more lenient and only insist that one of them be filled at both the first and last stop. // The meaning of the first stop's arrival time is unclear, and same for the last stop's departure time (except // in the case of interlining). // it's fine to just check departure time, as the above pass ensures that all stop times have either both // arrival and departure times, or neither if (stopTimes[0].departure_time == Entity.INT_MISSING || stopTimes[stopTimes.length - 1].departure_time == Entity.INT_MISSING) { throw new FirstAndLastStopsDoNotHaveTimes(); } // second pass: fill complete stop times int startOfInterpolatedBlock = -1; for (int stopTime = 0; stopTime < stopTimes.length; stopTime++) { if (stopTimes[stopTime].departure_time == Entity.INT_MISSING && startOfInterpolatedBlock == -1) { startOfInterpolatedBlock = stopTime; } else if (stopTimes[stopTime].departure_time != Entity.INT_MISSING && startOfInterpolatedBlock != -1) { // we have found the end of the interpolated section int nInterpolatedStops = stopTime - startOfInterpolatedBlock; double totalLengthOfInterpolatedSection = 0; double[] lengthOfInterpolatedSections = new double[nInterpolatedStops]; GeodeticCalculator calc = new GeodeticCalculator(); for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { Stop start = stops.get(stopTimes[stopTimeToInterpolate - 1].stop_id); Stop end = stops.get(stopTimes[stopTimeToInterpolate].stop_id); calc.setStartingGeographicPoint(start.stop_lon, start.stop_lat); calc.setDestinationGeographicPoint(end.stop_lon, end.stop_lat); double segLen = calc.getOrthodromicDistance(); totalLengthOfInterpolatedSection += segLen; lengthOfInterpolatedSections[i] = segLen; } // add the segment post-last-interpolated-stop Stop start = stops.get(stopTimes[stopTime - 1].stop_id); Stop end = stops.get(stopTimes[stopTime].stop_id); calc.setStartingGeographicPoint(start.stop_lon, start.stop_lat); calc.setDestinationGeographicPoint(end.stop_lon, end.stop_lat); totalLengthOfInterpolatedSection += calc.getOrthodromicDistance(); int departureBeforeInterpolation = stopTimes[startOfInterpolatedBlock - 1].departure_time; int arrivalAfterInterpolation = stopTimes[stopTime].arrival_time; int totalTime = arrivalAfterInterpolation - departureBeforeInterpolation; double lengthSoFar = 0; for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { lengthSoFar += lengthOfInterpolatedSections[i]; int time = (int) (departureBeforeInterpolation + totalTime * (lengthSoFar / totalLengthOfInterpolatedSection)); stopTimes[stopTimeToInterpolate].arrival_time = stopTimes[stopTimeToInterpolate].departure_time = time; } // we're done with this block startOfInterpolatedBlock = -1; } } return Arrays.asList(stopTimes); } public Collection<Frequency> getFrequencies (String trip_id) { // IntelliJ tells me all these casts are unnecessary, and that's also my feeling, but the code won't compile // without them return (List<Frequency>) frequencies.subSet(new Fun.Tuple2(trip_id, null), new Fun.Tuple2(trip_id, Fun.HI)).stream() .map(t2 -> ((Tuple2<String, Frequency>) t2).b) .collect(Collectors.toList()); } public List<String> getOrderedStopListForTrip (String trip_id) { Iterable<StopTime> orderedStopTimes = getOrderedStopTimesForTrip(trip_id); List<String> stops = Lists.newArrayList(); // In-order traversal of StopTimes within this trip. The 2-tuple keys determine ordering. for (StopTime stopTime : orderedStopTimes) { stops.add(stopTime.stop_id); } return stops; } /** * Bin all trips by the sequence of stops they visit. * @return A map from a list of stop IDs to a list of Trip IDs that visit those stops in that sequence. */ public void findPatterns() { int n = 0; Multimap<TripPatternKey, String> tripsForPattern = HashMultimap.create(); for (String trip_id : trips.keySet()) { if (++n % 100000 == 0) { LOG.info("trip {}", human(n)); } Trip trip = trips.get(trip_id); // no need to scope ID here, this is in the context of a single object TripPatternKey key = new TripPatternKey(trip.route_id); StreamSupport.stream(getOrderedStopTimesForTrip(trip_id).spliterator(), false) .forEach(key::addStopTime); tripsForPattern.put(key, trip_id); } // create an in memory list because we will rename them and they need to be immutable once they hit mapdb List<Pattern> patterns = tripsForPattern.asMap().entrySet() .stream() .map((e) -> new Pattern(this, e.getKey().stops, new ArrayList<>(e.getValue()))) .collect(Collectors.toList()); namePatterns(patterns); patterns.stream().forEach(p -> { this.patterns.put(p.pattern_id, p); p.associatedTrips.stream().forEach(t -> this.tripPatternMap.put(t, p.pattern_id)); }); LOG.info("Total patterns: {}", tripsForPattern.keySet().size()); } /** destructively rename passed in patterns */ private void namePatterns(Collection<Pattern> patterns) { LOG.info("Generating unique names for patterns"); Map<String, PatternNamingInfo> namingInfoForRoute = new HashMap<>(); for (Pattern pattern : patterns) { if (pattern.associatedTrips.isEmpty() || pattern.orderedStops.isEmpty()) continue; Trip trip = trips.get(pattern.associatedTrips.get(0)); // TODO this assumes there is only one route associated with a pattern String route = trip.route_id; // names are unique at the route level if (!namingInfoForRoute.containsKey(route)) namingInfoForRoute.put(route, new PatternNamingInfo()); PatternNamingInfo namingInfo = namingInfoForRoute.get(route); if (trip.trip_headsign != null) namingInfo.headsigns.put(trip.trip_headsign, pattern); // use stop names not stop IDs as stops may have duplicate names and we want unique pattern names String fromName = stops.get(pattern.orderedStops.get(0)).stop_name; String toName = stops.get(pattern.orderedStops.get(pattern.orderedStops.size() - 1)).stop_name; namingInfo.fromStops.put(fromName, pattern); namingInfo.toStops.put(toName, pattern); pattern.orderedStops.stream().map(stops::get).forEach(stop -> { if (fromName.equals(stop.stop_name) || toName.equals(stop.stop_name)) return; namingInfo.vias.put(stop.stop_name, pattern); }); namingInfo.patternsOnRoute.add(pattern); } // name the patterns on each route for (PatternNamingInfo info : namingInfoForRoute.values()) { for (Pattern pattern : info.patternsOnRoute) { pattern.name = null; // clear this now so we don't get confused later on String headsign = trips.get(pattern.associatedTrips.get(0)).trip_headsign; String fromName = stops.get(pattern.orderedStops.get(0)).stop_name; String toName = stops.get(pattern.orderedStops.get(pattern.orderedStops.size() - 1)).stop_name; /* We used to use this code but decided it is better to just always have the from/to info, with via if necessary. if (headsign != null && info.headsigns.get(headsign).size() == 1) { // easy, unique headsign, we're done pattern.name = headsign; continue; } if (info.toStops.get(toName).size() == 1) { pattern.name = String.format(Locale.US, "to %s", toName); continue; } if (info.fromStops.get(fromName).size() == 1) { pattern.name = String.format(Locale.US, "from %s", fromName); continue; } */ // check if combination from, to is unique Set<Pattern> intersection = new HashSet<>(info.fromStops.get(fromName)); intersection.retainAll(info.toStops.get(toName)); if (intersection.size() == 1) { pattern.name = String.format(Locale.US, "from %s to %s", fromName, toName); continue; } // check for unique via stop pattern.orderedStops.stream().map(stops::get).forEach(stop -> { Set<Pattern> viaIntersection = new HashSet<>(intersection); viaIntersection.retainAll(info.vias.get(stop.stop_name)); if (viaIntersection.size() == 1) { pattern.name = String.format(Locale.US, "from %s to %s via %s", fromName, toName, stop.stop_name); } }); if (pattern.name == null) { // no unique via, one pattern is subset of other. if (intersection.size() == 2) { Iterator<Pattern> it = intersection.iterator(); Pattern p0 = it.next(); Pattern p1 = it.next(); if (p0.orderedStops.size() > p1.orderedStops.size()) { p1.name = String.format(Locale.US, "from %s to %s express", fromName, toName); p0.name = String.format(Locale.US, "from %s to %s local", fromName, toName); } else if (p1.orderedStops.size() > p0.orderedStops.size()){ p0.name = String.format(Locale.US, "from %s to %s express", fromName, toName); p1.name = String.format(Locale.US, "from %s to %s local", fromName, toName); } } } if (pattern.name == null) { // give up pattern.name = String.format(Locale.US, "from %s to %s like trip %s", fromName, toName, pattern.associatedTrips.get(0)); } } // attach a stop and trip count to each for (Pattern pattern : info.patternsOnRoute) { pattern.name = String.format(Locale.US, "%s stops %s (%s trips)", pattern.orderedStops.size(), pattern.name, pattern.associatedTrips.size()); } } } public LineString getStraightLineForStops(String trip_id) { CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); Iterable<StopTime> stopTimes; stopTimes = getOrderedStopTimesForTrip(trip.trip_id); if (Iterables.size(stopTimes) > 1) { for (StopTime stopTime : stopTimes) { Stop stop = stops.get(stopTime.stop_id); Double lat = stop.stop_lat; Double lon = stop.stop_lon; coordinates.add(new Coordinate(lon, lat)); } ls = gf.createLineString(coordinates.toCoordinateArray()); } // set ls equal to null if there is only one stopTime to avoid an exception when creating linestring else{ ls = null; } return ls; } /** * Returns a trip geometry object (LineString) for a given trip id. * If the trip has a shape reference, this will be used for the geometry. * Otherwise, the ordered stoptimes will be used. * * @param trip_id trip id of desired trip geometry * @return the LineString representing the trip geometry. * @see LineString */ public LineString getTripGeometry(String trip_id){ CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); // If trip has shape_id, use it to generate geometry. if (trip.shape_id != null) { Shape shape = getShape(trip.shape_id); if (shape != null) ls = shape.geometry; } // Use the ordered stoptimes. if (ls == null) { ls = getStraightLineForStops(trip_id); } return ls; } public double getTripDistance (String trip_id, boolean straightLine) { return straightLine ? GeoUtils.getDistance(this.getStraightLineForStops(trip_id)) : GeoUtils.getDistance(this.getTripGeometry(trip_id)); } public double getTripSpeed (String trip_id) { return getTripSpeed(trip_id, false); } public double getTripSpeed (String trip_id, boolean straightLine) { StopTime firstStopTime = this.stop_times.ceilingEntry(Fun.t2(trip_id, null)).getValue(); StopTime lastStopTime = this.stop_times.floorEntry(Fun.t2(trip_id, Fun.HI)).getValue(); // ensure that stopTime returned matches trip id (i.e., that the trip has stoptimes) if (!firstStopTime.trip_id.equals(trip_id) || !lastStopTime.trip_id.equals(trip_id)) { return Double.NaN; } double distance = getTripDistance(trip_id, straightLine); int time = lastStopTime.arrival_time - firstStopTime.departure_time; return distance / time; // meters per second } public ZoneId getTimeZoneForStop (String stop_id) { SortedSet<Tuple2<String, Tuple2>> index = stopStopTimeSet.subSet(new Tuple2<>(stop_id, null), new Tuple2(stop_id, Fun.HI)); StopTime stopTime = this.stop_times.get(index.first().b); Trip trip = this.trips.get(stopTime.trip_id); Route route = this.routes.get(trip.route_id); Agency agency = route.agency_id != null ? this.agency.get(route.agency_id) : this.agency.get(0); return ZoneId.of(agency.agency_timezone); } // TODO: code review public Geometry getMergedBuffers() { if (this.mergedBuffers == null) { // synchronized (this) { Collection<Geometry> polygons = new ArrayList<>(); for (Stop stop : this.stops.values()) { if (stopCountByStopTime != null && !stopCountByStopTime.containsKey(stop.stop_id)) { continue; } if (stop.stop_lat > -1 && stop.stop_lat < 1 || stop.stop_lon > -1 && stop.stop_lon < 1) { continue; } Point stopPoint = gf.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)); Polygon stopBuffer = (Polygon) stopPoint.buffer(.01); polygons.add(stopBuffer); } Geometry multiGeometry = gf.buildGeometry(polygons); this.mergedBuffers = multiGeometry.union(); if (polygons.size() > 100) { this.mergedBuffers = DouglasPeuckerSimplifier.simplify(this.mergedBuffers, .001); } } return this.mergedBuffers; } public Polygon getConvexHull() { if (this.convexHull == null) { synchronized (this) { List<Coordinate> coordinates = this.stops.values().stream().map( stop -> new Coordinate(stop.stop_lon, stop.stop_lat) ).collect(Collectors.toList()); Coordinate[] coords = coordinates.toArray(new Coordinate[coordinates.size()]); ConvexHull convexHull = new ConvexHull(coords, gf); this.convexHull = (Polygon) convexHull.getConvexHull(); } } return this.convexHull; } /** * Cloning can be useful when you want to make only a few modifications to an existing feed. * Keep in mind that this is a shallow copy, so you'll have to create new maps in the clone for tables you want * to modify. */ @Override public GTFSFeed clone() { try { return (GTFSFeed) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public void close () { db.close(); } /** Thrown when we cannot interpolate stop times because the first or last stops do not have times */ public class FirstAndLastStopsDoNotHaveTimes extends Exception { /** do nothing */ } private static class PatternNamingInfo { Multimap<String, Pattern> headsigns = HashMultimap.create(); Multimap<String, Pattern> fromStops = HashMultimap.create(); Multimap<String, Pattern> toStops = HashMultimap.create(); Multimap<String, Pattern> vias = HashMultimap.create(); List<Pattern> patternsOnRoute = new ArrayList<>(); } /** Create a GTFS feed in a temp file */ public GTFSFeed () { // calls to this must be first operation in constructor - why, Java? this(DBMaker.newTempFileDB() .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .deleteFilesAfterClose() .compressionEnable() // .cacheSize(1024 * 1024) this bloats memory consumption .make()); // TODO db.close(); } /** Create a GTFS feed connected to a particular DB, which will be created if it does not exist. */ public GTFSFeed (String dbFile) { this(DBMaker.newFileDB(new File(dbFile)) .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .compressionEnable() // .cacheSize(1024 * 1024) this bloats memory consumption .make()); // TODO db.close(); } private GTFSFeed (DB db) { this.db = db; agency = db.getTreeMap("agency"); feedInfo = db.getTreeMap("feed_info"); routes = db.getTreeMap("routes"); trips = db.getTreeMap("trips"); stop_times = db.getTreeMap("stop_times"); frequencies = db.getTreeSet("frequencies"); transfers = db.getTreeMap("transfers"); stops = db.getTreeMap("stops"); fares = db.getTreeMap("fares"); services = db.getTreeMap("services"); shape_points = db.getTreeMap("shape_points"); feedId = db.getAtomicString("feed_id").get(); checksum = db.getAtomicLong("checksum").get(); // use Java serialization because MapDB serialization is very slow with JTS as they have a lot of references. // nothing else contains JTS objects patterns = db.createTreeMap("patterns") .valueSerializer(Serializer.JAVA) .makeOrGet(); tripPatternMap = db.getTreeMap("patternForTrip"); stopCountByStopTime = db.getTreeMap("stopCountByStopTime"); stopStopTimeSet = db.getTreeSet("stopStopTimeSet"); errors = db.getTreeSet("errors"); System.out.println(errors.iterator().hasNext() ? errors.iterator().next().errorType : "no val"); } }
package com.dua3.utility.io; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; /** * Utility class for Inpit/Output. */ public class IOUtil { /** * Get file extension. * * @param path * the path * @return the extension */ public static String getExtension(Path path) { String fname = path.getFileName().toString(); int pos = fname.lastIndexOf('.'); return pos < 0 ? "" : fname.substring(pos + 1); } /** * Read content of path into String. * * @param path * the Path * @param cs * the Charset * @return content of path * @throws IOException * if content could not be read */ public static String read(Path path, Charset cs) throws IOException { return new String(Files.readAllBytes(path), cs); } /** * Write content String to a path. * * @param path * the Path * @param text * the text * @param options * the options to use (see {@link OpenOption}) * @throws IOException * if something goes wrong */ public static void write(Path path, String text, OpenOption... options) throws IOException { try (BufferedWriter writer = Files.newBufferedWriter(path, options)) { writer.append(text); } } private IOUtil() { // utility class } }
package com.github.jsonj; import static com.github.jsonj.tools.JsonBuilder.fromObject; import static com.github.jsonj.tools.JsonBuilder.primitive; import com.github.jsonj.exceptions.JsonTypeMismatchException; import com.github.jsonj.tools.JsonBuilder; import com.github.jsonj.tools.JsonSerializer; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.ListIterator; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.stream.Stream; import javax.annotation.Nonnull; import org.apache.commons.lang3.StringUtils; /** * Representation of json arrays. */ public class JsonArray extends ArrayList<JsonElement> implements JsonElement { private static final long serialVersionUID = -1269731858619421388L; private boolean immutable=false; public JsonArray() { super(); } public JsonArray(@Nonnull Collection<?> existing) { super(); for(Object o: existing) { add(fromObject(o)); } } public JsonArray(@Nonnull Stream<Object> s) { super(); s.forEach(o -> this.addObject(o)); } /** * Allows you to add any kind of object. * @param o the value; will be passed through fromObject() * @return true if object was added */ public boolean addObject(Object o) { return this.add(fromObject(o)); } /** * @param p a predicate * @return array of elements matching p */ public @Nonnull JsonArray filter(@Nonnull Predicate<JsonElement> p) { return stream().filter(p).collect(JsonjCollectors.array()); } /** * @param p a predicate * @return an optional of the first element matching p or Optional.empty() if nothing matches */ public Optional<JsonElement> findFirstMatching(@Nonnull Predicate<JsonElement> p) { for(JsonElement e: this) { if(p.test(e)) { return Optional.of(e); } } return Optional.empty(); } /** * Allows you to lookup objects from an array by e.g. their id. * @param fieldName field to match on * @param value value of the field * @return the first object where field == value, or null */ public Optional<JsonObject> findFirstWithFieldValue(@Nonnull String fieldName, String value) { JsonElement result = findFirstMatching(e -> { if(!e.isObject()) { return false; } JsonObject object = e.asObject(); String fieldValue = object.getString(fieldName); if(fieldValue !=null) { return fieldValue.equals(value); } else { return false; } }).orElse(null); if(result != null) { return Optional.of(result.asObject()); } else { return Optional.empty(); } } /** * Variant of add that takes a string instead of a JsonElement. The inherited add only supports JsonElement. * @param s string * @return true if element was added successfully */ public boolean add(String s) { return add(primitive(s)); } /** * Variant of add that adds one or more strings. * @param strings values */ public void add(String...strings) { for (String s : strings) { add(primitive(s)); } } /** * Variant of add that adds one or more numbers (float/int). * @param numbers values */ public void add(Number...numbers) { for (Number n : numbers) { add(primitive(n)); } } /** * Variant of add that adds one or more booleans. * @param booleans values */ public void add(@Nonnull Boolean...booleans) { for (Boolean b : booleans) { add(primitive(b)); } } /** * Variant of add that adds one or more JsonElements. * @param elements elements */ public void add(@Nonnull JsonElement...elements) { for (JsonElement element : elements) { add(element); } } /** * Variant of add that adds one or more JsonBuilders. This means you don't have to call get() on the builder when adding object builders. * @param elements builders */ public void add(@Nonnull JsonBuilder...elements) { for (JsonBuilder element : elements) { add(element.get()); } } public void add(@Nonnull JsonDataObject...elements) { for (JsonDataObject element : elements) { add(element.getJsonObject()); } } @Override public boolean add(JsonElement e) { if(immutable) { throw new IllegalStateException("object is immutable"); } return super.add(e); } @Override public void add(int index, JsonElement element) { if(immutable) { throw new IllegalStateException("object is immutable"); } super.add(index, element); } @Override public boolean addAll(@SuppressWarnings("rawtypes") Collection c) { for (Object element : c) { if(element instanceof JsonElement) { add((JsonElement)element); } else { add(primitive(element)); } } return c.size() != 0; } /** * Convenient method providing a few alternate ways of extracting elements * from a JsonArray. * * @param label label * @return the first element in the array matching the label or the n-th * element if the label is an integer and the element an object or * an array. */ public JsonElement get(String label) { int i = 0; try{ for (JsonElement e : this) { if(e.isPrimitive() && e.asPrimitive().asString().equals(label)) { return e; } else if((e.isObject() || e.isArray()) && Integer.valueOf(label).equals(i)) { return e; } i++; } } catch(NumberFormatException e) { // fail gracefully return null; } // the element was not found return null; } public Optional<JsonElement> maybeGet(int index) { if(index>=size()) { // prevent index out of bounds exception return Optional.empty(); } return Optional.ofNullable(get(index)); } public Optional<String> maybeGetString(int index) { return maybeGet(index).map(e -> e.asString()); } public Optional<Integer> maybeGetInt(int index) { return maybeGet(index).map(e -> e.asInt()); } public Optional<Long> maybeGetLong(int index) { return maybeGet(index).map(e -> e.asLong()); } public Optional<Number> maybeGetNumber(int index) { return maybeGet(index).map(e -> e.asNumber()); } public Optional<Boolean> maybeGetBoolean(int index) { return maybeGet(index).map(e -> e.asBoolean()); } public Optional<JsonArray> maybeGetArray(int index) { return maybeGet(index).map(e -> e.asArray()); } public Optional<JsonSet> maybeGetSet(int index) { return maybeGet(index).map(e -> e.asSet()); } public Optional<JsonObject> maybeGetObject(int index) { return maybeGet(index).map(e -> e.asObject()); } public JsonElement first() { return get(0); } public JsonElement last() { return get(size()-1); } /** * Variant of contains that checks if the array contains something that can be extracted with JsonElement get(final String label). * @param label label * @return true if the array contains the element */ public boolean contains(final String label) { return get(label) != null; } @Override public JsonType type() { return JsonType.array; } @Override public @Nonnull JsonObject asObject() { throw new JsonTypeMismatchException("not an object"); } @Override public @Nonnull JsonArray asArray() { return this; } @Override public @Nonnull JsonSet asSet() { JsonSet set = JsonBuilder.set(); set.addAll(this); return set; } public double[] asDoubleArray() { double[] result = new double[size()]; int i=0; for(JsonElement e: this) { result[i++] = e.asPrimitive().asDouble(); } return result; } public int[] asIntArray() { int[] result = new int[size()]; int i=0; for(JsonElement e: this) { result[i++] = e.asPrimitive().asInt(); } return result; } public String[] asStringArray() { String[] result = new String[size()]; int i=0; for(JsonElement e: this) { result[i++] = e.asPrimitive().asString(); } return result; } @Override public JsonPrimitive asPrimitive() { throw new JsonTypeMismatchException("not a primitive"); } @Override public float asFloat() { throw new JsonTypeMismatchException("not a primitive"); } @Override public double asDouble() { throw new JsonTypeMismatchException("not a primitive"); } @Override public int asInt() { throw new JsonTypeMismatchException("not a primitive"); } @Override public long asLong() { throw new JsonTypeMismatchException("not a primitive"); } @Override public boolean asBoolean() { throw new JsonTypeMismatchException("not a primitive"); } @Override public String asString() { throw new JsonTypeMismatchException("not a primitive"); } @Override public boolean isObject() { return false; } @Override public boolean isArray() { return true; } @Override public boolean isPrimitive() { return false; } @Override public boolean equals(final Object o) { if (o == null) { return false; } if (!(o instanceof JsonArray)) { return false; } JsonArray array = (JsonArray) o; if (size() != array.size()) { return false; } for(int i=0; i<size();i++) { JsonElement e1 = get(i); JsonElement e2 = array.get(i); if(!e1.equals(e2)) { return false; } } return true; } @Override public int hashCode() { int code = 7; for (JsonElement e : this) { code += e.hashCode(); } return code; } @Override public @Nonnull Object clone() { return deepClone(); } @SuppressWarnings("unchecked") @Override public @Nonnull JsonArray deepClone() { JsonArray array = new JsonArray(); for (JsonElement jsonElement : this) { JsonElement e = jsonElement.deepClone(); array.add(e); } return array; } @Override public @Nonnull JsonArray immutableClone() { JsonArray array = new JsonArray(); for (JsonElement jsonElement : this) { JsonElement e = jsonElement.immutableClone(); array.add(e); } array.immutable=true; return array; } @Override public boolean isMutable() { return !immutable; } public boolean isNotEmpty() { return !isEmpty(); } @Override public boolean isEmpty() { boolean empty = true; if(size() > 0) { for (JsonElement element : this) { empty = empty && element.isEmpty(); if(!empty) { return false; } } } return empty; } @Override public boolean remove(Object o) { if(immutable) { throw new IllegalStateException("object is immutable"); } if(o instanceof JsonElement) { return super.remove(o); } else { // try remove it as a primitive. return super.remove(primitive(o)); } } @Override public void removeEmpty() { if(immutable) { throw new IllegalStateException("object is immutable"); } Iterator<JsonElement> iterator = iterator(); while (iterator.hasNext()) { JsonElement jsonElement = iterator.next(); if(jsonElement.isEmpty()) { iterator.remove(); } else { jsonElement.removeEmpty(); } } } @Override public String toString() { return JsonSerializer.serialize(this,false); } @Override public void serialize(Writer w) throws IOException { w.append(JsonSerializer.OPEN_BRACKET); Iterator<JsonElement> it = iterator(); while (it.hasNext()) { JsonElement jsonElement = it.next(); jsonElement.serialize(w); if(it.hasNext()) { w.append(JsonSerializer.COMMA); } } w.append(JsonSerializer.CLOSE_BRACKET); } @Override public String prettyPrint() { return JsonSerializer.serialize(this, true); } @Override public boolean isNumber() { return false; } @Override public boolean isBoolean() { return false; } @Override public boolean isNull() { return false; } @Override public boolean isString() { return false; } /** * Replaces the first matching element. * @param e1 original * @param e2 replacement * @return true if the element was replaced. */ public boolean replace(JsonElement e1, JsonElement e2) { int index = indexOf(e1); if(index>=0) { set(index, e2); return true; } else { return false; } } /** * Replaces the element. * @param e1 original * @param e2 replacement * @return true if element was replaced */ public boolean replace(Object e1, Object e2) { return replace(fromObject(e1),fromObject(e2)); } /** * Convenient replace method that allows you to replace an object based on field equality for a specified field. * Useful if you have an id field in your objects. Note, the array may contain non objects as well or objects * without the specified field. Those elements won't be replaced of course. * * @param e1 object you want replaced; must have a value at the specified path * @param e2 replacement * @param path path * @return true if something was replaced. */ public boolean replaceObject(JsonObject e1, JsonObject e2, String...path) { JsonElement compareElement = e1.get(path); if(compareElement == null) { throw new IllegalArgumentException("specified path may not be null in object " + StringUtils.join(path)); } int i=0; for(JsonElement e: this) { if(e.isObject()) { JsonElement fieldValue = e.asObject().get(path); if(compareElement.equals(fieldValue)) { set(i,e2); return true; } } i++; } return false; } @Override public JsonElement set(int index, JsonElement element) { if(immutable) { throw new IllegalStateException("object is immutable"); } return super.set(index, element); } @Override public boolean addAll(int index, Collection<? extends JsonElement> c) { if(immutable) { throw new IllegalStateException("object is immutable"); } return super.addAll(index, c); } @Override public void ensureCapacity(int minCapacity) { if(immutable) { throw new IllegalStateException("object is immutable"); } super.ensureCapacity(minCapacity); } @Override public @Nonnull Iterator<JsonElement> iterator() { if(immutable) { Iterator<JsonElement> it = super.iterator(); return new Iterator<JsonElement>() { @Override public boolean hasNext() { return it.hasNext(); } @Override public JsonElement next() { return it.next(); } @Override public void remove() { throw new IllegalStateException("object is immutable"); } }; } else { return super.iterator(); } } @Override public JsonElement remove(int index) { if(immutable) { throw new IllegalStateException("object is immutable"); } return super.remove(index); } @Override public boolean removeAll(Collection<?> c) { if(immutable) { throw new IllegalStateException("object is immutable"); } return super.removeAll(c); } @Override public boolean removeIf(Predicate<? super JsonElement> filter) { if(immutable) { throw new IllegalStateException("object is immutable"); } return super.removeIf(filter); } @Override public ListIterator<JsonElement> listIterator() { if(immutable) { throw new IllegalStateException("object is immutable"); } return super.listIterator(); } @Override public ListIterator<JsonElement> listIterator(int index) { if(immutable) { throw new IllegalStateException("object is immutable"); } return super.listIterator(index); } @Override public void replaceAll(UnaryOperator<JsonElement> operator) { if(immutable) { throw new IllegalStateException("object is immutable"); } super.replaceAll(operator); } @Override public boolean retainAll(Collection<?> c) { if(immutable) { throw new IllegalStateException("object is immutable"); } return super.retainAll(c); } /** * Convenience method to prevent casting JsonElement to JsonObject when iterating in the common case that you have * an array of JsonObjects. * * @return iterable that iterates over JsonObjects instead of JsonElements. */ public @Nonnull Iterable<JsonObject> objects() { final JsonArray parent=this; return () -> { final Iterator<JsonElement> iterator = parent.iterator(); return new Iterator<JsonObject>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public JsonObject next() { return iterator.next().asObject(); } @Override public void remove() { iterator.remove(); } }; }; } public @Nonnull Stream<JsonObject> streamObjects() { return stream().map(e -> e.asObject()); } public @Nonnull Stream<JsonArray> streamArrays() { return stream().map(e -> e.asArray()); } public @Nonnull Stream<String> streamStrings() { return stream().map(e -> e.asString()); } public @Nonnull Stream<JsonElement> map(Function<JsonElement,JsonElement> f) { return stream().map(f); } public @Nonnull Stream<JsonObject> mapObjects(Function<JsonObject, JsonObject> f) { return streamObjects().map(f); } public void forEachObject(@Nonnull Consumer<? super JsonObject> action) { for (JsonElement e : this) { action.accept(e.asObject()); } } /** * Convenience method to prevent casting JsonElement to JsonArray when iterating in the common case that you have * an array of JsonArrays. * * @return iterable that iterates over JsonArrays instead of JsonElements. */ public @Nonnull Iterable<JsonArray> arrays() { final JsonArray parent=this; return () -> { final Iterator<JsonElement> iterator = parent.iterator(); return new Iterator<JsonArray>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public JsonArray next() { return iterator.next().asArray(); } @Override public void remove() { iterator.remove(); } }; }; } /** * Convenience method to prevent casting JsonElement to String when iterating in the common case that you have * an array of strings. * * @return iterable that iterates over Strings instead of JsonElements. */ public @Nonnull Iterable<String> strings() { final JsonArray parent=this; return () -> { final Iterator<JsonElement> iterator = parent.iterator(); return new Iterator<String>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public String next() { return iterator.next().asString(); } @Override public void remove() { iterator.remove(); } }; }; } /** * Convenience method to prevent casting JsonElement to Double when iterating in the common case that you have * an array of doubles. * * @return iterable that iterates over Doubles instead of JsonElements. */ public @Nonnull Iterable<Double> doubles() { final JsonArray parent=this; return () -> { final Iterator<JsonElement> iterator = parent.iterator(); return new Iterator<Double>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Double next() { return iterator.next().asDouble(); } @Override public void remove() { iterator.remove(); } }; }; } /** * Convenience method to prevent casting JsonElement to Long when iterating in the common case that you have * an array of longs. * * @return iterable that iterates over Longs instead of JsonElements. */ public @Nonnull Iterable<Long> longs() { final JsonArray parent=this; return () -> { final Iterator<JsonElement> iterator = parent.iterator(); return new Iterator<Long>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Long next() { return iterator.next().asLong(); } @Override public void remove() { iterator.remove(); } }; }; } /** * Convenience method to prevent casting JsonElement to Long when iterating in the common case that you have * an array of longs. * * @return iterable that iterates over Longs instead of JsonElements. */ public @Nonnull Iterable<Integer> ints() { final JsonArray parent=this; return () -> { final Iterator<JsonElement> iterator = parent.iterator(); return new Iterator<Integer>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Integer next() { return iterator.next().asInt(); } @Override public void remove() { iterator.remove(); } }; }; } }
package com.blarg.gdx.tilemap3d; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.RenderableProvider; import com.badlogic.gdx.graphics.g3d.materials.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.materials.Material; import com.badlogic.gdx.graphics.g3d.materials.TextureAttribute; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.Pool; public class TileChunk extends TileContainer implements TileRawDataContainer, RenderableProvider, Disposable { final int x; final int y; final int z; final int width; final int height; final int depth; final Tile[] data; final BoundingBox bounds; final BoundingBox tmpBounds = new BoundingBox(); final Vector3 position; final Vector3 tmpPosition = new Vector3(); Mesh opaqueMesh; Mesh alphaMesh; final Material opaqueMaterial = new Material(); final Material alphaMaterial = new Material(); final BoundingBox meshBounds = new BoundingBox(); public final TileMap tileMap; @Override public Tile[] getData() { return data; } @Override public int getWidth() { return width; } @Override public int getHeight() { return height; } @Override public int getDepth() { return depth; } @Override public int getMinX() { return x; } @Override public int getMinY() { return y; } @Override public int getMinZ() { return z; } @Override public int getMaxX() { return x + width - 1; } @Override public int getMaxY() { return y + height - 1; } @Override public int getMaxZ() { return z + depth - 1; } @Override public Vector3 getPosition() { tmpPosition.set(position); return tmpPosition; } @Override public BoundingBox getBounds() { tmpBounds.set(bounds); return tmpBounds; } public BoundingBox getMeshBounds() { tmpBounds.set(meshBounds); return tmpBounds; } public int getNumVertices() { return opaqueMesh != null ? opaqueMesh.getNumVertices() : 0; } public int getNumAlphaVertices() { return alphaMesh != null ? alphaMesh.getNumVertices() : 0; } public TileChunk(int x, int y, int z, int width, int height, int depth, TileMap tileMap) { if (tileMap == null) throw new IllegalArgumentException(); this.tileMap = tileMap; this.x = x; this.y = y; this.z = z; this.width = width; this.height = height; this.depth = depth; this.position = new Vector3(x, y, z); bounds = new BoundingBox(); bounds.min.set(x, y, z); bounds.max.set(x + width, y + height, z + depth); int numTiles = width * height * depth; data = new Tile[numTiles]; for (int i = 0; i < numTiles; ++i) data[i] = new Tile(); opaqueMesh = null; alphaMesh = null; opaqueMaterial.set(TextureAttribute.createDiffuse(tileMap.tileMeshes.atlas.texture)); alphaMaterial.set(TextureAttribute.createDiffuse(tileMap.tileMeshes.atlas.texture)); alphaMaterial.set(new BlendingAttribute()); } public void updateVertices(ChunkVertexGenerator generator) { ChunkVertexGenerator.GeneratedChunkMeshes generatedMeshes = generator.generate(this); meshBounds.clr(); if (generatedMeshes.opaqueMesh.getNumVertices() > 0) { opaqueMesh = generatedMeshes.opaqueMesh; opaqueMesh.calculateBoundingBox(tmpBounds); meshBounds.ext(tmpBounds); } else opaqueMesh = null; if (generatedMeshes.alphaMesh.getNumVertices() > 0) { alphaMesh = generatedMeshes.alphaMesh; alphaMesh.calculateBoundingBox(tmpBounds); meshBounds.ext(tmpBounds); } else alphaMesh = null; } public Tile getWithinSelfOrNeighbour(int x, int y, int z) { int checkX = x + this.x; int checkY = y + this.y; int checkZ = z + this.z; return tileMap.get(checkX, checkY, checkZ); } public Tile getWithinSelfOrNeighbourSafe(int x, int y, int z) { int checkX = x + this.x; int checkY = y + this.y; int checkZ = z + this.z; if (!tileMap.isWithinBounds(checkX, checkY, checkZ)) return null; else return tileMap.get(checkX, checkY, checkZ); } @Override public Tile get(int x, int y, int z) { int index = getIndexOf(x, y, z); return data[index]; } @Override public Tile getSafe(int x, int y, int z) { if (!isWithinLocalBounds(x, y, z)) return null; else return get(x, y, z); } private int getIndexOf(int x, int y, int z) { return (y * width * depth) + (z * width) + x; } @Override public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) { if (opaqueMesh != null) renderables.add(getRenderableFor(pool, opaqueMesh, opaqueMaterial, null)); if (alphaMesh != null) renderables.add(getRenderableFor(pool, alphaMesh, alphaMaterial, null)); } private Renderable getRenderableFor(Pool<Renderable> pool, Mesh mesh, Material material, Object userData) { Renderable renderable = pool.obtain(); renderable.mesh = mesh; renderable.meshPartOffset = 0; renderable.meshPartSize = mesh.getNumVertices(); renderable.primitiveType = GL20.GL_TRIANGLES; renderable.bones = null; renderable.lights = null; renderable.shader = null; renderable.userData = userData; renderable.material = material; return renderable; } @Override public void dispose() { opaqueMesh.dispose(); alphaMesh.dispose(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TileChunk tileChunk = (TileChunk)o; if (x != tileChunk.x) return false; if (y != tileChunk.y) return false; if (z != tileChunk.z) return false; if (tileMap != null ? !tileMap.equals(tileChunk.tileMap) : tileChunk.tileMap != null) return false; return true; } @Override public int hashCode() { int result = x; result = 31 * result + y; result = 31 * result + z; result = 31 * result + (tileMap != null ? tileMap.hashCode() : 0); return result; } }
package com.jaamsim.events; import java.util.ArrayList; /** * Process is a subclass of Thread that can be managed by the discrete event * simulation. * * This is the basis for all functionality required by startProcess and the * discrete event model. Each process creates its own thread to run in. These * threads are managed by the eventManager and when a Process has completed * running is pooled for reuse. * * LOCKING: All state in the Process must be updated from a synchronized block * using the Process itself as the lock object. Care must be taken to never take * the eventManager's lock while holding the Process's lock as this can cause a * deadlock with other threads trying to wake you from the threadPool. */ public final class Process extends Thread { // Properties required to manage the pool of available Processes private static final ArrayList<Process> pool; // storage for all available Processes private static final int maxPoolSize = 100; // Maximum number of Processes allowed to be pooled at a given time private static int numProcesses = 0; // Total of all created processes to date (used to name new Processes) private static double timeScale; // the scale from discrete to continuous time private static double secondsPerTick; // The reciprocal of ticksPerSecond private ProcessTarget target; // The entity whose method is to be executed private EventManager eventManager; // The EventManager that is currently managing this Process private Process nextProcess; // The Process from which the present process was created private int flags; // Present execution state of the process static final int TERMINATE = 0x01; // The process should terminate immediately static final int ACTIVE = 0x02; // The process is currently executing code static final int COND_WAIT = 0x04; // The process is waiting for a condition to be satisfied static final int SCHED_WAIT = 0x08; // The process is waiting until a future simulation time // Note: The ACTIVE, COND_WAIT, and SCED_WAIT flags are mutually exclusive. // The TERMINATE flag can only be set at the same time as COND_WAIT or a // SCHED_WAIT flag. // Initialize the storage for the pooled Processes static { pool = new ArrayList<Process>(maxPoolSize); } private Process(String name) { // Construct a thread with the given name super(name); // Initialize the state flags flags = 0; } /** * Returns the currently executing Process. */ public static final Process current() { Thread cur = Thread.currentThread(); if (cur instanceof Process) return (Process)cur; throw new ProcessError("Non-process thread called Process.current()"); } public static final boolean isModelProcess() { return (Thread.currentThread() instanceof Process); } public static final long currentTick() { return Process.current().eventManager.currentTick(); } /** * Run method invokes the method on the target with the given arguments. * A process loops endlessly after it is created executing the method on the * target set as the entry point. After completion, it calls endProcess and * will return it to a process pool if space is available, otherwise the resources * including the backing thread will be released. * * This method is called by Process.getProcess() */ @Override public void run() { while (true) { synchronized (pool) { // Add ourselves to the pool and wait to be assigned work pool.add(this); // Set the present process to sleep, and release its lock // (done by pool.wait();) // Note: the try/while(true)/catch construct is needed to avoid // spurious wake ups allowed as of Java 5. All legitimate wake // ups are done through the InterruptedException. try { while (true) { pool.wait(); } } catch (InterruptedException e) {} } // Process has been woken up, execute the method we have been assigned this.execute(); // Ensure all state is cleared before returning to the pool synchronized (this) { eventManager = null; nextProcess = null; target = null; flags = 0; } } } private void execute() { ProcessTarget procTarget; // Save a locally-consistent processTarget, synchronized // against against a call to allocate() from a separate thread synchronized (this) { procTarget = this.target; this.target = null; } try { // Execute the method procTarget.process(); // Notify the event manager that the process has been completed synchronized (this) { eventManager.releaseProcess(); } return; } catch (ThreadKilledException e) { // If the process was killed by a terminateThread method then // return to the beginning of the process loop return; } catch (Throwable e) { eventManager.handleProcessError(e); } } // Set up a new process for the given entity, method, and arguments // Called from Process.start() and from EventManager.startExternalProcess() static Process allocate(EventManager eventManager, ProcessTarget proc) { // Create the new process Process newProcess = Process.getProcess(); // Setup the process state for execution synchronized (newProcess) { newProcess.target = proc; newProcess.eventManager = eventManager; newProcess.flags = 0; } return newProcess; } // Return a process from the pool or create a new one private static Process getProcess() { while (true) { synchronized (pool) { // If there is an available process in the pool, then use it if (pool.size() > 0) { return pool.remove(pool.size() - 1); } // If there are no process in the pool, then create a new one and add it to the pool else { numProcesses++; Process temp = new Process("processthread-" + numProcesses); temp.start(); // Note: Thread.start() calls Process.run which adds the new process to the pool } } // Allow the Process.run method to execute so that it can add the // new process to the pool // Note: that the lock on the pool has been dropped, so that the // Process.run method can grab it. try { Thread.sleep(10); } catch (InterruptedException e) {} } } synchronized void setNextProcess(Process next) { nextProcess = next; } /** * Return the next process and set it to null as we are about to switch to that process. */ synchronized Process getAndClearNextProcess() { Process p = nextProcess; nextProcess = null; return p; } /** * Debugging aid to test that we are not executing a conditional event, useful * to try and catch places where a waitUntil was missing a waitUntilEnded. * While not fatal, it will print out a stack dump to try and find where the * waitUntilEnded was missed. */ void assertNotWaitUntil() { if (!this.testFlag(Process.COND_WAIT)) return; System.out.println("AUDIT - waitUntil without waitUntilEnded " + this); for (StackTraceElement elem : this.getStackTrace()) { System.out.println(elem.toString()); } } synchronized void setFlag(int flag) { flags |= flag; } synchronized void clearFlag(int flag) { flags &= ~flag; } synchronized boolean testFlag(int flag) { return (flags & flag) != 0; } static void setSimTimeScale(double scale) { timeScale = scale; secondsPerTick = 3600.0d / scale; } /** * Return the number of seconds represented by the given number of ticks. */ public static final double ticksToSeconds(long ticks) { return ticks * secondsPerTick; } public static double getSimTimeFactor() { return timeScale; } public static double getEventTolerance() { return (1.0d / getSimTimeFactor()); } }
package com.bunkr_beta; import com.bunkr_beta.interfaces.IArchiveInfoContext; import com.bunkr_beta.inventory.Inventory; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.*; import java.security.NoSuchAlgorithmException; public class ArchiveInfoContext implements IArchiveInfoContext { public final File filePath; private Inventory inventory; private Descriptor descriptor; private int blockSize; private long blockDataLength; private boolean fresh = false; public ArchiveInfoContext(File filePath) throws IOException, NoSuchAlgorithmException { this.filePath = filePath; this.refresh(); } @Override public void refresh() throws IOException, NoSuchAlgorithmException { try(FileInputStream fis = new FileInputStream(this.filePath)) { try(DataInputStream dis = new DataInputStream(fis)) { String fivebytes = IO.readNByteString(dis, 5); if (! fivebytes.equals("BUNKR")) throw new IOException("File format header does not match 'BUNKR'"); dis.readByte(); dis.readByte(); dis.readByte(); this.blockSize = dis.readInt(); this.blockDataLength = dis.readLong(); IO.reliableSkip(dis, this.blockDataLength); String descjson = IO.readString(dis); this.descriptor = new ObjectMapper().readValue(descjson, Descriptor.class); if (this.descriptor.encryption == null) { this.inventory = new ObjectMapper().readValue(IO.readString(dis), Inventory.class); } else { int l = dis.readInt(); byte[] encryptedInventory = new byte[l]; assert l == dis.read(encryptedInventory); // TODO add assymetrics key decryption here throw new RuntimeException("Not implemented"); } } } this.fresh = true; } @Override public boolean isFresh() { return this.fresh; } @Override public void invalidate() { this.fresh = false; } @Override public void assertFresh() { if (! isFresh()) { throw new AssertionError("ArchiveInfoContext is no longer fresh"); } } @Override public int getBlockSize() { return blockSize; } @Override public Descriptor getDescriptor() { return descriptor; } @Override public Inventory getInventory() { return inventory; } @Override public long getNumBlocks() { return this.blockDataLength / this.blockSize; } @Override public long getBlockDataLength() { return blockDataLength; } }
package com.chess.genesis; import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteCursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.preference.PreferenceManager; import java.util.Date; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; class GameDataDB { private final SQLiteDatabase db; private final Context context; public GameDataDB(final Context _context) { context = _context; db = (new DatabaseOpenHelper(context)).getWritableDatabase(); } public void close() { db.close(); } public static Bundle rowToBundle(final SQLiteCursor cursor, final int index) { final Bundle bundle = new Bundle(); final String[] column = cursor.getColumnNames(); cursor.moveToPosition(index); for (int i = 0; i < cursor.getColumnCount(); i++) bundle.putString(column[i], cursor.getString(i)); return bundle; } public String getUsername() { final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); return pref.getString("username", "!error!"); } /* * Local Game Queries */ public Bundle newLocalGame(final String gamename, final int gametype, final int opponent) { final long time = (new Date()).getTime(); final Object[] data = {gamename, time, time, gametype, opponent}; final String[] data2 = {String.valueOf(time)}; db.execSQL("INSERT INTO localgames (name, ctime, stime, gametype, opponent) VALUES (?, ?, ?, ?, ?);", data); final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery("SELECT * FROM localgames WHERE ctime=?", data2); final Bundle game = rowToBundle(cursor, 0); game.putInt("type", Enums.LOCAL_GAME); return game; } public void saveLocalGame(final int id, final long stime, final String zfen, final String history) { final Object[] data = {stime, zfen, history, id}; db.execSQL("UPDATE localgames SET stime=?, zfen=?, history=? WHERE id=?;", data); } public void renameLocalGame(final int id, final String name) { final Object[] data = {name, id}; db.execSQL("UPDATE localgames SET name=? WHERE id=?;", data); } public void deleteLocalGame(final int id) { final Object[] data = {id}; db.execSQL("DELETE FROM localgames WHERE id=?;", data); } public void deleteAllLocalGames() { db.execSQL("DELETE FROM localgames;"); } public SQLiteCursor getLocalGameList() { return (SQLiteCursor) db.rawQuery("SELECT * FROM localgames ORDER BY stime DESC", null); } public void copyGameToLocal(final String gameid, final int gametype) { final String[] data = {gameid}; final String type = (gametype == Enums.ONLINE_GAME)? "onlinegames" : "archivegames"; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery("SELECT * FROM " + type + " WHERE gameid=?", data); final Bundle row = rowToBundle(cursor, 0); final long time = (new Date()).getTime(); final String tnames = "(name, ctime, stime, gametype, opponent, zfen, history)"; final String dstring = "(?, ?, ?, ?, ?, ?, ?)"; final Object[] data2 = {row.get("white") + " vs. " + row.get("black"), time, time, row.get("gametype"), Enums.HUMAN_OPPONENT, row.get("zfen"), row.get("history")}; db.execSQL("INSERT INTO localgames" + tnames + " VALUES " + dstring + ";", data2); } /* * Online Game Queries */ public void insertOnlineGame(final JSONObject json) { try { final String gameid = json.getString("gameid"); final String white = json.getString("white"); final String black = json.getString("black"); final String zfen = json.getString("zfen"); final String history = json.getString("history"); final long ctime = json.getLong("ctime"); final long stime = json.getLong("stime"); final int gametype = Enums.GameType(json.getString("gametype")); final int eventtype = Enums.EventType(json.getString("eventtype")); final int status = Enums.GameStatus(json.getString("status")); final int idle = (json.has("idle")? 1:0) + (json.has("nudge")? 1:0) + (json.has("close")? 1:0); final int drawoffer = json.has("drawoffer")? (json.getString("drawoffer").equals("white")? Piece.WHITE : Piece.BLACK) : 0; final GameInfo info = new GameInfo(context, status, history, white, drawoffer); final int ply = info.getPly(), yourturn = info.getYourTurn(); final Object[] data = {gameid, gametype, eventtype, status, ctime, stime, yourturn, ply, white, black, zfen, history, idle, drawoffer}; final String q1 = "INSERT OR REPLACE INTO onlinegames "; final String q2 = "(gameid, gametype, eventtype, status, ctime, stime, "; final String q3 = "yourturn, ply, white, black, zfen, history, idle, drawoffer) "; final String q4 = "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; db.execSQL(q1 + q2 + q3 + q4, data); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void updateOnlineGame(final JSONObject json) { try { final String gameid = json.getString("gameid"); final String[] data1 = {gameid}; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery("SELECT * FROM onlinegames WHERE gameid=?", data1); if (cursor.getCount() < 1) { insertOnlineGame(json); return; } final String zfen = json.getString("zfen"); final String history = json.getString("history"); final long stime = json.getLong("stime"); final int status = Enums.GameStatus(json.getString("status")); final int idle = (json.has("idle")? 1:0) + (json.has("nudge")? 1:0) + (json.has("close")? 1:0); final int drawoffer = json.has("drawoffer")? (json.getString("drawoffer").equals("white")? Piece.WHITE : Piece.BLACK) : 0; final Bundle row = rowToBundle(cursor, 0); final GameInfo info = new GameInfo(context, status, history, row.getString("white"), drawoffer); final int ply = info.getPly(), yourturn = info.getYourTurn(); final Object[] data2 = {stime, status, ply, yourturn, zfen, history, idle, drawoffer, gameid}; db.execSQL("UPDATE onlinegames SET stime=?, status=?, ply=?, yourturn=?, zfen=?, history=?, idle=?, drawoffer=? WHERE gameid=?;", data2); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public long getNewestOnlineTime() { final String username = getUsername(); final String[] data = {username, username}; final String query = "SELECT stime FROM onlinegames WHERE white=? OR black=? ORDER BY stime DESC LIMIT 1"; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery(query, data); if (cursor.getCount() == 0) return 0; cursor.moveToFirst(); return cursor.getLong(0); } public ObjectArray<String> getOnlineGameIds() { final ObjectArray<String> list = new ObjectArray<String>(); final String username = getUsername(); final String[] data = {username, username}; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery("SELECT gameid FROM onlinegames WHERE white=? OR black=?", data); cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { list.push(cursor.getString(0)); cursor.moveToNext(); } return list; } public SQLiteCursor getOnlineGameList(final int yourturn) { final String username = getUsername(); final String[] data = {username, username, String.valueOf(yourturn)}; final String query = "SELECT * FROM onlinegames LEFT JOIN (SELECT gameid, unread FROM msgtable WHERE unread=1) USING(gameid) " + "WHERE (white=? OR black=?) AND yourturn=? GROUP BY gameid ORDER BY stime DESC"; return (SQLiteCursor) db.rawQuery(query, data); } public Bundle getOnlineGameData(final String gameid) { final String[] data = {gameid}; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery("SELECT * from onlinegames WHERE gameid=?", data); return rowToBundle(cursor, 0); } public void recalcYourTurn() { final String username = getUsername(); final String[] data = {username, username}; final String query = "SELECT gameid, status, history, white, drawoffer FROM onlinegames WHERE white=? or black=?;"; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery(query, data); cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { final String gameid = cursor.getString(0); final int status = cursor.getInt(1); final String history = cursor.getString(2); final String white = cursor.getString(3); final int drawoffer = cursor.getInt(4); final GameInfo info = new GameInfo(context, status, history, white, drawoffer); final Object[] data2 = {info.getYourTurn(), gameid}; db.execSQL("UPDATE onlinegames SET yourturn=? WHERE gameid=?;", data2); cursor.moveToNext(); } } /* * Archive Game Queries */ public void insertArchiveGame(final JSONObject json) { try { final String gameid = json.getString("gameid"); final int gametype = Enums.GameType(json.getString("gametype")); final int eventtype = Enums.EventType(json.getString("eventtype")); final int status = Enums.GameStatus(json.getString("status")); final long ctime = json.getLong("ctime"); final long stime = json.getLong("stime"); final String white = json.getString("white"); final String black = json.getString("black"); final String zfen = json.getString("zfen"); final String history = json.getString("history"); int w_psrfrom = 0; int w_psrto = 0; int b_psrfrom = 0; int b_psrto = 0; if (eventtype != Enums.INVITE) { w_psrfrom = json.getJSONObject("score").getJSONObject("white").getInt("from"); w_psrto = json.getJSONObject("score").getJSONObject("white").getInt("to"); b_psrfrom = json.getJSONObject("score").getJSONObject("black").getInt("from"); b_psrto = json.getJSONObject("score").getJSONObject("black").getInt("to"); } final String tmp[] = zfen.split(":"); final int ply = Integer.valueOf(tmp[tmp.length - 1]); final Object[] data = {gameid, gametype, eventtype, status, w_psrfrom, w_psrto, b_psrfrom, b_psrto, ctime, stime, ply, white, black, zfen, history}; final String q1 = "INSERT OR REPLACE INTO archivegames "; final String q2 = "(gameid, gametype, eventtype, status, w_psrfrom, w_psrto, b_psrfrom, b_psrto, "; final String q3 = "ctime, stime, ply, white, black, zfen, history) "; final String q4 = "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; db.execSQL(q1 + q2 + q3 + q4, data); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void deleteArchiveGame(final String gameid) { final Object[] data = {gameid}; db.execSQL("DELETE FROM archivegames WHERE gameid=?;", data); } public ObjectArray<String> getArchiveGameIds() { final ObjectArray<String> list = new ObjectArray<String>(); final String username = getUsername(); final String[] data = {username, username}; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery("SELECT gameid FROM archivegames WHERE white=? OR black=?", data); cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { list.push(cursor.getString(0)); cursor.moveToNext(); } return list; } public SQLiteCursor getArchiveGameList() { final String username = getUsername(); final String[] data = {username, username}; final String query = "SELECT * FROM archivegames LEFT JOIN " + "(SELECT gameid, unread FROM msgtable WHERE unread=1) USING(gameid) " + "WHERE white=? OR black=? GROUP BY gameid ORDER BY stime DESC"; return (SQLiteCursor) db.rawQuery(query, data); } public void archiveNetworkGame(final String gameid, final int w_from, final int w_to, final int b_from, final int b_to) { final String[] data = {gameid}; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery("SELECT * FROM onlinegames WHERE gameid=?", data); final Bundle row = rowToBundle(cursor, 0); final String tnames = "(gameid, gametype, eventtype, status, w_psrfrom, w_psrto, b_psrfrom, b_psrto, ctime, stime, ply, white, black, zfen, history)"; final String dstring = "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; final Object[] data2 = {row.get("gameid"), row.get("gametype"), row.get("eventtype"), row.get("status"), w_from, w_to, b_from, b_to, row.get("ctime"), row.get("stime"), row.get("ply"), row.get("white"), row.get("black"), row.get("zfen"), row.get("history")}; db.execSQL("INSERT OR REPLACE INTO archivegames " + tnames + " VALUES " + dstring + ";", data2); db.execSQL("DELETE FROM onlinegames WHERE gameid=?;", data); } /* * Chat Queries */ public void insertMsg(final JSONObject json) { try { final String user = getUsername(); final JSONArray players = json.getJSONArray("players"); final String gameid = json.getString("gameid"), username = json.getString("username"), opponent = (username.equals(players.getString(0)))? players.getString(1) : players.getString(0), msg = json.getString("txt"); final long time = json.getLong("time"); final int unread = (user.equals(username))? 0 : 1; final Object[] data = {gameid, time, username, msg, opponent, unread}; db.execSQL("INSERT OR IGNORE INTO msgtable (gameid, time, username, msg, opponent, unread) VALUES (?, ?, ?, ?, ?, ?);", data); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(); } } public void setMsgsRead(final String gameid) { final Object[] data = {gameid}; db.execSQL("UPDATE msgtable SET unread=0 WHERE gameid=?", data); } public void setAllMsgsRead() { final Object[] data = {}; db.execSQL("UPDATE msgtable SET unread=0;", data); } public int getUnreadMsgCount(final String gameid) { final String[] data = {gameid}; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery("SELECT COUNT(unread) FROM msgtable WHERE unread=1 AND gameid=?", data); cursor.moveToFirst(); return cursor.getInt(0); } public int getUnreadMsgCount() { final String username = getUsername(); final String[] data = {username, username}; final String query = "SELECT COUNT(*) FROM msgtable WHERE unread=1 AND (username=? OR opponent=?)"; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery(query, data); cursor.moveToFirst(); return cursor.getInt(0); } public long getNewestMsg() { final String username = getUsername(); final String[] data = {username, username}; final SQLiteCursor cursor = (SQLiteCursor) db.rawQuery("SELECT time FROM msgtable WHERE username=? OR opponent=? ORDER BY time DESC LIMIT 1", data); if (cursor.getCount() == 0) return 0; cursor.moveToFirst(); return cursor.getLong(0); } public SQLiteCursor getMsgList(final String gameid) { final String username = getUsername(); final String[] data = {gameid, username, username}; return (SQLiteCursor) db.rawQuery("SELECT * FROM msgtable WHERE gameid=? AND (username=? OR opponent=?) ORDER BY time ASC", data); } }
package com.coolweather.app.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtil { public static void sendHttpRequest(final String address,final HttpCallbackListener listener) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(address); connection (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while((line = reader.readLine())!=null){ response.append(line); } if(listener !=null){ listener.onFinish(response.toString()); } } catch (Exception e) { // TODO: handle exception } } }) } }
package hackerrank; import java.util.Scanner; public class BiggerIsGreater { private static String nextPermutation(String str) { // TODO return null; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = in.nextInt(); for (int t = 0; t < testCases; t++) { String str = in.next(); System.out.println(nextPermutation(str)); } } }
package infovis.draw; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; /** * Realizes the actual painting of labels. * * @author Joschi <josua.krause@googlemail.com> */ public interface LabelRealizer { /** * Draws a label. * * @param g The graphics context. * @param view The current view-port. * @param scale The current scale. * @param pos The position where the label should be drawn. * @param text The text of the label. * @param isImportantNode Whether this node is important. */ void drawLabel(Graphics2D g, Rectangle2D view, double scale, Point2D pos, String text, boolean isImportantNode); /** * The standard way to draw labels. * * @author Joschi <josua.krause@googlemail.com> */ LabelRealizer STANDARD = new LabelRealizer() { private final float minZoomLevel = 10; private final float maxZoomLevel = 120; @Override public void drawLabel(final Graphics2D g, final Rectangle2D view, final double scale, final Point2D pos, final String label, final boolean isImportantNode) { final StringDrawer sd = new StringDrawer(g, label, pos); final Rectangle2D bbox = sd.getBounds(); if(!view.intersects(bbox)) return; final float d = (float) (scale * scale); final float alpha = isImportantNode ? d : (d - minZoomLevel) / (maxZoomLevel - minZoomLevel); if(alpha <= 0f) return; final Graphics2D g2 = (Graphics2D) g.create(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f * Math.min(1f, alpha))); g2.setColor(Color.WHITE); final double arc = bbox.getHeight() / 3; final double space = bbox.getHeight() / 6; g2.fill(new RoundRectangle2D.Double(bbox.getMinX() - space, bbox.getMinY() - space, bbox.getWidth() + 2 * space, bbox.getHeight() + 2 * space, arc, arc)); g2.dispose(); if(alpha < 1f) { g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } g.setColor(Color.BLACK); sd.draw(); } }; }
package com.exedio.cronjob; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.Principal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.exedio.cops.CopsServlet; import com.exedio.cops.Resource; public class CronjobManager extends CopsServlet { private static final long serialVersionUID =100000000000001L; static final Resource stylesheet = new Resource("cronjob.css"); static final Resource logo = new Resource("logo.png"); private List<Handler> handlers; @Override public void init() throws ServletException { super.init(); System.out.println("CronjobManager is starting ... (" + System.identityHashCode(this) + ')'); final String STORE = "store"; final String storeNames=getServletConfig().getInitParameter(STORE); if (storeNames==null) { throw new RuntimeException("ERROR: Servlet-Init-Parameter: >> "+STORE+" << was expected but not found"); } final List<CronjobStore> stores = new ArrayList<CronjobStore>(); for ( final String storeName: storeNames.split(",") ) { final Class<?> storeClass; try { storeClass = Class.forName(storeName); } catch (final ClassNotFoundException e) { throw new RuntimeException("ERROR: A class with name: "+storeName+" was not found", e); } final Constructor<?> storeConstructor; try { storeConstructor = storeClass.getConstructor(ServletConfig.class); } catch(final NoSuchMethodException e) { throw new RuntimeException("ERROR: Class "+storeClass+" has no suitable constructor", e); } final Object o; try { o = storeConstructor.newInstance(getServletConfig()); } catch(final InvocationTargetException e) { throw new RuntimeException("ERROR: Class "+storeClass+" constructor throw exception", e); } catch(final InstantiationException e) { throw new RuntimeException("ERROR: Class "+storeClass+" could not be instantiated (must not be abstract or an interface)", e); } catch(final IllegalAccessException e) { throw new RuntimeException("ERROR: Class "+storeClass+" or its null-constructor could not be accessed ", e); } if (o instanceof CronjobStore) { stores.add( (CronjobStore)o ); } else { throw new RuntimeException("ERROR: Class "+storeClass+" must implement the CronjobStore-interface"); } } handlers = new ArrayList<Handler>(); int idCounter = 1; for ( final CronjobStore store: stores ) { final long storeInitialDelay = store.getInitialDelayInMilliSeconds(); for (final Job job: store.getJobs()) handlers.add(new Handler(job, idCounter++, storeInitialDelay)); } // start threads at the very end // so that errors in code above do not // leave running threads for(final Handler handler : handlers) handler.startThread(); System.out.println("CronjobManager is started. (" + System.identityHashCode(this) + ')'); } @Override public void destroy() { System.out.println("CronjobManager is terminating ... (" + System.identityHashCode(this) + ')'); for(final Handler job : handlers) { job.setActivated(false); } for(final Handler job : handlers) { job.stopThread(); } System.out.println("CronjobManager is terminated. (" + System.identityHashCode(this) + ')'); } private String getImplementationVersion() { final String iv=CronjobManager.class.getPackage().getImplementationVersion(); return iv==null ? "" : iv; } @Override protected void doRequest( final HttpServletRequest request, final HttpServletResponse response) throws IOException { final PageCop cop = PageCop.getCop(request); if("POST".equals(request.getMethod())) { cop.post(request, handlers); response.sendRedirect(cop.getAbsoluteURL(request)); } final Principal principal = request.getUserPrincipal(); final String authentication = principal!=null ? principal.getName() : null; String hostname = null; try { hostname = InetAddress.getLocalHost().getHostName(); } catch(final UnknownHostException e) { // leave hostname==null } final long now = System.currentTimeMillis(); response.setContentType("text/html; charset=utf-8"); final Out out = new Out(request, response); Page_Jspm.write(out, cop, authentication, hostname, now, new SimpleDateFormat("yyyy/MM/dd'&nbsp;'HH:mm:ss.SSS Z (z)").format(new Date(now)), handlers, getImplementationVersion(), System.identityHashCode(this)); out.sendBody(); } }
package io.measures.passage; import com.google.common.base.Joiner; import io.measures.passage.geometry.Model3D; import io.measures.passage.geometry.Point2D; import io.measures.passage.geometry.Projectable2D; import io.measures.passage.geometry.Projectable3D; import io.measures.passage.geometry.SphericalPoint; import io.measures.passage.geometry.Triangle3D; import processing.core.PApplet; import processing.core.PGraphics; import processing.core.PImage; import processing.event.KeyEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Sketch * @author Dietrich Featherston */ public class Sketch extends PApplet { protected final long startedAt = System.currentTimeMillis()/1000L; protected final String homeDir; protected final String baseDataDir; protected static final Joiner pathJoiner = Joiner.on(File.separatorChar); public final int slate = color(50); public final int gray = color(180); public final int yellow = color(255, 255, 1); public final int pink = color(255, 46, 112); public final int teal = color(85, 195, 194); public final int nak = color(0, 170, 255); public final int blue = color(49, 130, 189); public final int darkblue = color(49, 130, 189); public final int lightblue = color(222, 235, 247); public final int redorange = color(240, 59, 32); private PGraphics paperGraphics; protected boolean recordPdf = false; protected long pdfTime = 0L; private boolean saveAnimation = false; private int numAnimationFrames = -1; // save an unbounded number of frames public Sketch() { String homeDir = getParameter("PASSAGE_HOME"); String userDir = System.getProperty("user.dir"); if(homeDir == null) { homeDir = userDir; } this.homeDir = homeDir; baseDataDir = getParameter("PASSAGE_DATA") == null ? homeDir : getParameter("PASSAGE_DATA"); // ensure the snapshot directory exists new File(getSnapshotDir()).mkdirs(); // ensure the data dir exists new File(getDataDir()).mkdirs(); } public void initSize(String type) { size(getTargetWidth(), getTargetHeight(), type); } public int getTargetWidth() { return 1280; } public int getTargetHeight() { return 720; } public float getAspectRatio() { return (float)getTargetWidth() / (float)getTargetHeight(); } public void saveAnimation() { this.saveAnimation = true; } public void animationFrames(int n) { numAnimationFrames = n; } @Override public final void draw() { beforeFrame(); try { renderFrame(); } catch(Exception e) { println(e.getMessage()); } finally { afterFrame(); } } public void beforeFrame() { if(recordPdf) { beginRaw(PDF, getSnapshotPath("vector-" + pdfTime + ".pdf")); } } public void renderFrame() { println("ERROR - sketch renderFrame() not implemented"); noLoop(); } public void afterFrame() { if(recordPdf) { endRaw(); recordPdf = false; } if(saveAnimation) { saveFrame(getSnapshotPath("frames-" + startedAt + "/frame- if(numAnimationFrames > 0 && frameCount >= numAnimationFrames) { exit(); } } } public int darker(int c) { return color(round(red(c)*0.6f), round(green(c)*0.6f), round(blue(c)*0.6f)); } public int lighter(int c) { return color( constrain(round(red(c)*1.1f), 0, 255), constrain(round(green(c)*1.1f), 0, 255), constrain(round(blue(c)*1.1f), 0, 255)); } public void point(Projectable2D p) { point(p.x(), p.y()); } public void points(Iterable<? extends Projectable2D> points) { for(Projectable2D p : points) { point(p); } } public void point(Projectable3D p) { point(p.x(), p.y(), p.z()); } public void vertex(Projectable3D p) { vertex(p.x(), p.y(), p.z()); } public void vertex(Projectable2D p) { vertex(p.x(), p.y()); } public void line(Projectable3D a, Projectable3D b) { line(a.x(), a.y(), a.z(), b.x(), b.y(), b.z()); } public void line(Projectable2D a, Projectable2D b) { line(a.x(), a.y(), b.x(), b.y()); } public void renderModel(Model3D model) { beginShape(TRIANGLES); for(Triangle3D t : model.getTriangles()) { vertex(t.a()); vertex(t.b()); vertex(t.c()); } endShape(); } public void triangle(Triangle3D t) { beginShape(TRIANGLE); vertex(t.a()); vertex(t.b()); vertex(t.c()); endShape(); } public void translate(Projectable2D p) { translate(p.x(), p.y()); } public void translate(Projectable3D p) { translate(p.x(), p.y(), p.z()); } public void translateNormal(SphericalPoint p) { rotateZ(p.phi()); rotateY(p.theta()); translate(0, 0, p.r()); } public static float dist(Projectable2D p) { return dist(p.x(), p.y(), 0, 0); } public static float dist(Projectable2D a, Projectable2D b) { return dist(a.x(), a.y(), b.x(), b.y()); } public static float dist(Projectable3D a, Projectable3D b) { return dist(a.x(), a.y(), a.z(), b.x(), b.y(), b.z()); } public float noiseZ(float noiseScale, float x, float y, float z) { return noise(noiseScale*(x+10000), noiseScale*(y+10000), noiseScale*(z+10000)); } @Override public void keyPressed(KeyEvent e) { super.keyPressed(); if(key == ' ') { // snapshot raster graphics + code snapshot(); } else if(key == 'p') { // snapshot a pdf + code recordPdf = true; pdfTime = now(); snapshotCode(pdfTime); } } public long now() { return System.currentTimeMillis()/1000; } public void snapshot() { long time = now(); snapshotCode(time); snapshotFrame(time); } public void snapshotCode() { snapshotCode(startedAt); } public void snapshotCode(long time) { println("taking code snapshot"); copyFile(getSketchSourceFile(), getSnapshotPath("code-" + time + ".java")); } public void snapshotFrame() { snapshotFrame(now()); } public void snapshotFrame(long time) { println("taking raster snapshot"); saveFrame(getSnapshotPath("raster-" + time + ".jpg")); } // todo - compatibility public void copyFile(String from, String to) { try { String command = "cp " + from + " " + to; Process p = Runtime.getRuntime().exec(command); copy(p.getInputStream(), System.out); copy(p.getErrorStream(), System.err); } catch(Exception ignored) { println(ignored.getMessage()); ignored.printStackTrace(); } } public void copy(InputStream in, OutputStream out) throws IOException { while (true) { int c = in.read(); if (c == -1) break; out.write((char)c); } } public String getSketchSourceFile() { return pathJoiner.join(getSketchSourcePath(), getSketchPathComponent() + ".java"); } private String getSketchSourcePath() { return pathJoiner.join(homeDir, "src/main/java"); } public String getSketchPathComponent() { return this.getClass().getName().replace('.', File.separatorChar); } /** * @return the directory to which progress artifacts should be saved */ public String getSnapshotDir() { return pathJoiner.join(baseDataDir, getSketchPathComponent(), "snapshots"); } public String getSnapshotPath(String name) { return pathJoiner.join(getSnapshotDir(), name); } public String getDataDir() { return pathJoiner.join(baseDataDir, getSketchPathComponent(), "data"); } public String getDataPath(String name) { return pathJoiner.join(getDataDir(), name); } public String getHomeDir() { return homeDir; } public String getHomePath(String name) { return pathJoiner.join(getHomeDir(), name); } public static void fit(PImage img, int maxWidth, int maxHeight) { // oblig image resizing to fit in our space float imgratio = (float)img.width / (float)img.height; if(img.width > img.height) { img.resize(round(imgratio * maxHeight), maxHeight); } else { img.resize(maxWidth, round(maxWidth/imgratio)); } } public void fit(PImage img) { if((img.width > width) || (img.height > height)) { if(((float) img.width / (float)img.height) > ((float) width / (float) height)) { img.resize(width, 0); } else { img.resize(0, height); } } } @Override public File dataFile(String where) { File why = new File(where); if (why.isAbsolute()) return why; File sketchSpecificFile = new File(getDataPath(where)); if(sketchSpecificFile.exists()) { return sketchSpecificFile; } else { File f = new File(pathJoiner.join(baseDataDir, "data", where)); if(f.exists()) { return f; } } return why; } @Override public String getParameter(String name) { return System.getenv(name); } public void printenv() { System.out.println("sketch name: " + this.getClass().getName()); System.out.println("PASSAGE_HOME=" + homeDir); System.out.println("PASSAGE_DATA=" + baseDataDir); System.out.println("sketch-specific path = " + getSketchPathComponent()); System.out.println("sketch source = " + getSketchSourcePath()); System.out.println("sketch source file = " + getSketchSourceFile()); System.out.println("snapshot dir = " + getSnapshotDir()); } public void oldPaperBackground() { if(paperGraphics == null) { int center = color(252, 243, 211); int edge = color(245, 222, 191); PGraphics g = createGraphics(10, 10); g.beginDraw(); g.noStroke(); g.background(edge); g.fill(center); g.ellipse(g.width/2, g.height/2, g.width*0.8f, g.height*0.8f); g.filter(BLUR, 2); g.endDraw(); /* g.filter(BLUR, width/30); g.filter(BLUR, width/30); g.filter(BLUR, width/30); */ paperGraphics = g; } } }
package com.github.kmkt.util; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MjpegServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory.getLogger(MjpegServlet.class); private static final byte[] CRLF = new byte[]{0x0d, 0x0a}; private static final String CONTENT_TYPE = "multipart/x-mixed-replace"; private Set<BlockingQueue<byte[]>> queueSet = new CopyOnWriteArraySet<BlockingQueue<byte[]>>(); /** * JPEG * * <pre> * MJPEG JPEG * GET MJPEG over HTTP * pourFrame * * * </pre> * * @param frame JPEG */ public void pourFrame(byte[] frame) { for (BlockingQueue<byte[]> frameServerOfConnection : queueSet) { frameServerOfConnection.offer(frame); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.debug("doGet"); BlockingQueue<byte[]> frameServer = new SynchronousQueue<byte[]>(); try { queueSet.add(frameServer); logger.debug("queueSet size : {}", queueSet.size()); logger.info("Accept HTTP connection."); String delemeter_str = Long.toHexString(System.currentTimeMillis()); byte[] delimiter = ("--"+delemeter_str).getBytes(); byte[] content_type = "Content-Type: image/jpeg".getBytes(); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(CONTENT_TYPE+";boundary=" + delemeter_str); resp.setHeader("Connection", "Close"); OutputStream out = new BufferedOutputStream(resp.getOutputStream()); try { frameServer.clear(); int i=-1; while (true) { byte[] frame = frameServer.poll(10, TimeUnit.SECONDS); if (frame == null) continue; byte[] content_length = ("Content-Length: " + frame.length).getBytes(); i++; logger.trace("Send frame {}", i); out.write(delimiter); out.write(CRLF); out.write(content_type); out.write(CRLF); out.write(content_length); out.write(CRLF); out.write(CRLF); out.write(frame); out.write(CRLF); out.flush(); } } catch (IOException e) { // connection closed logger.info("Close HTTP connection."); } catch (InterruptedException e) { logger.info(e.getMessage(), e); } } finally { queueSet.remove(frameServer); logger.debug("queueSet size : {}", queueSet.size()); } } }
package landmaster.plustic; import java.util.*; import landmaster.plustic.api.*; import landmaster.plustic.block.*; import landmaster.plustic.proxy.*; import landmaster.plustic.config.*; import landmaster.plustic.fluids.*; import landmaster.plustic.net.*; import landmaster.plustic.util.*; import landmaster.plustic.traits.*; import net.minecraft.block.*; import net.minecraft.init.*; import net.minecraft.item.*; import net.minecraft.util.*; import net.minecraft.util.text.*; import net.minecraftforge.common.*; import net.minecraftforge.fluids.*; import net.minecraftforge.fml.common.*; import net.minecraftforge.fml.common.event.*; import net.minecraftforge.fml.common.registry.*; import net.minecraftforge.oredict.*; import net.minecraftforge.fml.common.Mod.*; import slimeknights.tconstruct.*; import slimeknights.tconstruct.library.*; import slimeknights.tconstruct.library.materials.*; import slimeknights.tconstruct.library.smeltery.*; import slimeknights.tconstruct.shared.*; import static slimeknights.tconstruct.library.materials.MaterialTypes.*; import static slimeknights.tconstruct.library.utils.HarvestLevels.*; import static slimeknights.tconstruct.tools.TinkerTraits.*; @Mod(modid = PlusTiC.MODID, name = "PlusTiC", version = PlusTiC.VERSION, dependencies = "required-after:mantle;required-after:tconstruct;after:Mekanism;after:BiomesOPlenty;after:Botania;after:advancedRocketry;after:armorplus;after:EnderIO") public class PlusTiC { public static final String MODID = "plustic"; public static final String VERSION = "3.0"; public static Config config; @Mod.Instance(PlusTiC.MODID) public static PlusTiC INSTANCE; @SidedProxy(serverSide = "landmaster.plustic.proxy.CommonProxy", clientSide = "landmaster.plustic.proxy.ClientProxy") public static CommonProxy proxy; public static Map<String,Material> materials = new HashMap<>(); public static Map<String,MaterialIntegration> materialIntegrations = new HashMap<>(); public static final BowMaterialStats justWhy = new BowMaterialStats(0.2f, 0.4f, -1f); @EventHandler public void preInit(FMLPreInitializationEvent event) { Config config = new Config(event); config.sync(); initBase(); initBoP(); initMekanism(); initBotania(); initAdvRocketry(); initArmorPlus(); initEnderIO(); Utils.integrate(materials,materialIntegrations); Utils.registerModifiers(); } private void initBase() { if (Config.base) { Material tnt = new Material("tnt", TextFormatting.RED); tnt.addTrait(Explosive.explosive); tnt.addItem(Blocks.TNT, Material.VALUE_Ingot); tnt.setRepresentativeItem(Blocks.TNT); tnt.setCraftable(true); proxy.setRenderInfo(tnt, 0xFF4F4F); TinkerRegistry.addMaterialStats(tnt, new ArrowShaftMaterialStats(0.95f, 0)); materials.put("tnt", tnt); if (TinkerIntegration.isIntegrated(TinkerFluids.aluminum)) { // alumite is back! (with some changes) Item alumiteIngot = new Item().setUnlocalizedName("alumiteingot") .setRegistryName("alumiteingot"); alumiteIngot.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(alumiteIngot); OreDictionary.registerOre("ingotAlumite", alumiteIngot); proxy.registerItemRenderer(alumiteIngot, 0, "alumiteingot"); Item alumiteNugget = new Item().setUnlocalizedName("alumitenugget") .setRegistryName("alumitenugget"); alumiteNugget.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(alumiteNugget); OreDictionary.registerOre("nuggetAlumite", alumiteNugget); proxy.registerItemRenderer(alumiteNugget, 0, "alumitenugget"); Block alumiteBlock = new MetalBlock("alumiteblock"); alumiteBlock.setCreativeTab(TinkerRegistry.tabGeneral); ItemBlock alumiteBlock_item = new ItemBlock(alumiteBlock); GameRegistry.register(alumiteBlock); GameRegistry.register(alumiteBlock_item, alumiteBlock.getRegistryName()); OreDictionary.registerOre("blockAlumite", alumiteBlock); proxy.registerItemRenderer(alumiteBlock_item, 0, "alumiteblock"); Material alumite = new Material("alumite", TextFormatting.RED); alumite.addTrait(Global.global); alumite.addItem("ingotAlumite", 1, Material.VALUE_Ingot); alumite.setCraftable(false).setCastable(true); alumite.setRepresentativeItem(alumiteIngot); proxy.setRenderInfo(alumite, 0xFFE0F1); FluidMolten alumiteFluid = Utils.fluidMetal("alumite", 0xFFE0F1); alumiteFluid.setTemperature(890); Utils.initFluidMetal(alumiteFluid); alumite.setFluid(alumiteFluid); TinkerRegistry.registerAlloy(new FluidStack(alumiteFluid, 3), new FluidStack(TinkerFluids.aluminum, 5), new FluidStack(TinkerFluids.iron, 2), new FluidStack(TinkerFluids.obsidian, 2)); TinkerRegistry.addMaterialStats(alumite, new HeadMaterialStats(700, 6.8f, 5.5f, COBALT), new HandleMaterialStats(1.10f, 70), new ExtraMaterialStats(80), new BowMaterialStats(0.65f, 1.6f, 7f)); materials.put("alumite", alumite); } } } private void initBoP() { if ((Config.bop && Loader.isModLoaded("BiomesOPlenty")) || (Config.projectRed && Loader.isModLoaded("projectred-exploration"))) { Material sapphire = new Material("sapphire",TextFormatting.BLUE); sapphire.addTrait(aquadynamic); sapphire.addItem("gemSapphire", 1, Material.VALUE_Ingot); sapphire.setCraftable(true); sapphire.setRepresentativeItem(OreDictionary.getOres("gemSapphire").get(0)); proxy.setRenderInfo(sapphire,0x0000FF); TinkerRegistry.addMaterialStats(sapphire, new HeadMaterialStats(700, 5, 6.4f, COBALT)); TinkerRegistry.addMaterialStats(sapphire, new HandleMaterialStats(1, 100)); TinkerRegistry.addMaterialStats(sapphire, new ExtraMaterialStats(120)); TinkerRegistry.addMaterialStats(sapphire, new BowMaterialStats(1,1.5f,4)); materials.put("sapphire", sapphire); Material ruby = new Material("ruby",TextFormatting.RED); ruby.addTrait(BloodyMary.bloodymary); ruby.addTrait(sharp,HEAD); ruby.addItem("gemRuby", 1, Material.VALUE_Ingot); ruby.setCraftable(true); ruby.setRepresentativeItem(OreDictionary.getOres("gemRuby").get(0)); proxy.setRenderInfo(ruby,0xFF0000); TinkerRegistry.addMaterialStats(ruby, new HeadMaterialStats(660, 4.6f, 6.4f, COBALT)); TinkerRegistry.addMaterialStats(ruby, new HandleMaterialStats(1.2f, 0)); TinkerRegistry.addMaterialStats(ruby, new ExtraMaterialStats(20)); TinkerRegistry.addMaterialStats(ruby, new BowMaterialStats(1.5f,1.4f,4)); materials.put("ruby", ruby); Material peridot = new Material("peridot",TextFormatting.GREEN); peridot.addTrait(NaturesBlessing.naturesblessing); peridot.addItem("gemPeridot", 1, Material.VALUE_Ingot); peridot.setCraftable(true); peridot.setRepresentativeItem(OreDictionary.getOres("gemPeridot").get(0)); proxy.setRenderInfo(peridot,0xBEFA5C); TinkerRegistry.addMaterialStats(peridot, new HeadMaterialStats(640, 4.0f, 6.1f, COBALT)); TinkerRegistry.addMaterialStats(peridot, new HandleMaterialStats(1.3f, -30)); TinkerRegistry.addMaterialStats(peridot, new ExtraMaterialStats(20)); TinkerRegistry.addMaterialStats(peridot, new BowMaterialStats(1.4f,1.4f,4)); materials.put("peridot", peridot); } if (Config.bop && Loader.isModLoaded("BiomesOPlenty")) { Material malachite = new Material("malachite_gem",TextFormatting.DARK_GREEN); malachite.addTrait(NaturesWrath.natureswrath); malachite.addItem("gemMalachite", 1, Material.VALUE_Ingot); malachite.setCraftable(true); Utils.setDispItem(malachite, "biomesoplenty", "gem", 5); proxy.setRenderInfo(malachite,0x007523); TinkerRegistry.addMaterialStats(malachite, new HeadMaterialStats(640, 3.0f, 6.1f, COBALT)); TinkerRegistry.addMaterialStats(malachite, new HandleMaterialStats(1.3f, -30)); TinkerRegistry.addMaterialStats(malachite, new ExtraMaterialStats(20)); TinkerRegistry.addMaterialStats(malachite, new BowMaterialStats(1.4f,1.4f,4)); materials.put("malachite", malachite); Material amber = new Material("amber",TextFormatting.GOLD); amber.addTrait(shocking); amber.addTrait(Thundering.thundering, PROJECTILE); amber.addTrait(Thundering.thundering, SHAFT); amber.addItem("gemAmber", 1, Material.VALUE_Ingot); amber.setCraftable(true); Utils.setDispItem(amber, "biomesoplenty", "gem", 7); proxy.setRenderInfo(amber,0xFFD000); TinkerRegistry.addMaterialStats(amber, new HeadMaterialStats(730, 4.6f, 5.7f, COBALT)); TinkerRegistry.addMaterialStats(amber, new HandleMaterialStats(1, 30)); TinkerRegistry.addMaterialStats(amber, new ExtraMaterialStats(100)); TinkerRegistry.addMaterialStats(amber, justWhy); TinkerRegistry.addMaterialStats(amber, new ArrowShaftMaterialStats(1, 5)); materials.put("amber", amber); Material topaz = new Material("topaz",TextFormatting.GOLD); topaz.addTrait(NaturesPower.naturespower); topaz.addItem("gemTopaz", 1, Material.VALUE_Ingot); topaz.setCraftable(true); Utils.setDispItem(topaz, "biomesoplenty", "gem", 3); proxy.setRenderInfo(topaz,0xFFFF00); TinkerRegistry.addMaterialStats(topaz, new HeadMaterialStats(690, 6, 6, COBALT)); TinkerRegistry.addMaterialStats(topaz, new HandleMaterialStats(0.8f, 70)); TinkerRegistry.addMaterialStats(topaz, new ExtraMaterialStats(65)); TinkerRegistry.addMaterialStats(topaz, new BowMaterialStats(0.4f,1.4f,7)); materials.put("topaz", topaz); Material tanzanite = new Material("tanzanite",TextFormatting.LIGHT_PURPLE); tanzanite.addTrait(freezing); tanzanite.addItem("gemTanzanite", 1, Material.VALUE_Ingot); tanzanite.setCraftable(true); Utils.setDispItem(tanzanite, "biomesoplenty", "gem", 4); proxy.setRenderInfo(tanzanite,0x6200FF); TinkerRegistry.addMaterialStats(tanzanite, new HeadMaterialStats(650, 3, 7, COBALT)); TinkerRegistry.addMaterialStats(tanzanite, new HandleMaterialStats(0.7f, 0)); TinkerRegistry.addMaterialStats(tanzanite, new ExtraMaterialStats(25)); TinkerRegistry.addMaterialStats(tanzanite, justWhy); materials.put("tanzanite", tanzanite); Material amethyst = new Material("amethyst",TextFormatting.LIGHT_PURPLE); amethyst.addTrait(Apocalypse.apocalypse); amethyst.addItem( Item.REGISTRY.getObject(new ResourceLocation("biomesoplenty", "gem")), 1, Material.VALUE_Ingot); amethyst.setCraftable(true); Utils.setDispItem(amethyst, "biomesoplenty", "gem"); proxy.setRenderInfo(amethyst,0xFF00FF); TinkerRegistry.addMaterialStats(amethyst, new HeadMaterialStats(1200, 6, 10, COBALT)); TinkerRegistry.addMaterialStats(amethyst, new HandleMaterialStats(1.6f, 100)); TinkerRegistry.addMaterialStats(amethyst, new ExtraMaterialStats(100)); TinkerRegistry.addMaterialStats(amethyst, new BowMaterialStats(0.65f, 1.7f, 6.5f)); materials.put("amethyst", amethyst); } } private void initMekanism() { if (Config.mekanism && Loader.isModLoaded("Mekanism")) { // ugly workaround for dusts not melting Item tinDust = new Item().setUnlocalizedName("tindust").setRegistryName("tindust"); tinDust.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(tinDust); OreDictionary.registerOre("dustTin", tinDust); proxy.registerItemRenderer(tinDust, 0, "tindust"); Item osmiumDust = new Item().setUnlocalizedName("osmiumdust").setRegistryName("osmiumdust"); osmiumDust.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(osmiumDust); OreDictionary.registerOre("dustOsmium", osmiumDust); proxy.registerItemRenderer(osmiumDust, 0, "osmiumdust"); Item steelDust = new Item().setUnlocalizedName("steeldust").setRegistryName("steeldust"); steelDust.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(steelDust); OreDictionary.registerOre("dustSteel", steelDust); proxy.registerItemRenderer(steelDust, 0, "steeldust"); Item bronzeNugget = new Item().setUnlocalizedName("bronzenugget").setRegistryName("bronzenugget"); bronzeNugget.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(bronzeNugget); OreDictionary.registerOre("nuggetBronze", bronzeNugget); proxy.registerItemRenderer(bronzeNugget, 0, "bronzenugget"); Item bronzeIngot = new Item().setUnlocalizedName("bronzeingot").setRegistryName("bronzeingot"); bronzeIngot.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(bronzeIngot); OreDictionary.registerOre("ingotBronze", bronzeIngot); proxy.registerItemRenderer(bronzeIngot, 0, "bronzeingot"); // ugly workaround for molten tin not registering if (OreDictionary.getOres("ingotTin").size() == 0 || TinkerRegistry.getMelting(OreDictionary.getOres("ingotTin").get(0)) == null) { MaterialIntegration tinI = new MaterialIntegration(null, TinkerFluids.tin, "Tin"); tinI.integrate(); tinI.integrateRecipes(); materialIntegrations.put("tin", tinI); } Material osmium = new Material("osmium",TextFormatting.BLUE); osmium.addTrait(dense); osmium.addTrait(established); osmium.addItem("ingotOsmium", 1, Material.VALUE_Ingot); osmium.setCraftable(false).setCastable(true); proxy.setRenderInfo(osmium,0xBFD0FF); FluidMolten osmiumFluid = Utils.fluidMetal("osmium",0xBFD0FF); osmiumFluid.setTemperature(820); Utils.initFluidMetal(osmiumFluid); osmium.setFluid(osmiumFluid); TinkerRegistry.addMaterialStats(osmium, new HeadMaterialStats(500, 6, 5.8f, DIAMOND)); TinkerRegistry.addMaterialStats(osmium, new HandleMaterialStats(1.2f, 45)); TinkerRegistry.addMaterialStats(osmium, new ExtraMaterialStats(40)); TinkerRegistry.addMaterialStats(osmium, new BowMaterialStats(0.65f, 1.3f, 5.7f)); materials.put("osmium", osmium); Material refinedObsidian = new Material("refinedObsidian",TextFormatting.LIGHT_PURPLE); refinedObsidian.addTrait(dense); refinedObsidian.addTrait(duritos); refinedObsidian.addItem("ingotRefinedObsidian", 1, Material.VALUE_Ingot); refinedObsidian.setCraftable(false).setCastable(true); proxy.setRenderInfo(refinedObsidian, 0x5D00FF); FluidMolten refinedObsidianFluid = Utils.fluidMetal("refinedObsidian", 0x5D00FF); refinedObsidianFluid.setTemperature(860); Utils.initFluidMetal(refinedObsidianFluid); refinedObsidian.setFluid(refinedObsidianFluid); TinkerRegistry.addMaterialStats(refinedObsidian, new HeadMaterialStats(2500, 7, 11, COBALT)); TinkerRegistry.addMaterialStats(refinedObsidian, new HandleMaterialStats(1.5f, -100)); TinkerRegistry.addMaterialStats(refinedObsidian, new ExtraMaterialStats(160)); TinkerRegistry.addMaterialStats(refinedObsidian, justWhy); materials.put("refinedObsidian", refinedObsidian); } } private void initBotania() { if (Config.botania && Loader.isModLoaded("Botania")) { Material terrasteel = new Material("terrasteel",TextFormatting.GREEN); terrasteel.addTrait(Mana.mana); terrasteel.addTrait(Terrafirma.terrafirma[0]); terrasteel.addTrait(Terrafirma.terrafirma[1],HEAD); terrasteel.addItem("ingotTerrasteel", 1, Material.VALUE_Ingot); terrasteel.setCraftable(false).setCastable(true); Utils.setDispItem(terrasteel, "botania", "manaResource", 4); proxy.setRenderInfo(terrasteel, 0x00FF00); FluidMolten terrasteelFluid = Utils.fluidMetal("terrasteel", 0x00FF00); terrasteelFluid.setTemperature(760); Utils.initFluidMetal(terrasteelFluid); terrasteel.setFluid(terrasteelFluid); TinkerRegistry.addMaterialStats(terrasteel, new HeadMaterialStats(1562, 9, 5, OBSIDIAN)); TinkerRegistry.addMaterialStats(terrasteel, new HandleMaterialStats(1f, 10)); TinkerRegistry.addMaterialStats(terrasteel, new ExtraMaterialStats(10)); TinkerRegistry.addMaterialStats(terrasteel, new BowMaterialStats(0.4f, 2f, 9f)); materials.put("terrasteel", terrasteel); Material elementium = new Material("elementium",TextFormatting.LIGHT_PURPLE); elementium.addTrait(Mana.mana); elementium.addTrait(Elemental.elemental,HEAD); elementium.addItem("ingotElvenElementium", 1, Material.VALUE_Ingot); elementium.setCraftable(false).setCastable(true); Utils.setDispItem(elementium, "botania", "manaResource", 7); proxy.setRenderInfo(elementium, 0xF66AFD); FluidMolten elementiumFluid = Utils.fluidMetal("elementium", 0xF66AFD); elementiumFluid.setTemperature(800); Utils.initFluidMetal(elementiumFluid); elementium.setFluid(elementiumFluid); TinkerRegistry.addMaterialStats(elementium, new HeadMaterialStats(204, 6.00f, 4.00f, DIAMOND), new HandleMaterialStats(0.85f, 60), new ExtraMaterialStats(50)); TinkerRegistry.addMaterialStats(elementium, new BowMaterialStats(0.5f, 1.5f, 7f)); materials.put("elvenElementium", elementium); Material manasteel = new Material("manasteel",TextFormatting.BLUE); manasteel.addTrait(Mana.mana); manasteel.addItem("ingotManasteel", 1, Material.VALUE_Ingot); manasteel.setCraftable(false).setCastable(true); Utils.setDispItem(manasteel, "botania", "manaResource"); proxy.setRenderInfo(manasteel, 0x54E5FF); FluidMolten manasteelFluid = Utils.fluidMetal("manasteel", 0x54E5FF); manasteelFluid.setTemperature(681); Utils.initFluidMetal(manasteelFluid); manasteel.setFluid(manasteelFluid); TinkerRegistry.addMaterialStats(manasteel, new HeadMaterialStats(540, 7.00f, 6.00f, OBSIDIAN), new HandleMaterialStats(1.25f, 150), new ExtraMaterialStats(60)); TinkerRegistry.addMaterialStats(manasteel, new BowMaterialStats(1, 1.1f, 1)); materials.put("manasteel", manasteel); } } private void initAdvRocketry() { if (Config.advancedRocketry && Loader.isModLoaded("libVulpes")) { Material iridium = new Material("iridium", TextFormatting.GRAY); iridium.addTrait(dense); iridium.addTrait(alien, HEAD); iridium.addItem("ingotIridium", 1, Material.VALUE_Ingot); iridium.setCraftable(false).setCastable(true); Utils.setDispItem(iridium, "libvulpes", "productingot", 10); proxy.setRenderInfo(iridium, 0xE5E5E5); FluidMolten iridiumFluid = Utils.fluidMetal("iridium", 0xE5E5E5); iridiumFluid.setTemperature(810); Utils.initFluidMetal(iridiumFluid); iridium.setFluid(iridiumFluid); TinkerRegistry.addMaterialStats(iridium, new HeadMaterialStats(520, 6, 5.8f, DIAMOND)); TinkerRegistry.addMaterialStats(iridium, new HandleMaterialStats(1.15f, -20)); TinkerRegistry.addMaterialStats(iridium, new ExtraMaterialStats(60)); TinkerRegistry.addMaterialStats(iridium, justWhy); materials.put("iridium", iridium); Material titanium = new Material("titanium", TextFormatting.WHITE); titanium.addTrait(Light.light); titanium.addTrait(Anticorrosion.anticorrosion, HEAD); titanium.addItem("ingotTitanium", 1, Material.VALUE_Ingot); titanium.setCraftable(false).setCastable(true); Utils.setDispItem(titanium, "libvulpes", "productingot", 7); proxy.setRenderInfo(titanium, 0xDCE1EA); FluidMolten titaniumFluid = Utils.fluidMetal("titanium", 0xDCE1EA); titaniumFluid.setTemperature(790); Utils.initFluidMetal(titaniumFluid); titanium.setFluid(titaniumFluid); TinkerRegistry.addMaterialStats(titanium, new HeadMaterialStats(560, 6, 6, OBSIDIAN)); TinkerRegistry.addMaterialStats(titanium, new HandleMaterialStats(1.4f, 0)); TinkerRegistry.addMaterialStats(titanium, new ExtraMaterialStats(40)); TinkerRegistry.addMaterialStats(titanium, new BowMaterialStats(1.15f, 1.3f, 6.6f)); TinkerRegistry.addMaterialStats(titanium, new FletchingMaterialStats(1.0f, 1.3f)); materials.put("titanium", titanium); if (Config.mekanism && Loader.isModLoaded("Mekanism")) { // osmiridium Item osmiridiumIngot = new Item().setUnlocalizedName("osmiridiumingot") .setRegistryName("osmiridiumingot"); osmiridiumIngot.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(osmiridiumIngot); OreDictionary.registerOre("ingotOsmiridium", osmiridiumIngot); proxy.registerItemRenderer(osmiridiumIngot, 0, "osmiridiumingot"); Item osmiridiumNugget = new Item().setUnlocalizedName("osmiridiumnugget") .setRegistryName("osmiridiumnugget"); osmiridiumNugget.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(osmiridiumNugget); OreDictionary.registerOre("nuggetOsmiridium", osmiridiumNugget); proxy.registerItemRenderer(osmiridiumNugget, 0, "osmiridiumnugget"); MetalBlock osmiridiumBlock = new MetalBlock("osmiridiumblock"); osmiridiumBlock.setCreativeTab(TinkerRegistry.tabGeneral); ItemBlock osmiridiumBlock_item = new ItemBlock(osmiridiumBlock); GameRegistry.register(osmiridiumBlock); GameRegistry.register(osmiridiumBlock_item, osmiridiumBlock.getRegistryName()); OreDictionary.registerOre("blockOsmiridium", osmiridiumBlock); proxy.registerItemRenderer(osmiridiumBlock_item, 0, "osmiridiumblock"); Material osmiridium = new Material("osmiridium", TextFormatting.LIGHT_PURPLE); osmiridium.addTrait(DevilsStrength.devilsstrength); osmiridium.addTrait(Anticorrosion.anticorrosion, HEAD); osmiridium.addItem("ingotOsmiridium", 1, Material.VALUE_Ingot); osmiridium.setCraftable(false).setCastable(true); osmiridium.setRepresentativeItem(osmiridiumIngot); proxy.setRenderInfo(osmiridium, 0x666DFF); FluidMolten osmiridiumFluid = Utils.fluidMetal("osmiridium", 0x666DFF); osmiridiumFluid.setTemperature(840); Utils.initFluidMetal(osmiridiumFluid); osmiridium.setFluid(osmiridiumFluid); TinkerRegistry.registerAlloy(new FluidStack(osmiridiumFluid, 2), new FluidStack(materials.get("osmium").getFluid(), 1), new FluidStack(iridiumFluid, 1)); TinkerRegistry.addMaterialStats(osmiridium, new HeadMaterialStats(1300, 6.8f, 8, COBALT)); TinkerRegistry.addMaterialStats(osmiridium, new HandleMaterialStats(1.5f, 30)); TinkerRegistry.addMaterialStats(osmiridium, new ExtraMaterialStats(80)); TinkerRegistry.addMaterialStats(osmiridium, new BowMaterialStats(0.38f, 2.05f, 10)); materials.put("osmiridium", osmiridium); } } } private void initArmorPlus() { if (Config.armorPlus && Loader.isModLoaded("armorplus")) { Material witherBone = new Material("witherbone", TextFormatting.BLACK); witherBone.addTrait(Apocalypse.apocalypse); witherBone.addItem("witherBone", 1, Material.VALUE_Ingot); witherBone.setCraftable(true); proxy.setRenderInfo(witherBone, 0x000000); TinkerRegistry.addMaterialStats(witherBone, new ArrowShaftMaterialStats(1.0f, 20)); materials.put("witherbone", witherBone); Material guardianScale = new Material("guardianscale", TextFormatting.AQUA); guardianScale.addTrait(DivineShield.divineShield, HEAD); guardianScale.addTrait(aquadynamic); guardianScale.addItem("scaleGuardian", 1, Material.VALUE_Ingot); guardianScale.setCraftable(true); proxy.setRenderInfo(guardianScale, 0x00FFFF); TinkerRegistry.addMaterialStats(guardianScale, new HeadMaterialStats(600, 6.2f, 7, COBALT)); TinkerRegistry.addMaterialStats(guardianScale, new HandleMaterialStats(0.9f, 40)); TinkerRegistry.addMaterialStats(guardianScale, new ExtraMaterialStats(80)); TinkerRegistry.addMaterialStats(guardianScale, new BowMaterialStats(0.85f, 1.2f, 5.5f)); materials.put("guardianscale", guardianScale); } } private void initEnderIO() { if (Config.enderIO && Loader.isModLoaded("EnderIO")) { Fluid coalFluid = Utils.fluidMetal("coal", 0x111111); Fluid oldCoalFluid = null; coalFluid.setTemperature(500); Utils.initFluidMetal(coalFluid); MeltingRecipe coalMelting = TinkerRegistry.getMelting(new ItemStack(Items.COAL)); int amountPerCoalOld = Material.VALUE_Ingot; if (coalMelting == null) { TinkerRegistry.registerMelting("coal", coalFluid, Material.VALUE_Ingot); TinkerRegistry.registerBasinCasting(new ItemStack(Blocks.COAL_BLOCK), null, coalFluid, Material.VALUE_Ingot*9); TinkerRegistry.registerTableCasting(new ItemStack(Items.COAL), null, coalFluid, Material.VALUE_Ingot); } else { amountPerCoalOld = coalMelting.getResult().amount; oldCoalFluid = coalMelting.getResult().getFluid(); } Material darkSteel = new Material("darksteel_plustic_enderio", TextFormatting.DARK_GRAY); darkSteel.addTrait(Portly.portly, HEAD); darkSteel.addTrait(coldblooded); darkSteel.addItem("ingotDarkSteel", 1, Material.VALUE_Ingot); darkSteel.setCraftable(false).setCastable(true); Utils.setDispItem(darkSteel, "enderio", "itemAlloy", 6); proxy.setRenderInfo(darkSteel, 0x333333); FluidMolten darkSteelFluid = Utils.fluidMetal("darksteel", 0x333333); darkSteelFluid.setTemperature(800); Utils.initFluidMetal(darkSteelFluid); darkSteel.setFluid(darkSteelFluid); TinkerRegistry.registerAlloy(new FluidStack(darkSteelFluid, 1), new FluidStack(TinkerFluids.obsidian, 2), new FluidStack(TinkerFluids.iron, 1), new FluidStack(coalFluid, 1)); if (oldCoalFluid != null) { int denom = Utils.gcd(Material.VALUE_Ingot, Material.VALUE_SearedBlock, Material.VALUE_Ingot, amountPerCoalOld); TinkerRegistry.registerAlloy(new FluidStack(darkSteelFluid, Material.VALUE_Ingot/denom), new FluidStack(TinkerFluids.obsidian, Material.VALUE_SearedBlock/denom), new FluidStack(TinkerFluids.iron, Material.VALUE_Ingot/denom), new FluidStack(oldCoalFluid, amountPerCoalOld/denom)); } TinkerRegistry.addMaterialStats(darkSteel, new HeadMaterialStats(666, 7, 4, OBSIDIAN), new HandleMaterialStats(1.05f, 40), new ExtraMaterialStats(40), new BowMaterialStats(0.38f, 2.05f, 10)); materials.put("darkSteel", darkSteel); } } @EventHandler public void init(FMLInitializationEvent event) { MinecraftForge.EVENT_BUS.register(Toggle.class); proxy.registerKeyBindings(); PacketHandler.init(); // CURSE YOU, MEKANISM AND ARMORPLUS! YOU REGISTERED THE OREDICTS IN INIT INSTEAD OF PREINIT! Utils.setDispItem(materials.get("refinedObsidian"), "mekanism", "Ingot"); Utils.setDispItem(materials.get("osmium"), "mekanism", "Ingot", 1); Utils.setDispItem(materials.get("witherbone"), "armorplus", "wither_bone"); Utils.setDispItem(materials.get("guardianscale"), "armorplus", "guardian_scale"); Item bronzeNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "bronzenugget")); Item bronzeIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "bronzeingot")); Block osmiridiumBlock = Block.REGISTRY.getObject(new ResourceLocation(MODID, "osmiridiumblock")); Item osmiridiumIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "osmiridiumingot")); Item osmiridiumNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "osmiridiumnugget")); Block alumiteBlock = Block.REGISTRY.getObject(new ResourceLocation(MODID, "alumiteblock")); Item alumiteIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "alumiteingot")); Item alumiteNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "alumitenugget")); if (bronzeNugget != null) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(bronzeIngot), "III", "III", "III", 'I', "nuggetBronze")); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(bronzeNugget, 9), "ingotBronze")); } if (osmiridiumNugget != null) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(osmiridiumBlock), "III", "III", "III", 'I', "ingotOsmiridium")); GameRegistry.addShapelessRecipe(new ItemStack(osmiridiumIngot, 9), osmiridiumBlock); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(osmiridiumIngot), "III", "III", "III", 'I', "nuggetOsmiridium")); GameRegistry.addShapelessRecipe(new ItemStack(osmiridiumNugget, 9), osmiridiumIngot); } if (alumiteNugget != null) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(alumiteBlock), "III", "III", "III", 'I', "ingotAlumite")); GameRegistry.addShapelessRecipe(new ItemStack(alumiteIngot, 9), alumiteBlock); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(alumiteIngot), "III", "III", "III", 'I', "nuggetAlumite")); GameRegistry.addShapelessRecipe(new ItemStack(alumiteNugget, 9), alumiteIngot); } } }
package com.haxademic.core.app; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.IOException; import javax.sound.midi.InvalidMidiDataException; import com.haxademic.core.audio.analysis.input.AudioInputBeads; import com.haxademic.core.audio.analysis.input.AudioInputESS; import com.haxademic.core.audio.analysis.input.AudioInputMinim; import com.haxademic.core.audio.analysis.input.AudioStreamData; import com.haxademic.core.audio.analysis.input.IAudioInput; import com.haxademic.core.constants.AppSettings; import com.haxademic.core.constants.PRenderers; import com.haxademic.core.data.store.AppStore; import com.haxademic.core.debug.DebugUtil; import com.haxademic.core.debug.DebugView; import com.haxademic.core.debug.Stats; import com.haxademic.core.draw.context.DrawUtil; import com.haxademic.core.draw.context.OpenGLUtil; import com.haxademic.core.draw.image.MovieBuffer; import com.haxademic.core.file.FileUtil; import com.haxademic.core.hardware.browser.BrowserInputState; import com.haxademic.core.hardware.keyboard.KeyboardState; import com.haxademic.core.hardware.kinect.IKinectWrapper; import com.haxademic.core.hardware.kinect.KinectWrapperV1; import com.haxademic.core.hardware.kinect.KinectWrapperV2; import com.haxademic.core.hardware.kinect.KinectWrapperV2Mac; import com.haxademic.core.hardware.midi.MidiState; import com.haxademic.core.hardware.osc.OscWrapper; import com.haxademic.core.hardware.webcam.WebCamWrapper; import com.haxademic.core.render.AnimationLoop; import com.haxademic.core.render.GifRenderer; import com.haxademic.core.render.ImageSequenceRenderer; import com.haxademic.core.render.JoonsWrapper; import com.haxademic.core.render.MIDISequenceRenderer; import com.haxademic.core.render.Renderer; import com.haxademic.core.system.AppUtil; import com.haxademic.core.system.JavaInfo; import com.haxademic.core.system.P5Properties; import com.haxademic.core.system.SecondScreenViewer; import com.haxademic.core.system.SystemUtil; import com.haxademic.core.ui.PrefsSliders; import de.voidplus.leapmotion.LeapMotion; import krister.Ess.AudioInput; import processing.core.PApplet; import processing.core.PGraphics; import processing.core.PSurface; import processing.opengl.PJOGL; import processing.video.Movie; import themidibus.MidiBus; /** * PAppletHax is a starting point for interactive visuals, giving you a unified * environment for both realtime and rendering modes. It loads several Java * libraries and wraps them up to play nicely with each other. * * @author cacheflowe * */ public class PAppletHax extends PApplet { // Simplest launch: // public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } // Fancier launch: // public static void main(String args[]) { // PAppletHax.main(P.concat(args, new String[] { "--hide-stop", "--bgcolor=000000", Thread.currentThread().getStackTrace()[1].getClassName() })); // PApplet.main(new String[] { "--hide-stop", "--bgcolor=000000", "--location=1920,0", "--display=1", ElloMotion.class.getName() }); // public static String arguments[]; // public static void main(String args[]) { // arguments = args; // PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); // app protected static PAppletHax p; // Global/static ref to PApplet - any audio-reactive object should be passed this reference, or grabbed from this static ref. public PGraphics pg; // Offscreen buffer that matches the app size public P5Properties appConfig; // Loads the project .properties file to configure several app properties externally. protected String customPropsFile = null; // Loads an app-specific project .properties file. protected String renderer; // The current rendering engine protected Robot _robot; // audio public IAudioInput audioInput; public AudioStreamData audioData = new AudioStreamData(); public PGraphics audioInputDebugBuffer; // rendering public Renderer movieRenderer; public MIDISequenceRenderer _midiRenderer; public GifRenderer _gifRenderer; public ImageSequenceRenderer imageSequenceRenderer; protected Boolean _isRendering = true; protected Boolean _isRenderingAudio = true; protected Boolean _isRenderingMidi = true; protected JoonsWrapper joons; public AnimationLoop loop = null; // input public WebCamWrapper webCamWrapper = null; public MidiState midiState = null; public MidiBus midiBus; public KeyboardState keyboardState; public IKinectWrapper kinectWrapper = null; public LeapMotion leapMotion = null; public OscWrapper oscState = null; public BrowserInputState browserInputState = null; public int lastMouseTime = 0; public boolean mouseShowing = true; // debug public int _fps; public Stats _stats; public boolean showDebug = false; public DebugView debugView; public PrefsSliders prefsSliders; public SecondScreenViewer appViewerWindow; // INIT public void settings() { P.p = p = this; P.store = AppStore.instance(); AppUtil.setFrameBackground(p,0,255,0); loadAppConfig(); overridePropsFile(); setAppIcon(); setRenderer(); setSmoothing(); setRetinaScreen(); } protected void loadAppConfig() { appConfig = new P5Properties(p); if( customPropsFile != null ) appConfig.loadPropertiesFile( customPropsFile ); customPropsFile = null; } public void setAppIcon() { String appIconFile = p.appConfig.getString(AppSettings.APP_ICON, "haxademic/images/haxademic-logo.png"); PJOGL.setIcon(FileUtil.getFile(appIconFile)); } public void setup() { if(customPropsFile != null) DebugUtil.printErr("Make sure to load custom .properties files in settings()"); setAppletProps(); checkScreenManualPosition(); if(renderer != PRenderers.PDF) { debugView = new DebugView( p ); prefsSliders = new PrefsSliders(); if(p.appConfig.getBoolean(AppSettings.SHOW_SLIDERS, false) == true) { prefsSliders.active(!prefsSliders.active()); } } _stats = new Stats( p ); } // INIT GRAPHICS protected void setRetinaScreen() { if(p.appConfig.getBoolean(AppSettings.RETINA, false) == true) { if(p.displayDensity() == 2) { p.pixelDensity(2); } else { DebugUtil.printErr("Error: Attempting to set retina drawing on a non-retina screen"); } } } protected void setSmoothing() { if(p.appConfig.getInt(AppSettings.SMOOTHING, AppSettings.SMOOTH_HIGH) == 0) { p.noSmooth(); } else { p.smooth(p.appConfig.getInt(AppSettings.SMOOTHING, AppSettings.SMOOTH_HIGH)); } } protected void setRenderer() { PJOGL.profile = 4; renderer = p.appConfig.getString(AppSettings.RENDERER, P.P3D); if(p.appConfig.getBoolean(AppSettings.SPAN_SCREENS, false) == true) { // run fullscreen across all screens p.fullScreen(renderer, P.SPAN); } else if(p.appConfig.getBoolean(AppSettings.FULLSCREEN, false) == true) { // run fullscreen - default to screen #1 unless another is specified p.fullScreen(renderer, p.appConfig.getInt(AppSettings.FULLSCREEN_SCREEN_NUMBER, 1)); } else if(p.appConfig.getBoolean(AppSettings.FILLS_SCREEN, false) == true) { // fills the screen, but not fullscreen p.size(displayWidth,displayHeight,renderer); } else { if(renderer == PRenderers.PDF) { // set headless pdf output file p.size(p.appConfig.getInt(AppSettings.WIDTH, 800),p.appConfig.getInt(AppSettings.HEIGHT, 600), renderer, p.appConfig.getString(AppSettings.PDF_RENDERER_OUTPUT_FILE, "output/output.pdf")); } else { // run normal P3D renderer p.size(p.appConfig.getInt(AppSettings.WIDTH, 800),p.appConfig.getInt(AppSettings.HEIGHT, 600), renderer); } } } protected void checkScreenManualPosition() { boolean isFullscreen = p.appConfig.getBoolean(AppSettings.FULLSCREEN, false); // check for additional screen_x params to manually place the screen if(p.appConfig.getInt("screen_x", -1) != -1) { if(isFullscreen == false) { DebugUtil.printErr("Error: Manual screen positioning requires AppSettings.FULLSCREEN = true"); return; } surface.setSize(p.appConfig.getInt(AppSettings.WIDTH, 800), p.appConfig.getInt(AppSettings.HEIGHT, 600)); surface.setLocation(p.appConfig.getInt("screen_x", 0), p.appConfig.getInt("screen_y", 0)); // location has to happen after size, to break it out of fullscreen } } // INIT OBJECTS protected void setAppletProps() { _isRendering = p.appConfig.getBoolean(AppSettings.RENDERING_MOVIE, false); if( _isRendering == true ) DebugUtil.printErr("When rendering, make sure to call super.keyPressed(); for esc key shutdown"); _isRenderingAudio = p.appConfig.getBoolean(AppSettings.RENDER_AUDIO, false); _isRenderingMidi = p.appConfig.getBoolean(AppSettings.RENDER_MIDI, false); _fps = p.appConfig.getInt(AppSettings.FPS, 60); if(p.appConfig.getInt(AppSettings.FPS, 60) != 60) frameRate(_fps); p.showDebug = p.appConfig.getBoolean(AppSettings.SHOW_DEBUG, false); } protected void initHaxademicObjects() { // create offscreen buffer pg = p.createGraphics(p.width, p.height, P.P3D); DrawUtil.setTextureRepeat(pg, true); // audio input initAudioInput(); // animation loop if(p.appConfig.getFloat(AppSettings.LOOP_FRAMES, 0) != 0) loop = new AnimationLoop(p.appConfig.getFloat(AppSettings.LOOP_FRAMES, 0)); // save single reference for other objects if( appConfig.getInt(AppSettings.WEBCAM_INDEX, -1) >= 0 ) webCamWrapper = new WebCamWrapper(appConfig.getInt(AppSettings.WEBCAM_INDEX, -1), appConfig.getBoolean(AppSettings.WEBCAM_THREADED, true)); movieRenderer = new Renderer( p, _fps, Renderer.OUTPUT_TYPE_MOVIE, p.appConfig.getString( "render_output_dir", FileUtil.getHaxademicOutputPath() ) ); if(appConfig.getBoolean(AppSettings.RENDERING_GIF, false) == true) { _gifRenderer = new GifRenderer(appConfig.getInt(AppSettings.RENDERING_GIF_FRAMERATE, 45), appConfig.getInt(AppSettings.RENDERING_GIF_QUALITY, 15)); } if(appConfig.getBoolean(AppSettings.RENDERING_IMAGE_SEQUENCE, false) == true) { imageSequenceRenderer = new ImageSequenceRenderer(); } if( p.appConfig.getBoolean( AppSettings.KINECT_V2_WIN_ACTIVE, false ) == true ) { kinectWrapper = new KinectWrapperV2( p, p.appConfig.getBoolean( "kinect_depth", true ), p.appConfig.getBoolean( "kinect_rgb", true ), p.appConfig.getBoolean( "kinect_depth_image", true ) ); } else if( p.appConfig.getBoolean( AppSettings.KINECT_V2_MAC_ACTIVE, false ) == true ) { kinectWrapper = new KinectWrapperV2Mac( p, p.appConfig.getBoolean( "kinect_depth", true ), p.appConfig.getBoolean( "kinect_rgb", true ), p.appConfig.getBoolean( "kinect_depth_image", true ) ); } else if( p.appConfig.getBoolean( AppSettings.KINECT_ACTIVE, false ) == true ) { kinectWrapper = new KinectWrapperV1( p, p.appConfig.getBoolean( "kinect_depth", true ), p.appConfig.getBoolean( "kinect_rgb", true ), p.appConfig.getBoolean( "kinect_depth_image", true ) ); } if(kinectWrapper != null) { kinectWrapper.setMirror( p.appConfig.getBoolean( "kinect_mirrored", true ) ); kinectWrapper.setFlipped( p.appConfig.getBoolean( "kinect_flipped", false ) ); } if( p.appConfig.getInt(AppSettings.MIDI_DEVICE_IN_INDEX, -1) >= 0 ) { MidiBus.list(); // List all available Midi devices on STDOUT. This will show each device's index and name. midiBus = new MidiBus( this, p.appConfig.getInt(AppSettings.MIDI_DEVICE_IN_INDEX, 0), p.appConfig.getInt(AppSettings.MIDI_DEVICE_OUT_INDEX, 0) ); } midiState = new MidiState(); keyboardState = new KeyboardState(); browserInputState = new BrowserInputState(); if( p.appConfig.getBoolean( "leap_active", false ) == true ) leapMotion = new LeapMotion(this); if( p.appConfig.getBoolean( AppSettings.OSC_ACTIVE, false ) == true ) oscState = new OscWrapper(); joons = ( p.appConfig.getBoolean(AppSettings.SUNFLOW, false ) == true ) ? new JoonsWrapper( p, width, height, ( p.appConfig.getString(AppSettings.SUNFLOW_QUALITY, "low" ) == AppSettings.SUNFLOW_QUALITY_HIGH ) ? JoonsWrapper.QUALITY_HIGH : JoonsWrapper.QUALITY_LOW, ( p.appConfig.getBoolean(AppSettings.SUNFLOW_ACTIVE, true ) == true ) ? true : false ) : null; try { _robot = new Robot(); } catch( Exception error ) { println("couldn't init Robot for screensaver disabling"); } if(p.appConfig.getBoolean(AppSettings.APP_VIEWER_WINDOW, false) == true) appViewerWindow = new SecondScreenViewer(p.g, p.appConfig.getFloat(AppSettings.APP_VIEWER_SCALE, 0.5f)); // check for always on top boolean isFullscreen = p.appConfig.getBoolean(AppSettings.FULLSCREEN, false); if(isFullscreen == true) { if(p.appConfig.getBoolean(AppSettings.ALWAYS_ON_TOP, true)) surface.setAlwaysOnTop(true); } } protected void initAudioInput() { if(appConfig.getBoolean(AppSettings.AUDIO_DEBUG, false) == true) JavaInfo.debugInfo(); if( appConfig.getBoolean(AppSettings.INIT_MINIM_AUDIO, false) == true ) { audioInput = new AudioInputMinim(); } else if( appConfig.getBoolean(AppSettings.INIT_BEADS_AUDIO, false) == true ) { audioInput = new AudioInputBeads(); } else if( appConfig.getBoolean(AppSettings.INIT_ESS_AUDIO, true) == true ) { // Default to ESS being on, unless a different audio library is selected try { audioInput = new AudioInputESS(); DebugUtil.printErr("Fix AudioInputESS amp: audioStreamData.setAmp(fft.max);"); } catch (IllegalArgumentException e) { DebugUtil.printErr("ESS Audio not initialized. Check your sound card settings."); } } // if we've initialized an audio input, let's build an audio buffer if(audioInput != null) { audioInputDebugBuffer = p.createGraphics((int)AudioStreamData.debugW, (int)AudioStreamData.debugW, PRenderers.P3D); debugView.setTexture(audioInputDebugBuffer); } } protected void initializeOn1stFrame() { if( p.frameCount == 1 ) { P.println("Using Java version: " + SystemUtil.getJavaVersion() + " and GL version: " + OpenGLUtil.getGlVersion(p.g)); initHaxademicObjects(); setupFirstFrame(); } } // OVERRIDES protected void overridePropsFile() { if( customPropsFile == null ) P.println("YOU SHOULD OVERRIDE overridePropsFile(). Using run.properties"); } protected void setupFirstFrame() { // YOU SHOULD OVERRIDE setupFirstFrame() to avoid 5000ms Processing/Java timeout in setup() } protected void drawApp() { P.println("YOU MUST OVERRIDE drawApp()"); } // GETTERS // app surface public PSurface getSurface() { return surface; } public void setAlwaysOnTop() { surface.setAlwaysOnTop(false); surface.setAlwaysOnTop(true); } // audio public float[] audioFreqs() { return audioInput.audioData().frequencies(); } public float audioFreq(int index) { return audioFreqs()[index % audioFreqs().length]; } // DRAW public void draw() { initializeOn1stFrame(); killScreensaver(); if(loop != null) loop.update(); updateAudioData(); handleRenderingStepthrough(); midiState.update(); if( kinectWrapper != null ) kinectWrapper.update(); p.pushMatrix(); if( joons != null ) joons.startFrame(); drawApp(); if( joons != null ) joons.endFrame( p.appConfig.getBoolean(AppSettings.SUNFLOW_SAVE_IMAGES, false) == true ); p.popMatrix(); renderFrame(); keyboardState.update(); browserInputState.update(); autoHideMouse(); if(oscState != null) oscState.update(); showStats(); setAppDockIconAndTitle(); if(renderer == PRenderers.PDF) finishPdfRender(); } // UPDATE OBJECTS protected void updateAudioData() { if(audioInput != null) { PGraphics audioBuffer = (showDebug == true) ? audioInputDebugBuffer : null; // only draw if debugging if(audioBuffer != null) { audioBuffer.beginDraw(); audioBuffer.background(0); } audioInput.update(audioBuffer); audioData = audioInput.audioData(); if(audioBuffer != null) audioBuffer.endDraw(); } } protected void showStats() { p.noLights(); _stats.update(); if(showDebug) debugView.draw(); prefsSliders.update(); } protected void setAppDockIconAndTitle() { if(p.frameCount == 1 && renderer != PRenderers.PDF) { AppUtil.setTitle(p, p.appConfig.getString(AppSettings.APP_NAME, "Haxademic")); AppUtil.setAppToDockIcon(p); } } // RENDERING protected void finishPdfRender() { P.println("Finished PDF render."); p.exit(); } protected void handleRenderingStepthrough() { // step through midi file if set if( _isRenderingMidi == true ) { if( p.frameCount == 1 ) { try { _midiRenderer = new MIDISequenceRenderer(p); _midiRenderer.loadMIDIFile( p.appConfig.getString(AppSettings.RENDER_MIDI_FILE, ""), p.appConfig.getFloat(AppSettings.RENDER_MIDI_BPM, 150f), _fps, p.appConfig.getFloat(AppSettings.RENDER_MIDI_OFFSET, -8f) ); } catch (InvalidMidiDataException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } // analyze & init audio if stepping through a render if( _isRendering == true ) { if( p.frameCount == 1 ) { if( _isRenderingAudio == true ) { movieRenderer.startRendererForAudio( p.appConfig.getString(AppSettings.RENDER_AUDIO_FILE, "") ); } else { movieRenderer.startRenderer(); } } // if( p.frameCount > 1 ) { // have renderer step through audio, then special call to update the single WaveformData storage object if( _isRenderingAudio == true ) { movieRenderer.analyzeAudio(); } if( _midiRenderer != null ) { boolean doneCheckingForMidi = false; boolean triggered = false; while( doneCheckingForMidi == false ) { int rendererNote = _midiRenderer.checkForCurrentFrameNoteEvents(); if( rendererNote != -1 ) { midiState.noteOn( 0, rendererNote, 100 ); triggered = true; } else { doneCheckingForMidi = true; } } // if( triggered == false && midi != null ) midi.allOff(); } } if(_gifRenderer != null && appConfig.getBoolean(AppSettings.RENDERING_GIF, false) == true) { if(appConfig.getInt(AppSettings.RENDERING_GIF_START_FRAME, 1) == p.frameCount) { _gifRenderer.startGifRender(this); } } if(imageSequenceRenderer != null && appConfig.getBoolean(AppSettings.RENDERING_IMAGE_SEQUENCE, false) == true) { if(appConfig.getInt(AppSettings.RENDERING_IMAGE_SEQUENCE_START_FRAME, 1) == p.frameCount) { imageSequenceRenderer.startImageSequenceRender();; } } } protected void renderFrame() { // gives the app 1 frame to shutdown after the movie rendering stops if( _isRendering == true ) { if(p.frameCount >= appConfig.getInt(AppSettings.RENDERING_MOVIE_START_FRAME, 1)) { movieRenderer.renderFrame(); } // check for movie rendering stop frame if(p.frameCount == appConfig.getInt(AppSettings.RENDERING_MOVIE_STOP_FRAME, 5000)) { movieRenderer.stop(); P.println("shutting down renderer"); } } // check for gifrendering stop frame if(_gifRenderer != null && appConfig.getBoolean(AppSettings.RENDERING_GIF, false) == true) { if(appConfig.getInt(AppSettings.RENDERING_GIF_START_FRAME, 1) == p.frameCount) { _gifRenderer.startGifRender(this); } DrawUtil.setColorForPImage(p); _gifRenderer.renderGifFrame(p.g); if(appConfig.getInt(AppSettings.RENDERING_GIF_STOP_FRAME, 100) == p.frameCount) { _gifRenderer.finish(); } } // check for image sequence stop frame if(imageSequenceRenderer != null && appConfig.getBoolean(AppSettings.RENDERING_IMAGE_SEQUENCE, false) == true) { if(p.frameCount >= appConfig.getInt(AppSettings.RENDERING_IMAGE_SEQUENCE_START_FRAME, 1)) { imageSequenceRenderer.renderImageFrame(p.g); } if(p.frameCount == appConfig.getInt(AppSettings.RENDERING_IMAGE_SEQUENCE_STOP_FRAME, 500)) { imageSequenceRenderer.finish(); } } } // INPUT protected void autoHideMouse() { // show mouse if(p.mouseX != p.pmouseX || p.mouseY != p.pmouseY) { lastMouseTime = p.millis(); if(p.mouseShowing == false) { p.mouseShowing = true; p.cursor(); } } // hide mouse if(p.mouseShowing == true) { if(p.millis() > lastMouseTime + 5000) { p.noCursor(); mouseShowing = false; } } } protected void killScreensaver() { // keep screensaver off - hit shift every 1000 frames if( p.frameCount % 1000 == 10 ) _robot.keyPress(KeyEvent.VK_SHIFT); if( p.frameCount % 1000 == 11 ) _robot.keyRelease(KeyEvent.VK_SHIFT); } public void keyPressed() { // disable esc key - subclass must call super.keyPressed() if( p.key == P.ESC && ( p.appConfig.getBoolean(AppSettings.DISABLE_ESC_KEY, false) == true ) ) { // || p.appConfig.getBoolean(AppSettings.RENDERING_MOVIE, false) == true ) key = 0; // renderShutdownBeforeExit(); } keyboardState.setKeyOn(p.keyCode); // special core app key commands // audio input gain if ( p.key == '.' ) { p.audioData.setGain(p.audioData.gain() + 0.05f); p.debugView.setValue("audioData.gain()", p.audioData.gain()); } if ( p.key == ',' ) { p.audioData.setGain(p.audioData.gain() - 0.05f); p.debugView.setValue("audioData.gain()", p.audioData.gain()); } // show debug & prefs sliders if (p.key == '|') p.save(FileUtil.getHaxademicOutputPath() + "_screenshots/" + SystemUtil.getTimestamp(p) + ".png"); if (p.key == '/') showDebug = !showDebug; if (p.key == '\\') prefsSliders.active(!prefsSliders.active()); } public void keyReleased() { keyboardState.setKeyOff(p.keyCode); } public float mousePercentX() { return P.map(p.mouseX, 0, p.width, 0, 1); } public float mousePercentY() { return P.map(p.mouseY, 0, p.height, 0, 1); } // SHUTDOWN public void stop() { if(p.webCamWrapper != null) p.webCamWrapper.dispose(); if( kinectWrapper != null ) { kinectWrapper.stop(); kinectWrapper = null; } if( leapMotion != null ) leapMotion.dispose(); super.stop(); } // PAPPLET LISTENERS // Movie playback public void movieEvent(Movie m) { m.read(); MovieBuffer.moviesEventFrames.put(m, p.frameCount); } // ESS audio input public void audioInputData(AudioInput theInput) { if(audioInput instanceof AudioInputESS) { ((AudioInputESS) audioInput).audioInputCallback(theInput); } } // LEAP MOTION EVENTS void leapOnInit(){ // println("Leap Motion Init"); } void leapOnConnect(){ // println("Leap Motion Connect"); } void leapOnFrame(){ // println("Leap Motion Frame"); } void leapOnDisconnect(){ // println("Leap Motion Disconnect"); } void leapOnExit(){ // println("Leap Motion Exit"); } }
package landmaster.plustic; import java.util.*; import org.apache.logging.log4j.*; import com.brandon3055.draconicevolution.DEFeatures; import landmaster.plustic.api.*; import landmaster.plustic.proxy.*; import landmaster.plustic.config.*; import landmaster.plustic.fluids.*; import landmaster.plustic.net.*; import landmaster.plustic.util.*; import landmaster.plustic.traits.*; import net.minecraft.block.*; import net.minecraft.init.*; import net.minecraft.item.*; import net.minecraft.util.*; import net.minecraft.util.text.*; import net.minecraftforge.common.*; import net.minecraftforge.fluids.*; import net.minecraftforge.fml.common.*; import net.minecraftforge.fml.common.event.*; import net.minecraftforge.fml.common.registry.*; import net.minecraftforge.oredict.*; import net.minecraftforge.fml.common.Mod.*; import slimeknights.tconstruct.*; import slimeknights.tconstruct.library.*; import slimeknights.tconstruct.library.materials.*; import slimeknights.tconstruct.shared.*; import static slimeknights.tconstruct.library.materials.MaterialTypes.*; import static slimeknights.tconstruct.library.utils.HarvestLevels.*; import static slimeknights.tconstruct.tools.TinkerTraits.*; @Mod(modid = PlusTiC.MODID, name = PlusTiC.NAME, version = PlusTiC.VERSION, dependencies = PlusTiC.DEPENDS) public class PlusTiC { public static final String MODID = "plustic"; public static final String NAME = "PlusTiC"; public static final String VERSION = "4.1.0.0"; public static final String DEPENDS = "required-after:mantle;required-after:tconstruct;after:Mekanism;after:BiomesOPlenty;after:Botania;after:advancedRocketry;after:armorplus;after:EnderIO;after:projectred-exploration;after:thermalfoundation;after:substratum;after:draconicevolution;after:landcore;after:tesla;after:baubles;after:actuallyadditions"; public static Config config; @Mod.Instance(PlusTiC.MODID) public static PlusTiC INSTANCE; @SidedProxy(serverSide = "landmaster.plustic.proxy.CommonProxy", clientSide = "landmaster.plustic.proxy.ClientProxy") public static CommonProxy proxy; public static final Logger log = LogManager.getLogger( MODID.toUpperCase(Locale.US/* to avoid problems with Turkish */)); public static final Map<String, Material> materials = new HashMap<>(); public static final Map<String, MaterialIntegration> materialIntegrations = new HashMap<>(); public static final BowMaterialStats justWhy = new BowMaterialStats(0.2f, 0.4f, -1f); @EventHandler public void preInit(FMLPreInitializationEvent event) { (config = new Config(event)).sync(); proxy.initEntities(); initBase(); initBoP(); initMekanism(); initBotania(); initAdvRocketry(); initArmorPlus(); initEnderIO(); initTF(); initDraconicEvolution(); initActAdd(); Utils.integrate(materials, materialIntegrations); Utils.registerModifiers(); } private void initBase() { if (Config.base) { Material tnt = new Material("tnt", TextFormatting.RED); tnt.addTrait(Explosive.explosive); tnt.addItem(Blocks.TNT, Material.VALUE_Ingot); tnt.setRepresentativeItem(Blocks.TNT); tnt.setCraftable(true); proxy.setRenderInfo(tnt, 0xFF4F4F); TinkerRegistry.addMaterialStats(tnt, new ArrowShaftMaterialStats(0.95f, 0)); materials.put("tnt", tnt); if (TinkerIntegration.isIntegrated(TinkerFluids.aluminum)) { // alumite is back! (with some changes) Utils.ItemMatGroup alumiteGroup = Utils.registerMatGroup("alumite"); Material alumite = new Material("alumite", TextFormatting.RED); alumite.addTrait(Global.global); alumite.addItem("ingotAlumite", 1, Material.VALUE_Ingot); alumite.setCraftable(false).setCastable(true); alumite.setRepresentativeItem(alumiteGroup.ingot); proxy.setRenderInfo(alumite, 0xFFE0F1); FluidMolten alumiteFluid = Utils.fluidMetal("alumite", 0xFFE0F1); alumiteFluid.setTemperature(890); Utils.initFluidMetal(alumiteFluid); alumite.setFluid(alumiteFluid); TinkerRegistry.registerAlloy(new FluidStack(alumiteFluid, 3), new FluidStack(TinkerFluids.aluminum, 5), new FluidStack(TinkerFluids.iron, 2), new FluidStack(TinkerFluids.obsidian, 2)); TinkerRegistry.addMaterialStats(alumite, new HeadMaterialStats(700, 6.8f, 5.5f, COBALT), new HandleMaterialStats(1.10f, 70), new ExtraMaterialStats(80), new BowMaterialStats(0.65f, 1.6f, 7f)); materials.put("alumite", alumite); } } } private void initBoP() { if ((Config.bop && Loader.isModLoaded("BiomesOPlenty")) || (Config.projectRed && Loader.isModLoaded("projectred-exploration"))) { Material sapphire = new Material("sapphire", TextFormatting.BLUE); sapphire.addTrait(aquadynamic); sapphire.addItem("gemSapphire", 1, Material.VALUE_Ingot); sapphire.setCraftable(true); // sapphire.setRepresentativeItem(OreDictionary.getOres("gemSapphire").get(0)); proxy.setRenderInfo(sapphire, 0x0000FF); TinkerRegistry.addMaterialStats(sapphire, new HeadMaterialStats(700, 5, 6.4f, COBALT)); TinkerRegistry.addMaterialStats(sapphire, new HandleMaterialStats(1, 100)); TinkerRegistry.addMaterialStats(sapphire, new ExtraMaterialStats(120)); TinkerRegistry.addMaterialStats(sapphire, new BowMaterialStats(1, 1.5f, 4)); materials.put("sapphire", sapphire); Material ruby = new Material("ruby", TextFormatting.RED); ruby.addTrait(BloodyMary.bloodymary); ruby.addTrait(sharp, HEAD); ruby.addItem("gemRuby", 1, Material.VALUE_Ingot); ruby.setCraftable(true); // ruby.setRepresentativeItem(OreDictionary.getOres("gemRuby").get(0)); proxy.setRenderInfo(ruby, 0xFF0000); TinkerRegistry.addMaterialStats(ruby, new HeadMaterialStats(660, 4.6f, 6.4f, COBALT)); TinkerRegistry.addMaterialStats(ruby, new HandleMaterialStats(1.2f, 0)); TinkerRegistry.addMaterialStats(ruby, new ExtraMaterialStats(20)); TinkerRegistry.addMaterialStats(ruby, new BowMaterialStats(1.5f, 1.4f, 4)); materials.put("ruby", ruby); Material peridot = new Material("peridot", TextFormatting.GREEN); peridot.addTrait(NaturesBlessing.naturesblessing); peridot.addItem("gemPeridot", 1, Material.VALUE_Ingot); peridot.setCraftable(true); // peridot.setRepresentativeItem(OreDictionary.getOres("gemPeridot").get(0)); proxy.setRenderInfo(peridot, 0xBEFA5C); TinkerRegistry.addMaterialStats(peridot, new HeadMaterialStats(640, 4.0f, 6.1f, COBALT)); TinkerRegistry.addMaterialStats(peridot, new HandleMaterialStats(1.3f, -30)); TinkerRegistry.addMaterialStats(peridot, new ExtraMaterialStats(20)); TinkerRegistry.addMaterialStats(peridot, new BowMaterialStats(1.4f, 1.4f, 4)); materials.put("peridot", peridot); } if (Config.bop && Loader.isModLoaded("BiomesOPlenty")) { Material malachite = new Material("malachite_gem", TextFormatting.DARK_GREEN); malachite.addTrait(NaturesWrath.natureswrath); malachite.addItem("gemMalachite", 1, Material.VALUE_Ingot); malachite.setCraftable(true); Utils.setDispItem(malachite, "biomesoplenty", "gem", 5); proxy.setRenderInfo(malachite, 0x007523); TinkerRegistry.addMaterialStats(malachite, new HeadMaterialStats(640, 3.0f, 6.1f, COBALT)); TinkerRegistry.addMaterialStats(malachite, new HandleMaterialStats(1.3f, -30)); TinkerRegistry.addMaterialStats(malachite, new ExtraMaterialStats(20)); TinkerRegistry.addMaterialStats(malachite, new BowMaterialStats(1.4f, 1.4f, 4)); materials.put("malachite", malachite); Material amber = new Material("amber", TextFormatting.GOLD); amber.addTrait(shocking); amber.addTrait(Thundering.thundering, PROJECTILE); amber.addTrait(Thundering.thundering, SHAFT); amber.addItem("gemAmber", 1, Material.VALUE_Ingot); amber.setCraftable(true); Utils.setDispItem(amber, "biomesoplenty", "gem", 7); proxy.setRenderInfo(amber, 0xFFD000); TinkerRegistry.addMaterialStats(amber, new HeadMaterialStats(730, 4.6f, 5.7f, COBALT)); TinkerRegistry.addMaterialStats(amber, new HandleMaterialStats(1, 30)); TinkerRegistry.addMaterialStats(amber, new ExtraMaterialStats(100)); TinkerRegistry.addMaterialStats(amber, justWhy); TinkerRegistry.addMaterialStats(amber, new ArrowShaftMaterialStats(1, 5)); materials.put("amber", amber); Material topaz = new Material("topaz", TextFormatting.GOLD); topaz.addTrait(NaturesPower.naturespower); topaz.addItem("gemTopaz", 1, Material.VALUE_Ingot); topaz.setCraftable(true); Utils.setDispItem(topaz, "biomesoplenty", "gem", 3); proxy.setRenderInfo(topaz, 0xFFFF00); TinkerRegistry.addMaterialStats(topaz, new HeadMaterialStats(690, 6, 6, COBALT)); TinkerRegistry.addMaterialStats(topaz, new HandleMaterialStats(0.8f, 70)); TinkerRegistry.addMaterialStats(topaz, new ExtraMaterialStats(65)); TinkerRegistry.addMaterialStats(topaz, new BowMaterialStats(0.4f, 1.4f, 7)); materials.put("topaz", topaz); Material tanzanite = new Material("tanzanite", TextFormatting.LIGHT_PURPLE); tanzanite.addTrait(freezing); tanzanite.addItem("gemTanzanite", 1, Material.VALUE_Ingot); tanzanite.setCraftable(true); Utils.setDispItem(tanzanite, "biomesoplenty", "gem", 4); proxy.setRenderInfo(tanzanite, 0x6200FF); TinkerRegistry.addMaterialStats(tanzanite, new HeadMaterialStats(650, 3, 7, COBALT)); TinkerRegistry.addMaterialStats(tanzanite, new HandleMaterialStats(0.7f, 0)); TinkerRegistry.addMaterialStats(tanzanite, new ExtraMaterialStats(25)); TinkerRegistry.addMaterialStats(tanzanite, justWhy); materials.put("tanzanite", tanzanite); Material amethyst = new Material("amethyst", TextFormatting.LIGHT_PURPLE); amethyst.addTrait(Apocalypse.apocalypse); amethyst.addItem(Item.REGISTRY.getObject(new ResourceLocation("biomesoplenty", "gem")), 1, Material.VALUE_Ingot); amethyst.setCraftable(true); Utils.setDispItem(amethyst, "biomesoplenty", "gem"); proxy.setRenderInfo(amethyst, 0xFF00FF); TinkerRegistry.addMaterialStats(amethyst, new HeadMaterialStats(1200, 6, 10, COBALT)); TinkerRegistry.addMaterialStats(amethyst, new HandleMaterialStats(1.6f, 100)); TinkerRegistry.addMaterialStats(amethyst, new ExtraMaterialStats(100)); TinkerRegistry.addMaterialStats(amethyst, new BowMaterialStats(0.65f, 1.7f, 6.5f)); materials.put("amethyst", amethyst); } } private void initMekanism() { if (Config.mekanism && Loader.isModLoaded("Mekanism")) { // ugly workaround for dusts not melting Item tinDust = new Item().setUnlocalizedName("tindust").setRegistryName("tindust"); tinDust.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(tinDust); OreDictionary.registerOre("dustTin", tinDust); proxy.registerItemRenderer(tinDust, 0, "tindust"); Item osmiumDust = new Item().setUnlocalizedName("osmiumdust").setRegistryName("osmiumdust"); osmiumDust.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(osmiumDust); OreDictionary.registerOre("dustOsmium", osmiumDust); proxy.registerItemRenderer(osmiumDust, 0, "osmiumdust"); Item steelDust = new Item().setUnlocalizedName("steeldust").setRegistryName("steeldust"); steelDust.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(steelDust); OreDictionary.registerOre("dustSteel", steelDust); proxy.registerItemRenderer(steelDust, 0, "steeldust"); Item bronzeNugget = new Item().setUnlocalizedName("bronzenugget").setRegistryName("bronzenugget"); bronzeNugget.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(bronzeNugget); OreDictionary.registerOre("nuggetBronze", bronzeNugget); proxy.registerItemRenderer(bronzeNugget, 0, "bronzenugget"); Item bronzeIngot = new Item().setUnlocalizedName("bronzeingot").setRegistryName("bronzeingot"); bronzeIngot.setCreativeTab(TinkerRegistry.tabGeneral); GameRegistry.register(bronzeIngot); OreDictionary.registerOre("ingotBronze", bronzeIngot); proxy.registerItemRenderer(bronzeIngot, 0, "bronzeingot"); // ugly workaround for molten tin not registering if (OreDictionary.getOres("ingotTin").size() == 0 || TinkerRegistry.getMelting(OreDictionary.getOres("ingotTin").get(0)) == null) { MaterialIntegration tinI = new MaterialIntegration(null, TinkerFluids.tin, "Tin"); tinI.integrate(); tinI.integrateRecipes(); materialIntegrations.put("tin", tinI); } Material osmium = new Material("osmium", TextFormatting.BLUE); osmium.addTrait(dense); osmium.addTrait(established); osmium.addItem("ingotOsmium", 1, Material.VALUE_Ingot); osmium.setCraftable(false).setCastable(true); proxy.setRenderInfo(osmium, 0xBFD0FF); FluidMolten osmiumFluid = Utils.fluidMetal("osmium", 0xBFD0FF); osmiumFluid.setTemperature(820); Utils.initFluidMetal(osmiumFluid); osmium.setFluid(osmiumFluid); TinkerRegistry.addMaterialStats(osmium, new HeadMaterialStats(500, 6, 5.8f, DIAMOND)); TinkerRegistry.addMaterialStats(osmium, new HandleMaterialStats(1.2f, 45)); TinkerRegistry.addMaterialStats(osmium, new ExtraMaterialStats(40)); TinkerRegistry.addMaterialStats(osmium, new BowMaterialStats(0.65f, 1.3f, 5.7f)); materials.put("osmium", osmium); Material refinedObsidian = new Material("refinedObsidian", TextFormatting.LIGHT_PURPLE); refinedObsidian.addTrait(dense); refinedObsidian.addTrait(duritos); refinedObsidian.addItem("ingotRefinedObsidian", 1, Material.VALUE_Ingot); refinedObsidian.setCraftable(false).setCastable(true); proxy.setRenderInfo(refinedObsidian, 0x5D00FF); FluidMolten refinedObsidianFluid = Utils.fluidMetal("refinedObsidian", 0x5D00FF); refinedObsidianFluid.setTemperature(860); Utils.initFluidMetal(refinedObsidianFluid); refinedObsidian.setFluid(refinedObsidianFluid); TinkerRegistry.addMaterialStats(refinedObsidian, new HeadMaterialStats(2500, 7, 11, COBALT)); TinkerRegistry.addMaterialStats(refinedObsidian, new HandleMaterialStats(1.5f, -100)); TinkerRegistry.addMaterialStats(refinedObsidian, new ExtraMaterialStats(160)); TinkerRegistry.addMaterialStats(refinedObsidian, justWhy); materials.put("refinedObsidian", refinedObsidian); } } private void initBotania() { if (Config.botania && Loader.isModLoaded("Botania")) { Material terrasteel = new Material("terrasteel", TextFormatting.GREEN); terrasteel.addTrait(Mana.mana); terrasteel.addTrait(Terrafirma.terrafirma.get(0)); terrasteel.addTrait(Mana.mana, HEAD); terrasteel.addTrait(Terrafirma.terrafirma.get(1), HEAD); terrasteel.addItem("ingotTerrasteel", 1, Material.VALUE_Ingot); terrasteel.setCraftable(false).setCastable(true); Utils.setDispItem(terrasteel, "botania", "manaResource", 4); proxy.setRenderInfo(terrasteel, 0x00FF00); FluidMolten terrasteelFluid = Utils.fluidMetal("terrasteel", 0x00FF00); terrasteelFluid.setTemperature(760); Utils.initFluidMetal(terrasteelFluid); terrasteel.setFluid(terrasteelFluid); TinkerRegistry.addMaterialStats(terrasteel, new HeadMaterialStats(1562, 9, 6.5f, COBALT)); TinkerRegistry.addMaterialStats(terrasteel, new HandleMaterialStats(1.4f, 10)); TinkerRegistry.addMaterialStats(terrasteel, new ExtraMaterialStats(10)); TinkerRegistry.addMaterialStats(terrasteel, new BowMaterialStats(0.55f, 2f, 11f)); materials.put("terrasteel", terrasteel); Material elementium = new Material("elementium", TextFormatting.LIGHT_PURPLE); elementium.addTrait(Mana.mana); elementium.addTrait(Mana.mana, HEAD); elementium.addTrait(Elemental.elemental, HEAD); elementium.addItem("ingotElvenElementium", 1, Material.VALUE_Ingot); elementium.setCraftable(false).setCastable(true); Utils.setDispItem(elementium, "botania", "manaResource", 7); proxy.setRenderInfo(elementium, 0xF66AFD); FluidMolten elementiumFluid = Utils.fluidMetal("elementium", 0xF66AFD); elementiumFluid.setTemperature(800); Utils.initFluidMetal(elementiumFluid); elementium.setFluid(elementiumFluid); TinkerRegistry.addMaterialStats(elementium, new HeadMaterialStats(540, 7.00f, 6.00f, OBSIDIAN), new HandleMaterialStats(1.25f, 150), new ExtraMaterialStats(60)); TinkerRegistry.addMaterialStats(elementium, new BowMaterialStats(0.8f, 1.5f, 7.5f)); materials.put("elvenElementium", elementium); Material manasteel = new Material("manasteel", TextFormatting.BLUE); manasteel.addTrait(Mana.mana); manasteel.addItem("ingotManasteel", 1, Material.VALUE_Ingot); manasteel.setCraftable(false).setCastable(true); Utils.setDispItem(manasteel, "botania", "manaResource"); proxy.setRenderInfo(manasteel, 0x54E5FF); FluidMolten manasteelFluid = Utils.fluidMetal("manasteel", 0x54E5FF); manasteelFluid.setTemperature(681); Utils.initFluidMetal(manasteelFluid); manasteel.setFluid(manasteelFluid); TinkerRegistry.addMaterialStats(manasteel, new HeadMaterialStats(540, 7.00f, 6.00f, OBSIDIAN), new HandleMaterialStats(1.25f, 150), new ExtraMaterialStats(60)); TinkerRegistry.addMaterialStats(manasteel, new BowMaterialStats(1, 1.1f, 1)); materials.put("manasteel", manasteel); Material livingwood = new Material("livingwood_plustic", TextFormatting.DARK_GREEN); livingwood.addTrait(Botanical.botanical.get(1), HEAD); livingwood.addTrait(ecological, HEAD); livingwood.addTrait(Botanical.botanical.get(0)); livingwood.addTrait(ecological); livingwood.addItem("livingwood", 1, Material.VALUE_Ingot); livingwood.setCraftable(true); Utils.setDispItem(livingwood, "livingwood"); proxy.setRenderInfo(livingwood, 0x560018); TinkerRegistry.addMaterialStats(livingwood, new HeadMaterialStats(50, 5.1f, 2.8f, IRON), new HandleMaterialStats(1.15f, 20), new ExtraMaterialStats(20), new BowMaterialStats(1.1f, 1.1f, 1.8f), new ArrowShaftMaterialStats(1f, 6)); materials.put("livingwood", livingwood); // MIRION ALLOY Utils.ItemMatGroup mirionGroup = Utils.registerMatGroup("mirion"); Material mirion = new Material("mirion", TextFormatting.YELLOW); mirion.addTrait(Mirabile.mirabile, HEAD); mirion.addTrait(Mana.mana); mirion.addItem("ingotMirion", 1, Material.VALUE_Ingot); mirion.setCraftable(false).setCastable(true); mirion.setRepresentativeItem(mirionGroup.ingot); proxy.setRenderInfo(mirion, 0xDDFF00); FluidMolten mirionFluid = Utils.fluidMetal("mirion", 0xDDFF00); mirionFluid.setTemperature(777); Utils.initFluidMetal(mirionFluid); mirion.setFluid(mirionFluid); TinkerRegistry.registerAlloy(new FluidStack(mirionFluid, 4 * 18), new FluidStack(terrasteelFluid, 18), new FluidStack(manasteelFluid, 18), new FluidStack(elementiumFluid, 18), new FluidStack(TinkerFluids.cobalt, 18), new FluidStack(TinkerFluids.glass, 125)); TinkerRegistry.addMaterialStats(mirion, new HeadMaterialStats(1919, 9, 9, 5)); TinkerRegistry.addMaterialStats(mirion, new HandleMaterialStats(1.1f, 40)); TinkerRegistry.addMaterialStats(mirion, new ExtraMaterialStats(90)); TinkerRegistry.addMaterialStats(mirion, new BowMaterialStats(1.35f, 1.5f, 5.5f)); materials.put("mirion", mirion); } } private void initAdvRocketry() { if (Config.advancedRocketry && Loader.isModLoaded("libVulpes")) { Material iridium = new Material("iridium", TextFormatting.GRAY); iridium.addTrait(dense); iridium.addTrait(alien, HEAD); iridium.addItem("ingotIridium", 1, Material.VALUE_Ingot); iridium.setCraftable(false).setCastable(true); Utils.setDispItem(iridium, "libvulpes", "productingot", 10); proxy.setRenderInfo(iridium, 0xE5E5E5); FluidMolten iridiumFluid = Utils.fluidMetal("iridium", 0xE5E5E5); iridiumFluid.setTemperature(810); Utils.initFluidMetal(iridiumFluid); iridium.setFluid(iridiumFluid); TinkerRegistry.addMaterialStats(iridium, new HeadMaterialStats(520, 6, 5.8f, DIAMOND)); TinkerRegistry.addMaterialStats(iridium, new HandleMaterialStats(1.15f, -20)); TinkerRegistry.addMaterialStats(iridium, new ExtraMaterialStats(60)); TinkerRegistry.addMaterialStats(iridium, justWhy); materials.put("iridium", iridium); Material titanium = new Material("titanium", TextFormatting.WHITE); titanium.addTrait(Light.light); titanium.addTrait(Anticorrosion.anticorrosion, HEAD); titanium.addItem("ingotTitanium", 1, Material.VALUE_Ingot); titanium.setCraftable(false).setCastable(true); Utils.setDispItem(titanium, "libvulpes", "productingot", 7); proxy.setRenderInfo(titanium, 0xDCE1EA); FluidMolten titaniumFluid = Utils.fluidMetal("titanium", 0xDCE1EA); titaniumFluid.setTemperature(790); Utils.initFluidMetal(titaniumFluid); titanium.setFluid(titaniumFluid); TinkerRegistry.addMaterialStats(titanium, new HeadMaterialStats(560, 6, 6, OBSIDIAN)); TinkerRegistry.addMaterialStats(titanium, new HandleMaterialStats(1.4f, 0)); TinkerRegistry.addMaterialStats(titanium, new ExtraMaterialStats(40)); TinkerRegistry.addMaterialStats(titanium, new BowMaterialStats(1.15f, 1.3f, 6.6f)); TinkerRegistry.addMaterialStats(titanium, new FletchingMaterialStats(1.0f, 1.3f)); materials.put("titanium", titanium); if (Config.mekanism && Loader.isModLoaded("Mekanism")) { // osmiridium Utils.ItemMatGroup osmiridiumGroup = Utils.registerMatGroup("osmiridium"); Material osmiridium = new Material("osmiridium", TextFormatting.LIGHT_PURPLE); osmiridium.addTrait(DevilsStrength.devilsstrength); osmiridium.addTrait(Anticorrosion.anticorrosion, HEAD); osmiridium.addItem("ingotOsmiridium", 1, Material.VALUE_Ingot); osmiridium.setCraftable(false).setCastable(true); osmiridium.setRepresentativeItem(osmiridiumGroup.ingot); proxy.setRenderInfo(osmiridium, 0x666DFF); FluidMolten osmiridiumFluid = Utils.fluidMetal("osmiridium", 0x666DFF); osmiridiumFluid.setTemperature(840); Utils.initFluidMetal(osmiridiumFluid); osmiridium.setFluid(osmiridiumFluid); TinkerRegistry.registerAlloy(new FluidStack(osmiridiumFluid, 2), new FluidStack(materials.get("osmium").getFluid(), 1), new FluidStack(iridiumFluid, 1)); TinkerRegistry.addMaterialStats(osmiridium, new HeadMaterialStats(1300, 6.8f, 8, COBALT)); TinkerRegistry.addMaterialStats(osmiridium, new HandleMaterialStats(1.5f, 30)); TinkerRegistry.addMaterialStats(osmiridium, new ExtraMaterialStats(80)); TinkerRegistry.addMaterialStats(osmiridium, new BowMaterialStats(0.38f, 2.05f, 10)); materials.put("osmiridium", osmiridium); } } } private void initArmorPlus() { if (Config.armorPlus && Loader.isModLoaded("armorplus")) { Material witherBone = new Material("witherbone", TextFormatting.BLACK); witherBone.addTrait(Apocalypse.apocalypse); witherBone.addItem("witherBone", 1, Material.VALUE_Ingot); witherBone.setCraftable(true); proxy.setRenderInfo(witherBone, 0x000000); TinkerRegistry.addMaterialStats(witherBone, new ArrowShaftMaterialStats(1.0f, 20)); materials.put("witherbone", witherBone); Material guardianScale = new Material("guardianscale", TextFormatting.AQUA); guardianScale.addTrait(DivineShield.divineShield, HEAD); guardianScale.addTrait(aquadynamic); guardianScale.addItem("scaleGuardian", 1, Material.VALUE_Ingot); guardianScale.setCraftable(true); proxy.setRenderInfo(guardianScale, 0x00FFFF); TinkerRegistry.addMaterialStats(guardianScale, new HeadMaterialStats(600, 6.2f, 7, COBALT)); TinkerRegistry.addMaterialStats(guardianScale, new HandleMaterialStats(0.9f, 40)); TinkerRegistry.addMaterialStats(guardianScale, new ExtraMaterialStats(80)); TinkerRegistry.addMaterialStats(guardianScale, new BowMaterialStats(0.85f, 1.2f, 5.5f)); materials.put("guardianscale", guardianScale); } } private void initEnderIO() { if (Config.enderIO && Loader.isModLoaded("EnderIO")) { Fluid coalFluid = Utils.fluidMetal("coal", 0x111111); coalFluid.setTemperature(500); Utils.initFluidMetal(coalFluid); TinkerRegistry.registerMelting("coal", coalFluid, 100); TinkerRegistry.registerBasinCasting(new ItemStack(Blocks.COAL_BLOCK), null, coalFluid, 900); TinkerRegistry.registerTableCasting(new ItemStack(Items.COAL), null, coalFluid, 100); Material darkSteel = new Material("darksteel_plustic_enderio", TextFormatting.DARK_GRAY); darkSteel.addTrait(Portly.portly, HEAD); darkSteel.addTrait(coldblooded); darkSteel.addItem("ingotDarkSteel", 1, Material.VALUE_Ingot); darkSteel.setCraftable(false).setCastable(true); Utils.setDispItem(darkSteel, "enderio", "itemAlloy", 6); proxy.setRenderInfo(darkSteel, 0x333333); Fluid darkSteelFluid = FluidRegistry.getFluid("darksteel"); darkSteel.setFluid(darkSteelFluid); TinkerRegistry.registerAlloy(new FluidStack(darkSteelFluid, 36), new FluidStack(TinkerFluids.obsidian, 72), new FluidStack(TinkerFluids.iron, 36), new FluidStack(coalFluid, 25)); TinkerRegistry.addMaterialStats(darkSteel, new HeadMaterialStats(666, 7, 4, OBSIDIAN), new HandleMaterialStats(1.05f, 40), new ExtraMaterialStats(40), new BowMaterialStats(0.38f, 2.05f, 10)); materials.put("darkSteel", darkSteel); } } private void initTF() { if (Config.thermalFoundation && (Loader.isModLoaded("thermalfoundation") || Loader.isModLoaded("substratum"))) { Material signalum = new Material("signalum_plustic", TextFormatting.RED); signalum.addTrait(BloodyMary.bloodymary); signalum.addItem("ingotSignalum", 1, Material.VALUE_Ingot); signalum.setCraftable(false).setCastable(true); Utils.setDispItem(signalum, "ingotSignalum"); proxy.setRenderInfo(signalum, 0xD84100); FluidMolten signalumFluid = Utils.fluidMetal("signalum", 0xD84100); signalumFluid.setTemperature(930); Utils.initFluidMetal(signalumFluid); signalum.setFluid(signalumFluid); TinkerRegistry.registerAlloy(new FluidStack(signalumFluid, 72), new FluidStack(TinkerFluids.copper, 54), new FluidStack(TinkerFluids.silver, 18), new FluidStack(FluidRegistry.getFluid("redstone"), 125)); TinkerRegistry.addMaterialStats(signalum, new HeadMaterialStats(690, 7.5f, 5.2f, OBSIDIAN), new HandleMaterialStats(1.2f, 0), new ExtraMaterialStats(55), new BowMaterialStats(1.2f, 1.6f, 4.4f)); materials.put("signalum", signalum); Material platinum = new Material("platinum_plustic", TextFormatting.BLUE); platinum.addTrait(Global.global, HEAD); platinum.addTrait(Heavy.heavy); platinum.addTrait(Anticorrosion.anticorrosion); platinum.addItem("ingotPlatinum", 1, Material.VALUE_Ingot); platinum.setCraftable(false).setCastable(true); Utils.setDispItem(platinum, "ingotPlatinum"); proxy.setRenderInfo(platinum, 0xB7E7FF); FluidMolten platinumFluid = Utils.fluidMetal("platinum", 0xB7E7FF); platinumFluid.setTemperature(680); Utils.initFluidMetal(platinumFluid); platinum.setFluid(platinumFluid); TinkerRegistry.addMaterialStats(platinum, new HeadMaterialStats(720, 8, 6, COBALT), new HandleMaterialStats(1.05f, -5), new ExtraMaterialStats(60), new BowMaterialStats(0.85f, 1.8f, 8)); materials.put("platinum", platinum); Material enderium = new Material("enderium_plustic", TextFormatting.DARK_GREEN); enderium.addTrait(Portly.portly, HEAD); enderium.addTrait(Global.global); enderium.addTrait(enderference); enderium.addTrait(endspeed, PROJECTILE); enderium.addTrait(endspeed, SHAFT); enderium.addItem("ingotEnderium", 1, Material.VALUE_Ingot); enderium.setCraftable(false).setCastable(true); Utils.setDispItem(enderium, "ingotEnderium"); proxy.setRenderInfo(enderium, 0x007068); FluidMolten enderiumFluid = Utils.fluidMetal("enderium", 0x007068); enderiumFluid.setTemperature(970); Utils.initFluidMetal(enderiumFluid); enderium.setFluid(enderiumFluid); TinkerRegistry.registerAlloy(new FluidStack(enderiumFluid, 144), new FluidStack(TinkerFluids.tin, 72), new FluidStack(TinkerFluids.silver, 36), new FluidStack(platinumFluid, 36), new FluidStack(FluidRegistry.getFluid("ender"), 250)); TinkerRegistry.addMaterialStats(enderium, new HeadMaterialStats(800, 7.5f, 7, COBALT), new HandleMaterialStats(1.05f, -5), new ExtraMaterialStats(65), new BowMaterialStats(0.9f, 1.9f, 8), new ArrowShaftMaterialStats(1, 12)); materials.put("enderium", enderium); Material nickel = new Material("nickel", TextFormatting.YELLOW); nickel.addTrait(NickOfTime.nickOfTime, HEAD); nickel.addTrait(magnetic); nickel.addItem("ingotNickel", 1, Material.VALUE_Ingot); nickel.setCraftable(false).setCastable(true); Utils.setDispItem(nickel, "ingotNickel"); proxy.setRenderInfo(nickel, 0xFFF98E); nickel.setFluid(TinkerFluids.nickel); TinkerRegistry.addMaterialStats(nickel, new HeadMaterialStats(460, 6, 4.5f, OBSIDIAN), new HandleMaterialStats(1, -5), new ExtraMaterialStats(70), justWhy, new FletchingMaterialStats(0.95f, 1.05f)); materials.put("nickel", nickel); } } private void initDraconicEvolution() { if (Config.draconicEvolution && Loader.isModLoaded("draconicevolution")) { Material wyvern = new Material("wyvern_plustic", TextFormatting.DARK_PURPLE); wyvern.addTrait(BrownMagic.brownmagic, HEAD); wyvern.addTrait(BlindBandit.blindbandit, HEAD); wyvern.addTrait(Portly.portly); wyvern.addItem(DEFeatures.wyvernCore, 1, Material.VALUE_Ingot); wyvern.setCraftable(true); wyvern.setRepresentativeItem(DEFeatures.wyvernCore); proxy.setRenderInfo(wyvern, 0x7F00FF); TinkerRegistry.addMaterialStats(wyvern, new HeadMaterialStats(2000, 8, 15, 8)); TinkerRegistry.addMaterialStats(wyvern, new HandleMaterialStats(1.6f, 130)); TinkerRegistry.addMaterialStats(wyvern, new ExtraMaterialStats(240)); TinkerRegistry.addMaterialStats(wyvern, new BowMaterialStats(1.6f, 2, 11)); materials.put("wyvern_core", wyvern); Material awakened = new Material("awakened_plustic", TextFormatting.GOLD); awakened.addTrait(RudeAwakening.rudeawakening, HEAD); awakened.addTrait(BrownMagic.brownmagic, HEAD); awakened.addTrait(BlindBandit.blindbandit); awakened.addTrait(Apocalypse.apocalypse); awakened.addTrait(Global.global); awakened.addItem(DEFeatures.awakenedCore, 1, Material.VALUE_Ingot); awakened.setCraftable(true); awakened.setRepresentativeItem(DEFeatures.awakenedCore); proxy.setRenderInfo(awakened, 0xFFB200); TinkerRegistry.addMaterialStats(awakened, new HeadMaterialStats(5000, 9, 35, 10)); TinkerRegistry.addMaterialStats(awakened, new HandleMaterialStats(1.8f, 500)); TinkerRegistry.addMaterialStats(awakened, new ExtraMaterialStats(500)); TinkerRegistry.addMaterialStats(awakened, new BowMaterialStats(1.9f, 2.8f, 20)); materials.put("awakened_core", awakened); } } private void initActAdd() { if (Config.actuallyAdditions && Loader.isModLoaded("actuallyadditions")) { Material blackQuartz = new Material("blackquartz_plustic", TextFormatting.BLACK); blackQuartz.addTrait(DevilsStrength.devilsstrength); blackQuartz.addTrait(crude2); blackQuartz.addItem("gemQuartzBlack", 1, Material.VALUE_Ingot); blackQuartz.setCraftable(true); proxy.setRenderInfo(blackQuartz, 0x000000); TinkerRegistry.addMaterialStats(blackQuartz, new HeadMaterialStats(380, 6, 4.5f, DIAMOND), new HandleMaterialStats(0.8f, 0), new ExtraMaterialStats(50), justWhy); materials.put("blackquartz", blackQuartz); } } @EventHandler public void init(FMLInitializationEvent event) { registerAPIHandlers(); proxy.registerKeyBindings(); PacketHandler.init(); // CURSE YOU, MEKANISM AND ARMORPLUS! YOU REGISTERED THE OREDICTS IN // INIT INSTEAD OF PREINIT! Utils.setDispItem(materials.get("refinedObsidian"), "mekanism", "Ingot"); Utils.setDispItem(materials.get("osmium"), "mekanism", "Ingot", 1); Utils.setDispItem(materials.get("witherbone"), "armorplus", "wither_bone"); Utils.setDispItem(materials.get("guardianscale"), "armorplus", "guardian_scale"); // YOU TOO, ACTUALLY ADDITIONS! Utils.setDispItem(materials.get("blackquartz"), "actuallyadditions", "itemMisc", 5); Utils.setDispItem(materials.get("sapphire"), "gemSapphire"); Utils.setDispItem(materials.get("ruby"), "gemRuby"); Utils.setDispItem(materials.get("peridot"), "gemPeridot"); initRecipes(); } private void registerAPIHandlers() { MinecraftForge.EVENT_BUS.register(Toggle.class); MinecraftForge.EVENT_BUS.register(Portal.class); } private void initRecipes() { Item bronzeNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "bronzenugget")); Item bronzeIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "bronzeingot")); Block osmiridiumBlock = Block.REGISTRY.getObject(new ResourceLocation(MODID, "osmiridiumblock")); Item osmiridiumIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "osmiridiumingot")); Item osmiridiumNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "osmiridiumnugget")); Block alumiteBlock = Block.REGISTRY.getObject(new ResourceLocation(MODID, "alumiteblock")); Item alumiteIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "alumiteingot")); Item alumiteNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "alumitenugget")); Block mirionBlock = Block.REGISTRY.getObject(new ResourceLocation(MODID, "mirionblock")); Item mirionIngot = Item.REGISTRY.getObject(new ResourceLocation(MODID, "mirioningot")); Item mirionNugget = Item.REGISTRY.getObject(new ResourceLocation(MODID, "mirionnugget")); if (bronzeNugget != null) { GameRegistry.addRecipe( new ShapedOreRecipe(new ItemStack(bronzeIngot), "III", "III", "III", 'I', "nuggetBronze")); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(bronzeNugget, 9), "ingotBronze")); } if (osmiridiumNugget != null) { GameRegistry.addRecipe( new ShapedOreRecipe(new ItemStack(osmiridiumBlock), "III", "III", "III", 'I', "ingotOsmiridium")); GameRegistry.addShapelessRecipe(new ItemStack(osmiridiumIngot, 9), osmiridiumBlock); GameRegistry.addRecipe( new ShapedOreRecipe(new ItemStack(osmiridiumIngot), "III", "III", "III", 'I', "nuggetOsmiridium")); GameRegistry.addShapelessRecipe(new ItemStack(osmiridiumNugget, 9), osmiridiumIngot); } if (alumiteNugget != null) { GameRegistry.addRecipe( new ShapedOreRecipe(new ItemStack(alumiteBlock), "III", "III", "III", 'I', "ingotAlumite")); GameRegistry.addShapelessRecipe(new ItemStack(alumiteIngot, 9), alumiteBlock); GameRegistry.addRecipe( new ShapedOreRecipe(new ItemStack(alumiteIngot), "III", "III", "III", 'I', "nuggetAlumite")); GameRegistry.addShapelessRecipe(new ItemStack(alumiteNugget, 9), alumiteIngot); } if (mirionNugget != null) { GameRegistry.addRecipe( new ShapedOreRecipe(new ItemStack(mirionBlock), "III", "III", "III", 'I', "ingotMirion")); GameRegistry.addShapelessRecipe(new ItemStack(mirionIngot, 9), mirionBlock); GameRegistry.addRecipe( new ShapedOreRecipe(new ItemStack(mirionIngot), "III", "III", "III", 'I', "nuggetMirion")); GameRegistry.addShapelessRecipe(new ItemStack(mirionNugget, 9), mirionIngot); } } }
package com.lsu.vizeq; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import redis.clients.jedis.Jedis; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.ColorDrawable; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.DhcpInfo; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class SearchPartyActivity extends Activity { public LocationManager locationManager; MyApplication myapp; SearchPartyActivity thisActivity; ActionBar actionBar; Location currLocation = null; @Override protected void onStart(){ super.onStart(); actionBar = getActionBar(); EditText et = (EditText) findViewById(R.id.username_box); et.setText(myapp.myName); SharedPreferences memory = getSharedPreferences("VizEQ",MODE_PRIVATE); int posi = memory.getInt("colorPos", -1); if (posi != -1) VizEQ.numRand = posi; switch (VizEQ.numRand) { case 0: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.black))); break; case 1: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Blue))); break; case 2: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Green))); break; case 3: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Red))); break; case 4: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Grey85))); break; case 5: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Orange))); break; case 6: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Purple))); break; } } @Override protected void onCreate(Bundle savedInstanceState) { myapp = (MyApplication) this.getApplicationContext(); super.onCreate(savedInstanceState); thisActivity = this; setContentView(R.layout.activity_search_party); locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); // Show the Up button in the action bar. actionBar = getActionBar(); actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LightGreen))); setupActionBar(); } public InetAddress getBroadcastAddress() throws IOException { WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcp = wifi.getDhcpInfo(); int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; byte[] quads = new byte[4]; for(int k = 0; k < 4; k++) { quads[k] = (byte) ((broadcast >> k * 8) & 0xFF); } return InetAddress.getByAddress(quads); } public boolean checkIfNameEntered() { boolean nameEntered = false; EditText et = (EditText) findViewById(R.id.username_box); String username = et.getText().toString(); Log.d("username", username); if(!username.isEmpty()) { nameEntered = true; myapp.myName = username; } return nameEntered; } public void searchForPartiesServer(View view) { String name = "Dummy"; myapp.myName = name; if(myapp.zipcode.isEmpty() || myapp.zipcode.isEmpty()) myapp.zipcode = getZipcode(); if(myapp.zipcode.equals("00000")) { noLocationNotification(); } else new ContactServerTask().execute(name, myapp.zipcode); } public void searchForParties(View view) { new ListPartiesTask().execute(); new Thread(new Runnable() { @Override public void run() { DatagramSocket sendSocket; try { sendSocket = new DatagramSocket(); //send search signal byte[] sendData = new byte[1024]; String searchString = "search"; sendData = searchString.getBytes(); DatagramPacket searchPacket = new DatagramPacket(sendData, sendData.length, getBroadcastAddress(), 7770); //send it a bunch of times for(int i=0; i<100; i++) { sendSocket.send(searchPacket); Thread.sleep(10L); } Log.d("search party", "search sent"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } public void refreshPartyList(ArrayList<String> partyNames) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout nameLayout = (LinearLayout) findViewById(R.id.nameLayout); LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.buttonLayout); for(int i=0; i<partyNames.size(); i++) { final String name = partyNames.get(i); //name of party TextView tv = new TextView(this); tv.setText(name); tv.setWidth(200); tv.setHeight(60); tv.setTextSize(20.f); tv.setLayoutParams(params); //join button Button b = new Button(this); b.setText("Join"); b.setWidth(75); b.setHeight(60); b.setLayoutParams(params); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Log.d("Join", "Joining party"); new JoinTaskServer().execute(myapp.zipcode + ":" + name); //new JoinTask().execute((InetAddress) pairs.getValue()); } }); //add them nameLayout.addView(tv); buttonLayout.addView(b); } } public void refreshPartyList() { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout nameLayout = (LinearLayout) findViewById(R.id.nameLayout); LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.buttonLayout); Iterator<Map.Entry<String,InetAddress>> it = myapp.connectedUsers.entrySet().iterator(); while(it.hasNext()) { final Map.Entry<String,InetAddress> pairs = (Map.Entry<String,InetAddress>) it.next(); //name of party TextView tv = new TextView(this); tv.setText((String)pairs.getKey()); tv.setWidth(200); tv.setHeight(60); tv.setTextSize(20.f); tv.setLayoutParams(params); //join button Button b = new Button(this); b.setText("Join"); b.setWidth(75); b.setHeight(60); b.setLayoutParams(params); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { new JoinTask().execute((InetAddress) pairs.getValue()); } }); //add them nameLayout.addView(tv); buttonLayout.addView(b); } } public void noPartiesNotification() { Log.d("Contact Server", "No parties found"); AlertDialog.Builder builder = new AlertDialog.Builder(thisActivity); builder.setMessage("No parties found").setCancelable(false) .setPositiveButton("ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } public void connectionErrorNotification() { Log.d("Contact Server", "Error Connecting"); AlertDialog.Builder builder = new AlertDialog.Builder(thisActivity); builder.setMessage("Error connecting to server").setCancelable(false) .setPositiveButton("ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } public void noLocationNotification() { Log.d("Contact Server", "no location"); AlertDialog.Builder builder = new AlertDialog.Builder(thisActivity); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout alertLayout = new LinearLayout(this); TextView message = new TextView(this); message.setText("Couldn't find your location. Please manually enter your zipcode: "); final EditText zipin = new EditText(this); alertLayout.setOrientation(1); alertLayout.addView(message, params); alertLayout.addView(zipin, params); builder.setView(alertLayout).setCancelable(true) .setPositiveButton("ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String zipcode = zipin.getText().toString(); myapp.zipcode = zipcode; } }) .setNegativeButton("Nevermind", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); AlertDialog alert = builder.create(); alert.show(); } private class ContactServerTask extends AsyncTask<String, Integer, ArrayList<String>> { @Override //params[0] = party name //params[1] = zipcode protected ArrayList<String> doInBackground(String... params) { Log.d("ContactServerTask", "Trying to contact server"); String partyName = params[0]; String zipcode = params[1]; Integer result = 2; Jedis jedis = new Jedis(Redis.host, Redis.port); jedis.auth(Redis.auth); Set<String> names = jedis.smembers(zipcode); ArrayList<String> partyNames = new ArrayList<String>(); //Check if they all have valid ips Iterator<String> it = names.iterator(); while(it.hasNext()) { String name = it.next(); boolean check = jedis.exists(zipcode + ":" + name); if(!check) { jedis.srem(zipcode, name); it.remove(); } else partyNames.add(name); } if (partyNames.size() <= 0) result = 1; else result = 0; if (zipcode.equals("00000")) result = 3; publishProgress(result); jedis.close(); return partyNames; } @Override protected void onPostExecute(ArrayList<String> result) { // TODO Auto-generated method stub Log.d("ContactServerTask", "Finished"); refreshPartyList(result); } @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub if(values[0] == 0) { //good to go } else if(values[0] == 1) { noPartiesNotification(); } else if(values[0] == 2) { connectionErrorNotification(); } else if(values[0] == 3) { noLocationNotification(); } } } private class ListPartiesTask extends AsyncTask<Void, String, String> { DatagramSocket receiveSocket; @Override protected String doInBackground(Void... arg0) { //listen for incoming party info String result = "Unable to find parties. Make sure you're connected to Wifi and try again."; try { receiveSocket = new DatagramSocket(7770); receiveSocket.setSoTimeout(2000); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } String partyName = ""; String partyIp = ""; //listen for response boolean found = false; //base on time elapsed to receive more parties (or no parties) - later while (!found) { byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { receiveSocket.receive(receivePacket); String message = PacketParser.getHeader(receivePacket); if(message.equals("found")) { found = true; partyName = PacketParser.getArgs(receivePacket)[0]; partyIp = receivePacket.getAddress().getHostAddress(); myapp.connectedUsers.put(partyName, InetAddress.getByName(partyIp)); result = "Found parties:"; publishProgress(); } } catch(Exception e) { if(e.getClass().equals(SocketTimeoutException.class)) { found = true; } else e.printStackTrace(); } } return result; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub Log.d("ContactServerTask", "Finished"); TextView resultText = (TextView) findViewById(R.id.resultText); resultText.setText(result); receiveSocket.close(); } @Override protected void onProgressUpdate(String... values) { // TODO Auto-generated method stub refreshPartyList(); } } public class JoinTaskServer extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { //check if not entered username if(!checkIfNameEntered()) return "Must enter name first"; Jedis jedis = new Jedis(Redis.host, Redis.port); jedis.auth(Redis.auth); DatagramSocket sendSocket; DatagramSocket listenSocket; // TODO Auto-generated method stub //send join request Log.d("join party", "Clicked"); try { sendSocket = new DatagramSocket(); listenSocket = new DatagramSocket(7771); //send join request byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String searchString = "join\n"+myapp.myName; sendData = searchString.getBytes(); String ip = jedis.get(params[0]); Log.d("join thru server", "host ip: "+ip); InetAddress ipaddress = InetAddress.getByName(ip); Log.d("join party", "Sending to " + ipaddress.getHostName()); DatagramPacket searchPacket = new DatagramPacket(sendData, sendData.length, ipaddress, 7771); sendSocket.send(searchPacket); Log.d("join party", "join sent to "+ipaddress.getHostName()); //now wait for response boolean joined = false; while(!joined) { Log.d("listen for join", "listening"); DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length); listenSocket.receive(receivePacket); String message = PacketParser.getHeader(receivePacket); Log.d("listen for join", message); if(message.equals("accept")) { Log.d("listen for join", "we are joined"); myapp.joined = true; myapp.hostAddress = receivePacket.getAddress(); joined = true; VizEQ.nowPlaying = PacketParser.getArgs(receivePacket)[0]; } } return "Joined!"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "Failed!"; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub final String s = result; AlertDialog.Builder builder = new AlertDialog.Builder(thisActivity); builder.setMessage(result).setCancelable(false) .setPositiveButton("ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if(!s.equals("Must enter name first")) { Intent nextIntent = new Intent(SearchPartyActivity.this, SoundVisualizationActivity.class); startActivity(nextIntent); } } }); AlertDialog alert = builder.create(); alert.show(); } } public class JoinTask extends AsyncTask<InetAddress, Void, String> { @Override protected String doInBackground(InetAddress... arg0) { //check if not entered username if(!checkIfNameEntered()) return "Must enter name first"; DatagramSocket sendSocket; DatagramSocket listenSocket; // TODO Auto-generated method stub //send join request Log.d("join party", "Clicked"); try { sendSocket = new DatagramSocket(); listenSocket = new DatagramSocket(7771); //send join request byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String searchString = "join\n"+myapp.myName; sendData = searchString.getBytes(); InetAddress ipaddress = arg0[0]; Log.d("join party", "Sending to " + ipaddress.getHostName()); DatagramPacket searchPacket = new DatagramPacket(sendData, sendData.length, ipaddress, 7771); sendSocket.send(searchPacket); Log.d("join party", "join sent to "+ipaddress.getHostName()); //now wait for response boolean joined = false; while(!joined) { Log.d("listen for join", "listening"); DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length); listenSocket.receive(receivePacket); String message = PacketParser.getHeader(receivePacket); Log.d("listen for join", message); if(message.equals("accept")) { Log.d("listen for join", "we are joined"); myapp.joined = true; myapp.hostAddress = receivePacket.getAddress(); joined = true; } } return "Joined!"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "Failed!"; } @Override protected void onPostExecute(String result) { //move to dummy content final String s = result; AlertDialog.Builder builder = new AlertDialog.Builder(thisActivity); builder.setMessage(result).setCancelable(false) .setPositiveButton("ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if(!s.equals("Must enter name first")) { Intent nextIntent = new Intent(SearchPartyActivity.this, SoundVisualizationActivity.class); startActivity(nextIntent); } } }); AlertDialog alert = builder.create(); alert.show(); } } /** * Set up the {@link android.app.ActionBar}. */ private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.search_party, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent nextIntent = new Intent(SearchPartyActivity.this, ProfileActivity.class); startActivity(nextIntent); break; case R.id.about: Intent nextIntent2 = new Intent(SearchPartyActivity.this, AboutActivity.class); startActivity(nextIntent2); break; } return true; } public String getZipcode() { String zipcode = "00000"; if(currLocation == null) { String locationProvider = LocationManager.GPS_PROVIDER; currLocation = locationManager.getLastKnownLocation(locationProvider); } Geocoder geocoder = new Geocoder(this, Locale.getDefault()); try { List<Address> addresses = geocoder.getFromLocation(currLocation.getLatitude(), currLocation.getLongitude(), 1); zipcode = addresses.get(0).getPostalCode(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("zipcode", zipcode); locationManager.removeUpdates(locationListener); return zipcode; } public LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location arg0) { // TODO Auto-generated method stub Log.d("location listener", "location changed"); currLocation = arg0; } @Override public void onProviderDisabled(String arg0) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String arg0) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { // TODO Auto-generated method stub } }; }
package lemming.tree; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.model.IModel; import org.apache.wicket.request.Request; import org.apache.wicket.util.string.StringValue; /** * A selectable tree node. * * @param <T> data type */ public class DraggableNode<T> extends BaseNode<T> { /** * Creates a tree node. * * @param id ID of the node * @param tree the owning tree * @param model model of the node object */ public DraggableNode(String id, AbstractNestedTree<T> tree, IModel<T> model) { super(id, tree, model); Dropzone bottomDropzone = new Dropzone("bottomDropzone", DropzoneType.BOTTOM); Dropzone middleDropzone = new Dropzone("middleDropzone", DropzoneType.MIDDLE); Dropzone topDropzone = new Dropzone("topDropzone", DropzoneType.TOP); bottomDropzone.add(new DragenterBehavior()); bottomDropzone.add(new DragoverBehavior()); bottomDropzone.add(new DragleaveBehavior()); bottomDropzone.add(new DropBehavior()); add(bottomDropzone); middleDropzone.add(new NodeSwitch("switch")); middleDropzone.add(getTree().newContentComponent("content", getModel())); middleDropzone.add(new DragenterBehavior()); middleDropzone.add(new DragoverBehavior()); middleDropzone.add(new DragleaveBehavior()); middleDropzone.add(new DragstartBehavior()); middleDropzone.add(new DragendBehavior()); middleDropzone.add(new DropBehavior()); add(middleDropzone); topDropzone.add(new DragenterBehavior()); topDropzone.add(new DragoverBehavior()); topDropzone.add(new DragleaveBehavior()); topDropzone.add(new DropBehavior()); add(topDropzone); add(new SelectBehavior()); add(new StyleBehavior()); setOutputMarkupId(true); } /** * Renders to the web response what the component wants to contribute. * * @param response response object */ @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); String javaScript = "jQuery(document).on('dragover drop', ':not(.dropzone)', function (event) { " + "event.preventDefault(); });"; response.render(OnDomReadyHeaderItem.forScript(javaScript)); } /** * Dropzone type. */ private enum DropzoneType { BOTTOM, MIDDLE, TOP } /** * Additional dropzones for draggable nodes. */ private class Dropzone extends WebMarkupContainer { /** * Dropzone type. */ private DropzoneType type; /** * Creates a dropzone * * @param id ID of the dropzone * @param type dropzone type */ public Dropzone(String id, DropzoneType type) { super(id); this.type = type; setOutputMarkupId(true); } /** * Returns the dropzone type. * * @return A dropzone type. */ public DropzoneType getType() { return type; } /** * Processes the component tag. * * @param tag tag to modify */ @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); if (type.equals(DropzoneType.BOTTOM)) { tag.put("class", "dropzone dropzone-bottom"); } else if (type.equals(DropzoneType.MIDDLE)) { tag.put("class", "dropzone dropzone-middle"); tag.put("draggable", "true"); } else if (type.equals(DropzoneType.TOP)) { tag.put("class", "dropzone dropzone-top"); } } } /** * A behavior which fires on drag enter. */ private class DragenterBehavior extends Behavior { /** * Renders to the web response what the component wants to contribute. * * @param response response object */ @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); String nodeMarkupId = component.getParent().getMarkupId(); String javaScript = "jQuery(document).on('dragenter', '#" + component.getMarkupId() + "', " + "function (event) { " + "jQuery(this).addClass('dropzone-dragover'); " + "jQuery('#" + nodeMarkupId + "').not('.node-dragging').addClass('node-dragover'); " + "var active = jQuery('#" + nodeMarkupId + "').data('active') || 0; " + "jQuery('#" + nodeMarkupId + "').data('active', active + 1); " + "event.preventDefault(); });"; response.render(OnDomReadyHeaderItem.forScript(javaScript)); } } /** * A behavior which fires on drag over. */ private class DragoverBehavior extends Behavior { /** * Renders to the web response what the component wants to contribute. * * @param response response object */ @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); String javaScript = "jQuery(document).on('dragover', '#" + component.getMarkupId() + "', " + "function (event) { " + "event.originalEvent.dataTransfer.dropEffect = 'move'; " + "event.preventDefault(); });"; response.render(OnDomReadyHeaderItem.forScript(javaScript)); } } /** * A behavior which fires on drag leave. */ private class DragleaveBehavior extends Behavior { /** * Renders to the web response what the component wants to contribute. * * @param response response object */ @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); Component node = component.getParent(); String javaScript = "jQuery(document).on('dragleave', '#" + component.getMarkupId() + "', " + "function (event) { " + "jQuery(this).removeClass('dropzone-dragover'); " + "var active = jQuery('#" + node.getMarkupId() + "').data('active'); " + "jQuery('#" + node.getMarkupId() + "').data('active', active - 1); " + "if (active < 2) { jQuery('#" + node.getMarkupId() + "').removeClass('node-dragover'); } " + "event.preventDefault(); });"; response.render(OnDomReadyHeaderItem.forScript(javaScript)); } } /** * A behavior which fires on drag start. */ private class DragstartBehavior extends Behavior { /** * Renders to the web response what the component wants to contribute. * * @param response response object */ @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); Component node = component.getParent(); String javaScript = "jQuery(document).on('dragstart', '#" + component.getMarkupId() + "', " + "function (event) { " + "jQuery('#" + node.getMarkupId() + "').addClass('node-dragging'); " + "event.originalEvent.dataTransfer.clearData(); " + "event.originalEvent.dataTransfer.setData('text/plain', '" + node.getPageRelativePath() + "'); " + "event.originalEvent.dataTransfer.effectAllowed = 'move'; });"; response.render(OnDomReadyHeaderItem.forScript(javaScript)); } } /** * A behavior which fires on drag end. */ private class DragendBehavior extends Behavior { /** * Renders to the web response what the component wants to contribute. * * @param response response object */ @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); Component node = component.getParent(); String javaScript = "jQuery(document).on('dragend', '#" + component.getMarkupId() + "', " + "function (event) { jQuery('#" + node.getMarkupId() + "').removeClass('node-dragging'); " + "jQuery(this).closest('.tree').find('.node-dragover').data('active', 0)" + ".removeClass('node-dragover'); " + "jQuery(this).closest('.tree').find('.dropzone-dragover').removeClass('dropzone-dragover'); " + "event.preventDefault(); });"; response.render(OnDomReadyHeaderItem.forScript(javaScript)); } } /** * A behavior which fires on drop. */ private class DropBehavior extends AjaxEventBehavior { /** * Creates a drop behavior. */ public DropBehavior() { super("drop"); } /** * Renders to the web response what the component wants to contribute. * * @param response response object */ @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); String javaScript = "jQuery(document).on('drop', '#" + component.getMarkupId() + "', function (event) { " + "event.preventDefault(); });"; response.render(OnDomReadyHeaderItem.forScript(javaScript)); } /** * Called when a draggable is dropped on a node. * * @param target target that produces an Ajax response */ @Override @SuppressWarnings("unchecked") protected void onEvent(AjaxRequestTarget target) { AbstractNestedTree<T> tree = getTree(); Request request = getComponent().getRequest(); StringValue data = request.getRequestParameters().getParameterValue("data"); if (data.toString() != null && tree instanceof IDraggableTree) { String relativePath = data.toString(); Dropzone dropzone = (Dropzone) getComponent(); Component sourceComponent = getPage().get(relativePath); Component targetComponent = dropzone.getParent(); if (targetComponent.equals(sourceComponent)) { return; } for (IDropListener dropListener : ((IDraggableTree) tree).getDropListeners()) { if (dropzone.getType().equals(DropzoneType.BOTTOM)) { dropListener.onBottomDrop(sourceComponent, targetComponent); } else if (dropzone.getType().equals(DropzoneType.MIDDLE)) { dropListener.onMiddleDrop(sourceComponent, targetComponent); } else if (dropzone.getType().equals(DropzoneType.TOP)) { dropListener.onTopDrop(sourceComponent, targetComponent); } } } } /** * Modifies Ajax request attributes. * * @param attributes Ajax request attributes */ @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); String javaScript = "var dataTransfer = attrs.event.originalEvent.dataTransfer; " + "return { data: (!dataTransfer ? '' : dataTransfer.getData('text/plain')) };"; attributes.getDynamicExtraParameters().add(javaScript); } } }
package me.ronghai.sa.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author L5M */ @Entity(name="clients") public class Client implements Serializable, AbstractModel { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Column(name = "name") private String name; @Column(name = "wangwang") private String wangwang; @Column(name = "qq") private int qq; @Column(name = "birthday", nullable=true) @Temporal(TemporalType.TIME) private Date birthday; @Column(name = "gender") private String gender; @Column(name = "phone") private String phone; @Column(name = "disabled") private boolean disabled; @Column(name = "add_time", nullable=true) @Temporal(TemporalType.TIME) private Date addTime; @Column(name = "update_time", nullable=true) @Temporal(TemporalType.TIME) private Date updateTime; @Column(name = "note") private String note; public Client() { } public Client(Long id) { this.id = id; } public Client(Long id, String name, String wangwang, int qq, Date birthday, String gender, String phone, boolean disabled, Date addTime, Date updateTime) { this.id = id; this.name = name; this.wangwang = wangwang; this.qq = qq; this.birthday = birthday; this.gender = gender; this.phone = phone; this.disabled = disabled; this.addTime = addTime; this.updateTime = updateTime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWangwang() { return wangwang; } public void setWangwang(String wangwang) { this.wangwang = wangwang; } public int getQq() { return qq; } public void setQq(int qq) { this.qq = qq; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public boolean getDisabled() { return disabled; } /** * * @param disabled */ @Override public void setDisabled(boolean disabled) { this.disabled = disabled; } public Date getAddTime() { return addTime; } public void setAddTime(Date addTime) { this.addTime = addTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Client)) { return false; } Client other = (Client) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "me.ronghai.sa.model.Client[ id=" + id + " ]"; } }
package mj.jmex.visualfx; import com.jme3.asset.AssetManager; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.post.Filter; import com.jme3.renderer.RenderManager; import com.jme3.renderer.Renderer; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue; import com.jme3.texture.Image.Format; import com.jme3.texture.Texture; import com.jme3.texture.Texture2D; import java.io.IOException; import java.util.ArrayList; /** * This bloom filter uses mipmaps of the main scene to generate a large * bloom effect. * The final result is a scene texture with blur of the bright parts, which is * calculated by summing over the mipmap levels using the intensity equation: * <code>final_color=bloomFactor*sum(mipmap_color*bloomPower^level)</code> * <p> * Adjustment of the bloom inensity and the downsampling coefficient shall be * chosen very carefully. */ public class MipmapBloomFilter extends Filter { private Quality quality=Quality.High; private GlowMode glowMode=GlowMode.Scene; private float exposurePower=3.0f; private float exposureCutOff=0.0f; private float bloomFactor=1.5f; private float bloomPower=1.5f; private float downSamplingCoef=2.0f; private Pass preGlowPass; private Pass extractPass; private Material extractMat; private int screenWidth; private int screenHeight; private RenderManager renderManager; private ViewPort viewPort; private AssetManager assetManager; private int initialWidth; private int initialHeight; private final int numPasses=8; private Format texFormat=Format.RGB111110F; /** * GlowMode specifies if the glow will be applied to the whole scene, or to * objects that have aglow color or a glow map. */ public enum GlowMode { /** * Apply bloom filter to bright areas in the scene. (Default) */ Scene, /** * Apply bloom only to objects that have a glow map or a glow color. */ Objects, /** * Apply bloom to both bright parts of the scene and objects with glow map. */ SceneAndObjects; } /** * The Quality can be adjusted to achieve better results at lower * performance. */ public enum Quality { /** * Uses an additional gaussian blur to smooth each mipmap level. (Default) */ High, /** * Lower quality but better performance mode. */ Low; } /** * Instantiates a new bloom filter. */ public MipmapBloomFilter() { super("MipmapBloomFilter"); } /** * Instantiates a new bloom filter with the specified GlowMode. * @param glowMode */ public MipmapBloomFilter(GlowMode glowMode) { this(); this.glowMode=glowMode; } /** * Instantiates a new bloom filter with the specified quality. * @param quality */ public MipmapBloomFilter(Quality quality) { this(); this.quality=quality; } /** * Instantiates a new bloom filter with the specified quality and GlowMode. * @param quality * @param glowMode */ public MipmapBloomFilter(Quality quality, GlowMode glowMode) { this(); this.quality=quality; this.glowMode=glowMode; } @Override protected void initFilter(final AssetManager manager, RenderManager renderManager, ViewPort vp, int w, int h) { this.renderManager=renderManager; this.viewPort=vp; this.assetManager=manager; this.initialWidth=w; this.initialHeight=h; postRenderPasses=new ArrayList<Pass>(); // Configure the preGlowPass, for use with GlowMode.SceneAndObjects and // GlowMode.Objects. screenWidth=(int)Math.max(1.0, (w/downSamplingCoef)); screenHeight=(int)Math.max(1.0, (h/downSamplingCoef)); if (glowMode!=GlowMode.Scene) { preGlowPass=new Pass(); preGlowPass.init(renderManager.getRenderer(), screenWidth, screenHeight, texFormat, Format.Depth); } // Configure extractPass, extracting bright pixels from the scene. extractMat=new Material(manager, "Common/MatDefs/Post/BloomExtract.j3md"); extractPass=new Pass() { @Override public boolean requiresSceneAsTexture() {return true;} @Override public void beforeRender() { extractMat.setFloat("ExposurePow", exposurePower); extractMat.setFloat("ExposureCutoff", exposureCutOff); if (glowMode!=GlowMode.Scene) { extractMat.setTexture("GlowMap", preGlowPass.getRenderedTexture()); } extractMat.setBoolean("Extract", glowMode!=GlowMode.Objects); } }; extractPass.init(renderManager.getRenderer(), initialWidth, initialHeight, texFormat, Format.Depth, 1, extractMat); extractPass.getRenderedTexture().setMagFilter(Texture.MagFilter.Bilinear); extractPass.getRenderedTexture().setMinFilter(Texture.MinFilter.Trilinear); postRenderPasses.add(extractPass); // Configure mipmap blur passes. // The mipmaps will be generated with according width and height, that can be // specified implicitly with the downSamplingFactor. final Pass[] mmPasses=new Pass[numPasses]; final Texture2D[] mipmaps=new Texture2D[numPasses]; for (int ii=0; ii<numPasses; ii++) { final int passWidth=(int)(initialWidth/FastMath.pow(downSamplingCoef, (ii+1))); final int passHeight=(int)(initialHeight/FastMath.pow(downSamplingCoef, (ii+1))); final Material passMat=new Material(manager, "MatDefs/MipmapBloom/MipmapSampler.j3md"); final int jj=ii; mmPasses[jj]=new Pass() { @Override public void beforeRender() { if (jj==0) passMat.setTexture("Texture", extractPass.getRenderedTexture()); else passMat.setTexture("Texture", mmPasses[jj-1] .getRenderedTexture()); passMat.setFloat("Dx", 0.5f/(float)passWidth); passMat.setFloat("Dy", 0.5f/(float)passHeight); } }; mmPasses[jj].init(renderManager.getRenderer(), passWidth, passHeight, texFormat, Format.Depth, 1, passMat); mmPasses[jj].getRenderedTexture().setMagFilter( Texture.MagFilter.Bilinear); mmPasses[jj].getRenderedTexture().setMinFilter( Texture.MinFilter.Trilinear); postRenderPasses.add(mmPasses[jj]); // In high quality mode each mipmap will be blurred with a gaussian blur, // which makes the result much smoother. if (quality==Quality.High) mipmaps[jj]=gaussianBlur(manager, mmPasses[jj].getRenderedTexture()); else mipmaps[jj]=mmPasses[jj].getRenderedTexture(); } // Accumulate mipmaps to the final image. material=new Material(manager, "MatDefs/MipmapBloom/Accumulation.j3md"); for (int ii=0; ii<numPasses; ii++) material.setTexture("Texture"+(ii+1), mipmaps[ii]); setBloomIntensity(bloomFactor, bloomPower); } /** * Adds an additional Gaussian blur (one horizontal and one vertical pass) to * the specified texture. * * @param manager * @param texture A single mipmap texture here. * @return */ private Texture2D gaussianBlur(AssetManager manager, final Texture2D texture) { final int w=texture.getImage().getWidth(); final int h=texture.getImage().getHeight(); // Configure horizontal blur pass. final Material hBlurMat=new Material(manager, "MatDefs/MipmapBloom/HGaussianBlur.j3md"); final Pass hBlur=new Pass() { @Override public void beforeRender() { hBlurMat.setTexture("Texture", texture); hBlurMat.setFloat("Size", w); hBlurMat.setFloat("Scale", 0.5f); } }; hBlur.init(renderManager.getRenderer(), w, h, texFormat, Format.Depth, 1, hBlurMat); hBlur.getRenderedTexture().setMagFilter(Texture.MagFilter.Bilinear); hBlur.getRenderedTexture().setMinFilter(Texture.MinFilter.Trilinear); postRenderPasses.add(hBlur); // Configure vertical blur pass. final Material vBlurMat=new Material(manager, "MatDefs/MipmapBloom/VGaussianBlur.j3md"); final Pass vBlur=new Pass() { @Override public void beforeRender() { vBlurMat.setTexture("Texture", hBlur.getRenderedTexture()); vBlurMat.setFloat("Size", h); vBlurMat.setFloat("Scale", 0.5f); } }; vBlur.init(renderManager.getRenderer(), w, h, texFormat, Format.Depth, 1, vBlurMat); vBlur.getRenderedTexture().setMagFilter(Texture.MagFilter.Bilinear); vBlur.getRenderedTexture().setMinFilter(Texture.MinFilter.Trilinear); postRenderPasses.add(vBlur); return vBlur.getRenderedTexture(); } /** * Reinitializes the filter by calling initFilter. */ protected void reInitFilter() { initFilter(assetManager, renderManager, viewPort, initialWidth, initialHeight); } /** * Provides the premultiplication factor of the intensity equation. * * @return */ public float getBloomFactor() {return bloomFactor;} @Override protected Material getMaterial() {return material;} /** * Extracts the material's Glow techniques (if specified) and renders it into * the preGlowPass, if GlowMode is not Scene. * * @param queue The queue of the rendered scene. */ @Override protected void postQueue(RenderQueue queue) { if (glowMode!=GlowMode.Scene) { renderManager.getRenderer().setBackgroundColor(ColorRGBA.BlackNoAlpha); renderManager.getRenderer().setFrameBuffer( preGlowPass.getRenderFrameBuffer()); renderManager.getRenderer().clearBuffers(true, true, true); renderManager.setForcedTechnique("Glow"); renderManager.renderViewPortQueues(viewPort, false); renderManager.setForcedTechnique(null); renderManager.getRenderer().setFrameBuffer( viewPort.getOutputFrameBuffer()); } } @Override protected void cleanUpFilter(Renderer r) { if (glowMode!=GlowMode.Scene) preGlowPass.cleanup(r); } /** * Provides the power coefficient of the intensity equation. * @return The power coefficient. */ public float getBloomPower() {return bloomPower;} /** * Sets weight factors for each mipmap by calculating the intensity equation * (see above). * * @param bloomFactor A constant premultiplication factor that should be * less than 1. * @param bloomPower A greater value increases the bloom intensity of each * mipmap level. */ public void setBloomIntensity(float bloomFactor, float bloomPower) { if (material!=null) { for (int ii=0; ii<numPasses; ii++) { float wt=bloomFactor*FastMath.pow(bloomPower, ii); material.setFloat("Weight"+(ii+1), wt); } } this.bloomFactor=bloomFactor; this.bloomPower=bloomPower; } /** * Provides the exposure cutoff. * @return Exposure cutoff. */ public float getExposureCutOff() {return exposureCutOff;} /** * Define the color threshold on which the bloom will be applied (0.0 to 1.0) * @param exposureCutOff The color threshold value. */ public void setExposureCutOff(float exposureCutOff) { this.exposureCutOff=exposureCutOff; } /** * Provides the exposure power of the intensity equation. * @return */ public float getExposurePower() {return exposurePower;} /** * Sets the exposure power value of the intensity equation (see above). * @param exposurePower */ public void setExposurePower(float exposurePower) { this.exposurePower=exposurePower; } /** * Sets the glow mode of the bloom filter. * @param glowMode See above. */ public void setGlowMode(GlowMode glowMode) { this.glowMode=glowMode; if (assetManager!=null) // Dirty initialization check. reInitFilter(); } /** * Sets the quality of the bloom filter. * @param enabled <code>true</code> for <code>Quality.High</code>. */ public void setHighQuality(boolean enabled) { this.quality=enabled? Quality.High:Quality.Low; if (assetManager!=null) // Dirty initialization check. reInitFilter(); } /** * Provides the downSampling coefficient of the mipmap levels. * @return The downsampling coefficient. */ public float getDownSamplingCoef() {return downSamplingCoef;} /** * Sets the downsampling coefficient. * Each mipmap (starting with level 0) will have a reduced size defined by: * <code>mipmap_size=framebuffer_size/pow(downSamplingCoef^(level+1))</code>. * <p> * A lower value means less blur at higher computational cost, as the last level * will have a high resolution. The coefficient shall therefore be chosen in * such a way, that the highest (7th) level will have a resolution of just a few * pixels. * * @param downSamplingCoef The downsampling coefficient. */ public void setDownSamplingCoef(float downSamplingCoef) { this.downSamplingCoef=downSamplingCoef; if (assetManager!=null) // dirty isInitialised check reInitFilter(); } @Override public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule oc=ex.getCapsule(this); oc.write(quality, "quality", Quality.High); oc.write(glowMode, "glowMode", GlowMode.Scene); oc.write(exposurePower, "exposurePower", 5.0f); oc.write(exposureCutOff, "exposureCutOff", 0.0f); oc.write(bloomFactor, "bloomFactor", 0.2f); oc.write(bloomPower, "bloomIntensity", 2.0f); oc.write(downSamplingCoef, "downSamplingFactor", 1); } @Override public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule ic=im.getCapsule(this); quality=ic.readEnum("quality", Quality.class, Quality.High); glowMode=ic.readEnum("glowMode", GlowMode.class, GlowMode.Scene); exposurePower=ic.readFloat("exposurePower", 5.0f); exposureCutOff=ic.readFloat("exposureCutOff", 0.0f); bloomFactor=ic.readFloat("bloomFactor", 0.2f); bloomPower=ic.readFloat("bloomIntensity", 2.0f); downSamplingCoef=ic.readFloat("downSamplingFactor", 1); } }
package com.oasisfeng.android.base; import static android.content.Context.MODE_PRIVATE; import java.util.HashSet; import java.util.Set; import android.app.Activity; import android.app.Application.ActivityLifecycleCallbacks; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import com.oasisfeng.android.base.Scopes.Scope; /** @author Oasis */ public class Scopes { public static final String KPrefsNameAppScope = "app.scope"; public static final String KPrefsNameVersionScope = "version.scope"; public interface Scope { public boolean isMarked(String tag); public boolean mark(String tag); public boolean unmark(String tag); } public static Scope app(final Context context) { return new AppScope(context); } public static Scope version(final Context context) { return new VersionScope(context); } public static Scope process() { return ProcessScope.mSingleton; } public static Scope session(final Activity activity) { if (SessionScope.mSingleton == null) SessionScope.mSingleton = new SessionScope(activity); return SessionScope.mSingleton; } private Scopes() {} } class SessionScope extends MemoryBasedScopeImpl { private static final int KSessionTimeout = 30 * 60 * 1000; // TODO: Configurable public SessionScope(final Activity activity) { activity.getApplication().registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { @Override public void onActivityResumed(final Activity a) { if (System.currentTimeMillis() >= mTimeLastSession + KSessionTimeout) mSeen.clear(); } @Override public void onActivityPaused(final Activity a) { mTimeLastSession = System.currentTimeMillis(); } @Override public void onActivityStopped(final Activity a) {} @Override public void onActivityStarted(final Activity a) {} @Override public void onActivitySaveInstanceState(final Activity a, final Bundle s) {} @Override public void onActivityCreated(final Activity a, final Bundle s) {} @Override public void onActivityDestroyed(final Activity a) {} }); } private long mTimeLastSession = 0; static SessionScope mSingleton; } class ProcessScope extends MemoryBasedScopeImpl { static final Scope mSingleton = new ProcessScope(); } class MemoryBasedScopeImpl implements Scope { @Override public boolean isMarked(final String tag) { return mSeen.contains(tag); } @Override public boolean mark(final String tag) { return mSeen.add(tag); } @Override public boolean unmark(final String tag) { return mSeen.remove(tag); } protected final Set<String> mSeen = new HashSet<String>(); } class VersionScope extends SharedPrefsBasedScopeImpl { private static final String KPrefsKeyVersionCode = "version-code"; VersionScope(final Context context) { super(resetIfVersionChanges(context, context.getSharedPreferences(Scopes.KPrefsNameVersionScope, MODE_PRIVATE))); } private static SharedPreferences resetIfVersionChanges(final Context context, final SharedPreferences prefs) { final int version = Versions.code(context); if (version != prefs.getInt(KPrefsKeyVersionCode, 0)) prefs.edit().clear().putInt(KPrefsKeyVersionCode, version).apply(); return prefs; } } class AppScope extends SharedPrefsBasedScopeImpl { AppScope(final Context context) { super(context.getSharedPreferences(Scopes.KPrefsNameAppScope, MODE_PRIVATE)); } } class SharedPrefsBasedScopeImpl implements Scope { private static final String KPrefsKeyPrefix = "first-time-"; // Old name, for backward-compatibility @Override public boolean isMarked(final String tag) { final String key = KPrefsKeyPrefix + tag; return ! mPrefs.getBoolean(key, true); } @Override public boolean mark(final String tag) { final String key = KPrefsKeyPrefix + tag; if (! mPrefs.getBoolean(key, true)) return false; mPrefs.edit().putBoolean(key, false).apply(); return true; } @Override public boolean unmark(final String tag) { final String key = KPrefsKeyPrefix + tag; if (mPrefs.getBoolean(key, true)) return false; mPrefs.edit().putBoolean(key, true).apply(); return true; } protected SharedPrefsBasedScopeImpl(final SharedPreferences prefs) { mPrefs = prefs; } private final SharedPreferences mPrefs; }
package net.dean.jraw; import com.fasterxml.jackson.databind.JsonNode; import net.dean.jraw.http.AuthenticationMethod; import net.dean.jraw.http.HttpAdapter; import net.dean.jraw.http.HttpRequest; import net.dean.jraw.http.MediaTypes; import net.dean.jraw.http.NetworkException; import net.dean.jraw.http.OkHttpAdapter; import net.dean.jraw.http.RestClient; import net.dean.jraw.http.RestResponse; import net.dean.jraw.http.SubmissionRequest; import net.dean.jraw.http.UserAgent; import net.dean.jraw.http.oauth.Credentials; import net.dean.jraw.http.oauth.InvalidScopeException; import net.dean.jraw.http.oauth.OAuthData; import net.dean.jraw.http.oauth.OAuthHelper; import net.dean.jraw.models.Account; import net.dean.jraw.models.Award; import net.dean.jraw.models.Captcha; import net.dean.jraw.models.CommentSort; import net.dean.jraw.models.Listing; import net.dean.jraw.models.LoggedInAccount; import net.dean.jraw.models.Submission; import net.dean.jraw.models.Subreddit; import net.dean.jraw.models.Thing; import net.dean.jraw.models.meta.Model; import net.dean.jraw.models.meta.SubmissionSerializer; import net.dean.jraw.paginators.Sorting; import net.dean.jraw.paginators.SubredditPaginator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class provides a gateway to the services this library provides */ public class RedditClient extends RestClient { /** The host that will be used to execute OAuth requests */ public static final String HOST = "oauth.reddit.com"; /** Used under special circumstances, such as OAuth authentications */ public static final String HOST_SPECIAL = "www.reddit.com"; /** The amount of requests allowed per minute when using OAuth2 */ public static final int REQUESTS_PER_MINUTE = 60; /** The default amount of times a request will be retried if a server-side error is encountered. */ public static final int DEFAULT_RETRY_LIMIT = 5; /** The amount of trending subreddits that appear in each /r/trendingsubreddits post */ private static final int NUM_TRENDING_SUBREDDITS = 5; private static final String HEADER_AUTHORIZATION = "Authorization"; private static final String HEADER_RATELIMIT_RESET = "X-Ratelimit-Reset"; private static final String HEADER_RATELIMIT_REMAINING = "X-Ratelimit-Remaining"; /** The username of the user who is currently authenticated */ private String authenticatedUser; private boolean adjustRatelimit; private int retryLimit; /** The method of authentication currently being used */ private AuthenticationMethod authMethod; private OAuthData authData; private OAuthHelper authHelper; /** * Instantiates a new RedditClient and adds the given user agent to the default headers * * @param userAgent The User-Agent header that will be sent with all the HTTP requests. */ public RedditClient(UserAgent userAgent) { this(userAgent, new OkHttpAdapter()); } /** * Instantiates a new RedditClient and adds the given user agent to the default headers * * @param userAgent The User-Agent header that will be sent with all the HTTP requests. * @param adapter How the client will send HTTP requests */ public RedditClient(UserAgent userAgent, HttpAdapter adapter) { super(adapter, HOST, userAgent, REQUESTS_PER_MINUTE); this.authMethod = AuthenticationMethod.NOT_YET; this.authHelper = new OAuthHelper(this); this.adjustRatelimit = true; this.retryLimit = DEFAULT_RETRY_LIMIT; setHttpsDefault(true); } public String getAuthenticatedUser() { if (!(isAuthenticated() && hasActiveUserContext())) throw new IllegalStateException("Not authenticated or no active user context"); return authenticatedUser; } /** * Provides this RedditClient with the information to perform OAuth2-related activities. This method * <strong>must</strong> be called in order to use the API. All endpoints will return a 403 Forbidden otherwise. * @param authData Authentication data. Most commonly obtained from {@link #getOAuthHelper()}. * @throws NetworkException Thrown when there was a problem setting the authenticated user. Can only happen when * the authentication method is not userless. */ public void authenticate(OAuthData authData) throws NetworkException { if (authHelper.getAuthStatus() != OAuthHelper.AuthStatus.AUTHORIZED) throw new IllegalStateException("OAuthHelper says it is not authorized"); if (authData.getAuthenticationMethod() == null) throw new NullPointerException("Authentication method cannot be null"); this.authMethod = authData.getAuthenticationMethod(); this.authData = authData; httpAdapter.getDefaultHeaders().put(HEADER_AUTHORIZATION, "bearer " + authData.getAccessToken()); if (!authMethod.isUserless() && isAuthorizedFor(Endpoints.OAUTH_ME)) { this.authenticatedUser = me().getFullName(); } } /** * Removes any authentication data. The access token needs to be revoked first using * {@link OAuthHelper#revokeAccessToken(Credentials)}. */ public void deauthenticate() { if (authHelper.getAuthStatus() != OAuthHelper.AuthStatus.REVOKED) throw new IllegalArgumentException("Revoke the access token first"); authData = null; httpAdapter.getDefaultHeaders().remove(HEADER_AUTHORIZATION); authMethod = AuthenticationMethod.NOT_YET; } @Override public RestResponse execute(HttpRequest request) throws NetworkException, InvalidScopeException { return execute(request, 0); } private RestResponse execute(HttpRequest request, int retryCount) throws NetworkException, InvalidScopeException { RestResponse response; try { response = super.execute(request); } catch (NetworkException e) { RestResponse errorResponse = e.getResponse(); final int code = errorResponse.getStatusCode(); if (code == 403 && errorResponse.getHeaders().get("WWW-Authenticate") != null) { // Invalid scope throw new InvalidScopeException(errorResponse.getOrigin().getUrl()); } else if (code >= 500 && code < 600) { // Server-side error, retry if (retryCount++ > retryLimit) { throw new IllegalStateException("Reached retry limit", e); } return execute(request, retryCount); } throw e; } if (adjustRatelimit) adjustRatelimit(response); return response; } /** Adjust rate limit dynamically based off of X-Ratelimit-{Remaining,Reset} headers. */ private void adjustRatelimit(RestResponse response) { if (response.getHeaders().get(HEADER_RATELIMIT_RESET) == null || response.getHeaders().get(HEADER_RATELIMIT_REMAINING) == null) { // Could not find the necessary headers return; } int reset; // Time in seconds when the ratelimit will reset. Has an integer value double remaining; // How many requests are left. Has decimal value try { reset = Integer.parseInt(response.getHeaders().get(HEADER_RATELIMIT_RESET)); remaining = Double.parseDouble(response.getHeaders().get(HEADER_RATELIMIT_REMAINING)); } catch (NumberFormatException e) { JrawUtils.logger().warn("Unable to parse ratelimit headers, using default", e); // One request per minute for OAuth2, as specified by the docs reset = 600; remaining = 600.0; } double resetMinutes = reset / 60.0; int requestsPerMinute = (int) Math.floor(remaining / resetMinutes); if (requestsPerMinute < 1) { requestsPerMinute = 1; } setRatelimit(requestsPerMinute); } /** Checks whether the ratelimit will be changed based on specific headers returned from Reddit API responses. */ public boolean isAdjustingRatelimit() { return adjustRatelimit; } /** * Sets if the ratelimit should be adjusted based off values provided by Reddit in the form of headers from API * responses. */ public void setAdjustRatelimit(boolean flag) { this.adjustRatelimit = flag; } /** Gets the amount of times a request will be retried if a server-side error is encountered. */ public int getRetryLimit() { return retryLimit; } /** * Sets the amount of times a request will be retried if a server-side error is encountered. A negative value is not * accepted. * * @see #DEFAULT_RETRY_LIMIT */ public void setRetryLimit(int retryLimit) { if (retryLimit < 0) throw new IllegalArgumentException("Limit cannot be less than 0"); this.retryLimit = retryLimit; } /** Checks if this RedditClient is current authenticated. */ public boolean isAuthenticated() { return authMethod != AuthenticationMethod.NOT_YET && authData != null; } /** * Gets the currently logged in account * * @return The currently logged in account * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME) public LoggedInAccount me() throws NetworkException { RestResponse response = execute(request() .endpoint(Endpoints.OAUTH_ME) .build()); // Usually we would use response.as(), but /api/v1/me does not return a "data" or "kind" node. return new LoggedInAccount(response.getJson()); } /** * Checks if the current user needs a captcha to do specific actions such as submit links and compose private * messages. This will always be true if there is no logged in user. Usually, this method will return {@code true} * if the current logged in user has more than 10 link karma * * @return True if the user needs a captcha to do a specific action, else if not or not logged in. * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.NEEDS_CAPTCHA) public boolean needsCaptcha() throws NetworkException { // This endpoint does not return JSON, but rather just "true" or "false" RestResponse response = execute(request() .endpoint(Endpoints.NEEDS_CAPTCHA) .get() .build()); return Boolean.parseBoolean(response.getRaw()); } /** * Fetches a new captcha from the API * * @return A new Captcha * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ @EndpointImplementation(Endpoints.NEW_CAPTCHA) public Captcha getNewCaptcha() throws NetworkException, ApiException { RestResponse response = execute(request() .endpoint(Endpoints.NEW_CAPTCHA) .post(JrawUtils.mapOf( "api_type", "json" )).build()); if (response.hasErrors()) { throw response.getError(); } String id = response.getJson().get("json").get("data").get("iden").asText(); return getCaptcha(id); } /** * Gets a Captcha by its ID * * @param id The ID of the wanted captcha * @return A new Captcha object */ @EndpointImplementation(Endpoints.CAPTCHA_IDEN) public Captcha getCaptcha(String id) { return new Captcha(id); } /** * Gets a user with a specific username * * @param username The name of the desired user * @return An Account whose name matches the given username * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.USER_USERNAME_ABOUT) public Account getUser(String username) throws NetworkException { return execute(request() .endpoint(Endpoints.USER_USERNAME_ABOUT, username) .get() .build()).as(Account.class); } /** * Gets a link with a specific ID * * @param id The link's ID, ex: "92dd8" * @return A new Link object * @throws NetworkException If the request was not successful */ public Submission getSubmission(String id) throws NetworkException { return getSubmission(new SubmissionRequest(id)); } @EndpointImplementation(Endpoints.COMMENTS_ARTICLE) public Submission getSubmission(SubmissionRequest request) throws NetworkException { Map<String, String> args = new HashMap<>(); if (request.getDepth() != null) args.put("depth", Integer.toString(request.getDepth())); if (request.getContext() != null) args.put("context", Integer.toString(request.getContext())); if (request.getLimit() != null) args.put("limit", Integer.toString(request.getLimit())); if (request.getFocus() != null && !JrawUtils.isFullname(request.getFocus())) args.put("comment", request.getFocus()); CommentSort sort = request.getSort(); if (sort == null) // Reddit sorts by confidence by default sort = CommentSort.CONFIDENCE; args.put("sort", sort.name().toLowerCase()); RestResponse response = execute(request() .path(String.format("/comments/%s", request.getId())) .query(args) .build()); return SubmissionSerializer.withComments(response.getJson(), sort); } /** * Gets a Subreddit * * @param name The subreddit's name * @return A new Subreddit object * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.SUBREDDIT_ABOUT) public Subreddit getSubreddit(String name) throws NetworkException { return execute(request() .endpoint(Endpoints.SUBREDDIT_ABOUT, name) .build()).as(Subreddit.class); } /** * Gets a random submission * @return A random submission * @throws NetworkException If the request was not successful */ public Submission getRandomSubmission() throws NetworkException { return getRandomSubmission(null); } /** * Gets a random submission from a specific subreddit * @param subreddit The subreddit to use * @return A random submission * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.RANDOM) public Submission getRandomSubmission(String subreddit) throws NetworkException { String path = JrawUtils.getSubredditPath(subreddit, "/random"); // Favor path() instead of endpoint() because we have already decided the path above RestResponse response = execute(request() .path(path) .build()); // We don't really know which sort will be used so just guess Reddit's default return SubmissionSerializer.withComments(response.getJson(), CommentSort.CONFIDENCE); } /** * Gets a random subreddit * @return A random subreddit * @throws NetworkException If the request was not successful */ public Subreddit getRandomSubreddit() throws NetworkException { return getSubreddit("random"); } /** * Gets the text displayed in the "submit link" form. * @param subreddit The subreddit to use * @return The text displayed int he "submit link" form * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.SUBMIT_TEXT) public String getSubmitText(String subreddit) throws NetworkException { String path = JrawUtils.getSubredditPath(subreddit, "/api/submit_text"); JsonNode node = execute(request() .path(path) .build()).getJson(); return node.get("submit_text").asText(); } /** * Gets a list of subreddit names by a topic. For example, the topic "programming" returns "programming", * "ProgrammerHumor", etc. * * @param topic The topic to use * @return A list of subreddits related to the given topic * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.SUBREDDITS_BY_TOPIC) public List<String> getSubredditsByTopic(String topic) throws NetworkException { List<String> subreddits = new ArrayList<>(); HttpRequest request = request() .endpoint(Endpoints.SUBREDDITS_BY_TOPIC) .query("query", topic) .build(); JsonNode node = execute(request).getJson(); for (JsonNode childNode : node) { subreddits.add(childNode.get("name").asText()); } return subreddits; } /** * Gets a list of subreddits that start with the given string. For instance, searching for "fun" would return * {@code ["funny", "FunnyandSad", "funnysigns", "funnycharts", ...]} * @param start The begging of the subreddit to search for * @param includeNsfw Whether to include NSFW subreddits. * @return A list of subreddits that starts with the given string * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.SEARCH_REDDIT_NAMES) public List<String> searchSubreddits(String start, boolean includeNsfw) throws NetworkException { List<String> subs = new ArrayList<>(); HttpRequest request = request() .endpoint(Endpoints.SEARCH_REDDIT_NAMES) .post(JrawUtils.mapOf( "query", start, "include_over_18", includeNsfw )).build(); JsonNode node = execute(request).getJson(); for (JsonNode name : node.get("names")) { subs.add(name.asText()); } return subs; } /** * Gets the contents of the CSS file affiliated with a given subreddit (or the front page) * @param subreddit The subreddit to use, or null for the front page. * @return The content of the raw CSS file * @throws NetworkException If the request was not successful or the Content-Type header was not {@code text/css}. */ @EndpointImplementation(Endpoints.STYLESHEET) public String getStylesheet(String subreddit) throws NetworkException { String path = JrawUtils.getSubredditPath(subreddit, "/stylesheet"); HttpRequest r = request() .path(path) .expected(MediaTypes.CSS.type()) .build(); RestResponse response = execute(r); return response.getRaw(); } public List<String> getTrendingSubreddits() { SubredditPaginator paginator = new SubredditPaginator(this, "trendingsubreddits"); paginator.setSorting(Sorting.NEW); Submission latest = paginator.next().get(0); String title = latest.getTitle(); String[] parts = title.split(" "); List<String> subreddits = new ArrayList<>(NUM_TRENDING_SUBREDDITS); for (String part : parts) { if (part.startsWith("/r/")) { String sub = part.substring("/r/".length()); // All but the last part will be formatted like "/r/{name},", so remove the commas sub = sub.replace(",", ""); subreddits.add(sub); } } return subreddits; } /** * Gets a list of similar subreddits based on the given ones. * * @param subreddits A list of subreddit names to act as the seed * @param omit An array of subreddits to explicitly avoid. These will not appear in the result. * @return A list of similar subreddit names * @throws NetworkException If the request was not successful. */ @EndpointImplementation(Endpoints.RECOMMEND_SR_SRNAMES) public List<String> getRecommendations(List<String> subreddits, List<String> omit) throws NetworkException { if (subreddits.isEmpty()) { return new ArrayList<>(); } RestResponse response = execute(request() .get() .endpoint(Endpoints.RECOMMEND_SR_SRNAMES, JrawUtils.join(subreddits)) .query("omit", omit != null ? JrawUtils.join(omit) : "") .build()); JsonNode json = JrawUtils.fromString(response.getRaw()); List<String> recommendations = new ArrayList<>(); for (JsonNode node : json) { recommendations.add(node.get("sr_name").asText()); } return recommendations; } /** * Gets a Listing of the given fullnames. Only submissions, comments, and subreddits will be returned * @param fullNames A list of fullnames * @return A Listing of Things * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.INFO) public Listing<Thing> get(String... fullNames) throws NetworkException { for (String name : fullNames) { if (!(name.startsWith(Model.Kind.LINK.getValue()) || name.startsWith(Model.Kind.COMMENT.getValue()) || name.startsWith(Model.Kind.SUBREDDIT.getValue()))) { // Send the data, but warn the developer JrawUtils.logger().warn("Name '{}' is not a submission, comment, or subreddit", name); } } return execute(request() .endpoint(Endpoints.INFO) .query("id", JrawUtils.join(fullNames)) .build()).asListing(Thing.class); } /** * Gets the trophies for the currently authenticated user * @throws NetworkException If the request was not successful */ public List<Award> getTrophies() throws NetworkException { return getTrophies(null); } /** * Gets the trophies for a specific user * @param username The username to find the trophies for * @throws NetworkException If the request was not successful * @return A list of awards */ @EndpointImplementation({ Endpoints.OAUTH_ME_TROPHIES, Endpoints.OAUTH_USER_USERNAME_TROPHIES }) public List<Award> getTrophies(String username) throws NetworkException { if (username == null) assertNotUserless(); username = authenticatedUser; RestResponse response = execute(request() .endpoint(Endpoints.OAUTH_USER_USERNAME_TROPHIES, username) .build()); List<Award> awards = new ArrayList<>(); for (JsonNode awardNode : response.getJson().get("data").get("trophies")) { awards.add(new Award(awardNode.get("data"))); } return awards; } /** * Gets the object that will help clients authenticate users with their Reddit app */ public OAuthHelper getOAuthHelper() { return authHelper; } /** * Gets the data that shows that this client has been authenticated */ public OAuthData getOAuthData() { return authData; } /** * Checks if the given endpoint is applicable for the current OAuth scopes */ public boolean isAuthorizedFor(Endpoints endpoint) { if (authData == null) return false; if (authData.getScopes().length > 0 && authData.getScopes()[0].equals("*")) { // All scopes return true; } for (String scope : authData.getScopes()) { if (scope.equalsIgnoreCase(endpoint.getScope())) { return true; } } return false; } /** * Checks if this RedditClient has an active session in which a user is authenticated. This will return true for * "normal" authentication, in which a user must login with their username/password to use this app, or false if * this client hasn't been authenticated yet or if using user-less (application only) OAuth. * * @return If there is an authenticated user */ public boolean hasActiveUserContext() { return authMethod != null && !authMethod.isUserless(); } private void assertNotUserless() { if (!hasActiveUserContext()) { throw new IllegalArgumentException("Not applicable for application-only authentication"); } } /** Returns how the user was authenticated */ public AuthenticationMethod getAuthenticationMethod() { return authMethod; } }
package net.raboof.leftpad; import java.util.function.Function; public class LeftPad implements Function<CharSequence, String> { private final int length; private final char fill; public LeftPad(int length, char fill) { this.length = length; this.fill = fill; } public LeftPad(int length) { this(length, ' '); } public String apply(CharSequence inputString) { StringBuilder output = new StringBuilder(); int i = -1; int len = length - inputString.length(); while (++i < len) { output.append(fill); } output.append(inputString); return output.toString(); } }
package net.gogo98901.codeCounter; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import net.gogo98901.codeCounter.Display.Config; import net.gogo98901.log.Log; public class Searcher { private List<String> paths = new ArrayList<String>(); private String path; private int lines, whiteSpace, files, dirs, filesExcluded, dirsExcluded; private Config config; public Searcher(Config config) { this.config = config; path = ""; } public void setPath(String path) { this.path = path; } public void search() { File filePath = new File(path); if (!filePath.exists()) { Log.info("Searching... Failed"); return; } paths.clear(); lines = 0; whiteSpace = 0; files = 0; dirs = 0; filesExcluded = 0; dirsExcluded = 0; File[] start = filePath.listFiles(); scan(start); files = paths.size(); Log.info("Searching... Finished"); Log.info("Found " + files + " files and " + dirs + " directories"); Log.info(lines + " lines, but with " + whiteSpace + " white space lines"); Log.info(""); } private void scan(File[] group) { for (File file : group) { // Log.info(file); if (file.isDirectory()) { if (checkDir("\\" + file.getName())) scan(file.listFiles()); } else if (checkFile(file.getName())) { count(file); paths.add(file.getAbsolutePath()); } } } private void count(File file) { try { BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath())); String data; while ((data = br.readLine()) != null) { if (data.length() == 0) whiteSpace++; lines++; } br.close(); } catch (Exception e) { Log.warn("Could not read '" + file.getAbsolutePath() + "'"); Log.stackTrace(e); } } private boolean checkFile(String file) { for (String type : config.getExcludeFiles()) { if (file.toLowerCase().endsWith(type.toLowerCase())) { filesExcluded++; return false; } } files++; return true; } private boolean checkDir(String dir) { for (String type : config.getExcludeDirectories()) { if (dir.toLowerCase().endsWith(type.toLowerCase())) { dirsExcluded++; return false; } } dirs++; return true; } public List<String> getPaths() { return paths; } public String getPath() { return path; } public int getLines() { return lines; } public int getWhiteSpace() { return whiteSpace; } public int getFiles() { return files; } public int getDirs() { return dirs; } public int getFilesExcluded() { return filesExcluded; } public int getDirsExcluded() { return dirsExcluded; } }
package com.redhat.ceylon.common; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; public class FileUtil { /** * Create a temporary directory * @param prefix The prefix to use for the directory name * @return a File pointing to the new directory * @throws RuntimeException if the directory could not be created */ public static File makeTempDir(String prefix){ try { File dir = File.createTempFile(prefix, ""); if(!dir.delete() || !dir.mkdirs()) { throw new RuntimeException("Failed to create tmp dir: "+dir); } return dir; } catch (IOException e) { throw new RuntimeException(e); } } /** * Delete a file or directory * @param f The file or directory to be deleted * @throws RuntimeException if the file or directory could not be deleted */ public static void delete(File f){ if (f.exists()) { if (f.isDirectory()) { for (File c : f.listFiles()) { delete(c); } } if (!f.delete()) { throw new RuntimeException("Failed to delete file: " + f.getPath()); } } } /** * Turns the given file into the best absolute representation available * @param file A file * @return A canonical or absolute file */ public static File absoluteFile(File file) { if (file != null) { try { file = file.getCanonicalFile(); } catch (IOException e) { file = file.getAbsoluteFile(); } } return file; } /** * Given a list of files and a "current working directory" * returns the list where the files that were relative are * now absolute after having the "CWD" applied to them * as their parent directory. Files in the list that were * already absolute are returned unmodified. * @param cwd The current working directory * @param files A list of files * @return A list of absolute files */ public static List<File> applyCwd(File cwd, List<File> files) { List<File> result = new ArrayList<>(files.size()); for (File f : files) { result.add(applyCwd(cwd, f)); } return result; } /** * Given a file and a "current working directory" returns * an absolute file after having the "CWD" applied to it * first as its parent directory. If the file was already * absolute to begin with it is returned unmodified. * @param cwd The current working directory * @param files A file * @return An absolute file */ public static File applyCwd(File cwd, File file) { if (cwd != null && file != null && !file.isAbsolute()) { File absCwd = absoluteFile(cwd); file = new File(absCwd, file.getPath()); } return file; } /** * Given a file and a possible parent folder returns * the file relative to the parent. If the file wasn't * relative to the parent it is returned unmodified. * @param root A possible parent file * @param file A file * @return A file relative to the parent */ public static File relativeFile(File root, File file) { if (root != null && file != null) { String absRoot = absoluteFile(root).getPath(); String absFile = absoluteFile(file).getPath(); if (absFile.startsWith(absRoot)) { String path = absFile.substring(absRoot.length()); if (path.startsWith(File.separator)) { path = path.substring(1); } file = new File(path); } } return file; } /** * Turns the given path, if absolute, into a path relative to the * VM's current working directory and leaves it alone otherwise * @param f The File to make relative * @return A relative File */ public static File relativeFile(File f) { if (f.isAbsolute()) { File cwd = new File("."); String path = f.getAbsolutePath(); if (path.startsWith(cwd.getAbsolutePath())) { path = "./" + path.substring(cwd.getAbsolutePath().length()); f = new File(path); } else if (path.startsWith(System.getProperty("user.home"))) { path = "~/" + path.substring(System.getProperty("user.home").length() + 1); f = new File(path); } } return f; } /** * The OS-specific directory where global application data can be stored. * As given by the {@code ceylon.config.dir} system property or the default * OS-dependent directory if the property doesn't exist. (/etc/ceylon on * Unix-like systems and %ALLUSERSPROFILE%/ceylon on WIndows) */ public static File getSystemConfigDir() throws IOException { File configDir = null; String ceylonConfigDir = System.getProperty(Constants.PROP_CEYLON_CONFIG_DIR); if (ceylonConfigDir != null) { configDir = new File(ceylonConfigDir); } else { if (OSUtil.isWindows()) { String appDir = System.getenv("ALLUSERSPROFILE"); if (appDir != null) { configDir = new File(appDir, "ceylon"); } } else if (OSUtil.isMac()) { configDir = new File("/etc/ceylon"); } else { // Assume a "regular" unix OS configDir = new File("/etc/ceylon"); } } return configDir; } /** * The installation directory. As given by the {@code ceylon.home} * system property */ public static File getInstallDir() { String ceylonHome = System.getProperty(Constants.PROP_CEYLON_HOME_DIR); if (ceylonHome != null) { return new File(ceylonHome); } else { return null; } } /** * The default user directory, that is {@code ~/.ceylon}. */ public static File getDefaultUserDir() { String userHome = System.getProperty("user.home"); return new File(userHome, ".ceylon"); } /** * The effective user directory, checking the {@code ceylon.user.dir} * system property then defaulting to {@link getDefaultUserDir}. */ public static File getUserDir() { String ceylonUserDir = System.getProperty(Constants.PROP_CEYLON_USER_DIR); if (ceylonUserDir != null) { return new File(ceylonUserDir); } else { return getDefaultUserDir(); } } /** * Returns the environment variable {@code PATH} as an array of {@code File}. * If the value was empty a array of size 0 will be returned. */ public static File[] getExecPath() { String path = System.getenv("PATH"); if (path != null && !path.isEmpty()) { String[] items = path.split(Pattern.quote(File.pathSeparator)); File[] result = new File[items.length]; for (int i = 0; i < items.length; i++) { result[i] = new File(items[i]); } return result; } else { return EMPTY_FILES; } } private static final String[] EMPTY_STRINGS = new String[0]; private static final File[] EMPTY_FILES = new File[0]; public static List<File> pathsToFileList(List<String> paths) { if (paths != null) { List<File> result = new ArrayList<File>(paths.size()); for (String s : paths) { result.add(new File(s)); } return result; } else { return Collections.emptyList(); } } public static File[] pathsToFileArray(String[] paths) { if (paths != null) { File[] result = new File[paths.length]; int idx = 0; for (String s : paths) { result[idx++] = new File(s); } return result; } else { return EMPTY_FILES; } } public static List<String> filesToPathList(List<File> files) { if (files != null) { List<String> result = new ArrayList<String>(files.size()); for (File f : files) { result.add(f.getPath()); } return result; } else { return Collections.emptyList(); } } public static String[] filesToPathArray(File[] files) { if (files != null) { String[] result = new String[files.length]; int idx = 0; for (File f : files) { result[idx++] = f.getPath(); } return result; } else { return EMPTY_STRINGS; } } /** * Given a file path and a list of "search paths" * returns the relative path of the file (relative to the one * search path that matched) * @param paths A list of folders * @param file A path to a file * @return The relative file path or the original file path if no match was found */ public static String relativeFile(Iterable<? extends File> paths, String file){ // make sure file is absolute and normalized file = absoluteFile(new File(file)).getPath(); // find the matching path prefix int srcDirLength = 0; for (File prefixFile : paths) { String absPrefix = absoluteFile(prefixFile).getPath(); if (file.startsWith(absPrefix) && absPrefix.length() > srcDirLength) { srcDirLength = absPrefix.length(); } } String path = file.substring(srcDirLength); if (path.startsWith(File.separator)) { path = path.substring(1); } return path; } /** * Given a file path and a list of "search paths" * returns the search path where the file was located * @param paths A list of folders * @param file A path to a file * @return The search path where the file was located or null */ public static File selectPath(Iterable<? extends File> paths, String file) { // make sure file is absolute and normalized file = absoluteFile(new File(file)).getPath(); // find the matching path prefix int srcDirLength = 0; File srcDirFile = null; for (File prefixFile : paths) { String absPrefix = absoluteFile(prefixFile).getPath() + File.separatorChar; if (file.startsWith(absPrefix) && absPrefix.length() > srcDirLength) { srcDirLength = absPrefix.length(); srcDirFile = prefixFile; } } return srcDirFile; } public static boolean sameFile(File a, File b) { if(a == null) return b == null; if(b == null) return false; try { String aPath = a.getCanonicalPath(); String bPath = b.getCanonicalPath(); return aPath.equals(bPath); } catch (IOException e) { return a.equals(b); } } // duplicated in /ceylon-compiler/src/com/redhat/ceylon/ant/Util.java because FileUtil is not in Ant's ClassPath public static boolean isChildOfOrEquals(File parent, File child){ // doing a single comparison is likely cheaper than walking up to the root try { String parentPath = parent.getCanonicalPath(); String childPath = child.getCanonicalPath(); if(parentPath.equals(childPath)) return true; // make sure we compare with a separator, otherwise /foo would be considered a parent of /foo-bar if(!parentPath.endsWith(File.separator)) parentPath += File.separator; return childPath.startsWith(parentPath); } catch (IOException e) { return false; } } /** * Returns true if the specified folder contains at least one regular file */ public static boolean containsFile(File dir) { try { final boolean[] found = new boolean[1]; found[0] = false; Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>(){ @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) throws IOException { if(Files.isRegularFile(path)){ found[0] = true; return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } }); return found[0]; } catch (IOException e) { throw new RuntimeException(e); } } /** * Recursively copy every file/folder from root to dest */ public static void copy(File root, File dest) throws IOException { if(root.isDirectory()){ for(File child : root.listFiles()){ File childDest = new File(dest, child.getName()); if(child.isDirectory()){ if(!childDest.mkdirs()) throw new IOException("Failed to create dir "+childDest.getPath()); copy(child, childDest); }else{ Files.copy(child.toPath(), childDest.toPath()); } } }else{ File childDest = new File(dest, root.getName()); Files.copy(root.toPath(), childDest.toPath()); } } }
package nl.sense_os.platform; import java.util.Date; import nl.sense_os.service.ISenseService; import nl.sense_os.service.ISenseServiceCallback; import nl.sense_os.service.R; import nl.sense_os.service.commonsense.SenseApi; import nl.sense_os.service.commonsense.SensorRegistrator; import nl.sense_os.service.constants.SensorData.DataPoint; import nl.sense_os.service.storage.LocalStorage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.database.Cursor; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * A proxy class that acts as a high-level interface to the sense Android library. By instantiating * this class you bind (and start if needed) the sense service. You can then use the high level * methods of this class, and/or get the service object to work directly with the sense service. */ public class SensePlatform { private static final String TAG = "SensePlatform"; /** * Context of the enclosing application. */ private final Context context; /** * Keeps track of the service binding state. */ private boolean isServiceBound = false; /** * Interface for the SenseService. Gets instantiated by {@link #serviceConn}. */ private ISenseService service; /** * Service connection to handle connection with the Sense service. Manages * the <code>service</code> field when the service is connected or * disconnected. */ private class SenseServiceConn implements ServiceConnection { private final ServiceConnection serviceConnection; public SenseServiceConn(ServiceConnection serviceConnection) { this.serviceConnection = serviceConnection; } @Override public void onServiceConnected(ComponentName className, IBinder binder) { Log.v(TAG, "Bound to Sense Platform service..."); service = ISenseService.Stub.asInterface(binder); isServiceBound = true; // notify the external service connection if (serviceConnection != null) { serviceConnection.onServiceConnected(className, binder); } } @Override public void onServiceDisconnected(ComponentName className) { Log.v(TAG, "Sense Platform service disconnected..."); /* * this is not called when the service is stopped, only when it is suddenly killed! */ service = null; isServiceBound = false; // notify the external service connection if (serviceConnection != null) { serviceConnection.onServiceDisconnected(className); } } } /** * Callback for events for the binding with the Sense service */ private final ServiceConnection serviceConn; /** * Binds to the Sense service, creating it if necessary. */ public void bindToSenseService() { // start the service if it was not running already if (!isServiceBound) { Log.v(TAG, "Try to bind to Sense Platform service"); final Intent serviceIntent = new Intent(context.getString(R.string.action_sense_service)); boolean bindResult = context.bindService(serviceIntent, serviceConn, Context.BIND_AUTO_CREATE); Log.v(TAG, "Result: " + bindResult); } else { // already bound } } /** * @param context * Context that the Sense service will bind to. * @param serviceConnection * Optional. ServiceConnection that handles callbacks about the binding with the * service. */ public SensePlatform(Context context, ServiceConnection serviceConnection) { this.serviceConn = new SenseServiceConn(serviceConnection); this.context = context; bindToSenseService(); } public void flushData() throws IllegalStateException { checkSenseService(); Intent flush = new Intent(context.getString(R.string.action_sense_send_data)); context.startService(flush); } public void flushDataAndBlock() throws IllegalStateException { checkSenseService(); flushData(); // TODO: block till flush finishes or returns an error } public void login(String user, String password, ISenseServiceCallback.Stub callback) throws IllegalStateException, RemoteException { checkSenseService(); service.changeLogin(user, SenseApi.hashPassword(password), callback); } public void registerUser(String username, String password, String email, String address, String zipCode, String country, String firstName, String surname, String mobileNumber, ISenseServiceCallback.Stub callback) throws IllegalStateException, RemoteException { checkSenseService(); service.register(username, password, email, address, zipCode, country, firstName, surname, mobileNumber, callback); } public void addDataPoint(String sensorName, String displayName, String description, String dataType, String value, long timestamp) throws IllegalStateException { checkSenseService(); // register the sensor SensorRegistrator registrator = new TrivialSensorRegistrator(context); registrator.checkSensor(sensorName, displayName, dataType, description, value, null, null); // send data point String action = context.getString(nl.sense_os.service.R.string.action_sense_new_data); Intent intent = new Intent(action); intent.putExtra(DataPoint.SENSOR_NAME, sensorName); intent.putExtra(DataPoint.DISPLAY_NAME, displayName); intent.putExtra(DataPoint.SENSOR_DESCRIPTION, description); intent.putExtra(DataPoint.DATA_TYPE, dataType); intent.putExtra(DataPoint.VALUE, value); intent.putExtra(DataPoint.TIMESTAMP, timestamp); context.startService(intent); } public JSONArray getData(String sensorName, boolean onlyFromDevice, int nrLastPoints) throws IllegalStateException { checkSenseService(); Log.v(TAG, "getRemoteValues('" + sensorName + "', " + onlyFromDevice + ")"); JSONArray result = new JSONArray(); try { // select remote url Uri uri = Uri.parse("content://" + context.getString(R.string.local_storage_authority) + DataPoint.CONTENT_REMOTE_URI_PATH); // get the data // TODO: use nrLastPoints result = getValues(sensorName, onlyFromDevice, uri); } catch (JSONException e) { e.printStackTrace(); } return result; } public void giveFeedback(String state, Date from, Date to, String label) throws IllegalStateException { checkSenseService(); // TODO: implement } /** * @return The Sense service instance */ public ISenseService service() { return service; } /** * Return the intent for new sensor data. This can be used to subscribe to new data. * * @return The intent action for new sensor data */ public String newDataAction() { return context.getString(R.string.action_sense_new_data); } /** * Gets array of values from the LocalStorage * * @param sensorName * Name of the sensor to get values from. * @param onlyFromDevice * If true this function only looks for sensors attached to this * device. * @param uri * The uri to get data from, can be either local or remote. * @return JSONArray with values for the sensor with the selected name and * device * @throws JSONException */ private JSONArray getValues(String sensorName, boolean onlyFromDevice, Uri uri) throws JSONException { Cursor cursor = null; JSONArray result = new JSONArray(); String deviceUuid = onlyFromDevice ? SenseApi.getDefaultDeviceUuid(context) : null; String[] projection = new String[] { DataPoint.TIMESTAMP, DataPoint.VALUE }; String selection = DataPoint.SENSOR_NAME + " = '" + sensorName + "'"; if (null != deviceUuid) { selection += " AND " + DataPoint.DEVICE_UUID + "='" + deviceUuid + "'"; } String[] selectionArgs = null; String sortOrder = null; try { cursor = LocalStorage.getInstance(context).query(uri, projection, selection, selectionArgs, sortOrder); if (null != cursor && cursor.moveToFirst()) { while (!cursor.isAfterLast()) { JSONObject val = new JSONObject(); val.put("timestamp", cursor.getString(cursor.getColumnIndex(DataPoint.TIMESTAMP))); val.put("value", cursor.getString(cursor.getColumnIndex(DataPoint.VALUE))); result.put(val); cursor.moveToNext(); } } } catch (JSONException je) { throw je; } finally { if (cursor != null) cursor.close(); } return result; } private void checkSenseService() throws IllegalStateException { if (service == null) { throw new IllegalStateException("Sense service not bound"); } } }
package org.basex.tests.w3c; import static org.basex.tests.w3c.QT3Constants.*; import java.util.*; import org.basex.core.*; import org.basex.tests.bxapi.*; import org.basex.tests.bxapi.xdm.*; import org.basex.util.list.*; final class QT3Env { /** Namespaces: prefix, uri. */ final ArrayList<HashMap<String, String>> namespaces; /** Sources: role, file, validation, uri, xml:id. */ final ArrayList<HashMap<String, String>> sources; /** Resources. */ final ArrayList<HashMap<String, String>> resources; /** Parameters: name, as, select, declared. */ final ArrayList<HashMap<String, String>> params; /** Decimal Formats: decimal-separator, grouping-separator, digit, pattern-separator, infinity, NaN, per-mille, minus-sign, name, percent, zero-digit. */ final ArrayList<HashMap<String, String>> formats; /** Schemas: uri, file, xml:id. */ final HashMap<String, String> schemas; /** Collations: uri, default. */ final HashMap<String, String> collations; /** Static Base URI: uri. */ final String baseURI; /** Name. */ final String name; /** Collection uri. */ final String collURI; /** Collection context flag. */ final boolean collContext; /** Collection sources. */ final StringList collSources; /** * Constructor. * @param ctx database context * @param env environment item */ QT3Env(final Context ctx, final XdmValue env) { name = XQuery.string('@' + NNAME, env, ctx); sources = list(ctx, env, SOURCE); resources = list(ctx, env, RESOURCE); params = list(ctx, env, PARAM); namespaces = list(ctx, env, NAMESPACE); formats = list(ctx, env, DECIMAL_FORMAT); ArrayList<HashMap<String, String>> al = list(ctx, env, SCHEMA); schemas = al.isEmpty() ? null : al.get(0); al = list(ctx, env, COLLATION); collations = al.isEmpty() ? null : al.get(0); final String uri = string(STATIC_BASE_URI, ctx, env); baseURI = "#UNDEFINED".equals(uri) ? "" : uri; // collections collURI = XQuery.string("*:collection/@uri", env, ctx); /** * Returns a list of all attributes of the specified element in a map. * @param ctx database context * @param env root element * @param elem element to be parsed * @return map list */ static ArrayList<HashMap<String, String>> list(final Context ctx, final XdmValue env, final String elem) { final ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); final XQuery query = new XQuery("*:" + elem, ctx).context(env); for(final XdmItem it : query) list.add(map(ctx, it)); query.close(); return list; } /** * Returns all attributes of the specified element in a map. * @param ctx database context * @param env root element * @return map */ static HashMap<String, String> map(final Context ctx, final XdmValue env) { final HashMap<String, String> map = new HashMap<String, String>(); final XQuery query = new XQuery("@*", ctx).context(env); for(final XdmItem it : query) map.put(it.getName(), it.getString()); query.close(); return map; } /** * Returns a single attribute string. * @param elm name of element * @param ctx database context * @param env root element * @return map */ static String string(final String elm, final Context ctx, final XdmValue env) { String value = null; final XQuery query = new XQuery("*:" + elm, ctx).context(env); final XdmItem it = query.next(); if(it != null) { final XQuery qattr = new XQuery("string(@*)", ctx).context(it); value = qattr.next().getString(); qattr.close(); } query.close(); return value; } }
package opendap.bes.dap2Responders; import opendap.bes.Version; import opendap.bes.dap4Responders.Dap4Responder; import opendap.bes.dap4Responders.MediaType; import opendap.coreServlet.OPeNDAPException; import opendap.coreServlet.ReqInfo; import opendap.coreServlet.RequestCache; import opendap.coreServlet.Scrub; import opendap.dap.User; import org.slf4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; /** * Responder that transmits JSON encoded DAP2 data to the client. */ public class CovJson extends Dap4Responder { private Logger log; private static String defaultRequestSuffix = ".covjson"; public CovJson(String sysPath, BesApi besApi, boolean addTypeSuffixToDownloadFilename) { this(sysPath, null, defaultRequestSuffix, besApi, addTypeSuffixToDownloadFilename); } public CovJson(String sysPath, String pathPrefix, String requestSuffixRegex, BesApi besApi, boolean addTypeSuffixToDownloadFilename) { super(sysPath, pathPrefix, requestSuffixRegex, besApi); log = org.slf4j.LoggerFactory.getLogger(this.getClass()); addTypeSuffixToDownloadFilename(addTypeSuffixToDownloadFilename); setServiceRoleId("http://services.opendap.org/dap2/data/covjson"); setServiceTitle("CovJson encoded DAP2 data."); setServiceDescription("CovJson representation of the DAP2 Data Response object."); setServiceDescriptionLink("http://docs.opendap.org/index.php/DAP4:_Specification_Volume_2#DAP2:_CovJson_Data_Service"); setNormativeMediaType(new opendap.http.mediaTypes.Json(getRequestSuffix())); log.debug("Using RequestSuffix: '{}'", getRequestSuffix()); log.debug("Using CombinedRequestSuffixRegex: '{}'", getCombinedRequestSuffixRegex()); } public boolean isDataResponder(){ return true; } public boolean isMetadataResponder(){ return false; } @Override public boolean matches(String relativeUrl, boolean checkWithBes){ return super.matches(relativeUrl,checkWithBes); } @Override public void sendNormativeRepresentation(HttpServletRequest request, HttpServletResponse response) throws Exception { String requestedResourceId = ReqInfo.getLocalUrl(request); // String xmlBase = getXmlBase(request); String constraintExpression = ReqInfo.getConstraintExpression(request); String resourceID = getResourceId(requestedResourceId, false); BesApi besApi = getBesApi(); log.debug("Sending {} for dataset: {}",getServiceTitle(),resourceID); response.setHeader("Content-Disposition", " attachment; filename=\"" +getDownloadFileName(resourceID)+"\""); Version.setOpendapMimeHeaders(request, response, besApi); MediaType responseMediaType = getNormativeMediaType(); // Stash the Media type in case there's an error. That way the error handler will know how to encode the error. RequestCache.put(OPeNDAPException.ERROR_RESPONSE_MEDIA_TYPE_KEY, responseMediaType); response.setContentType(responseMediaType.getMimeType()); Version.setOpendapMimeHeaders(request, response, besApi); response.setHeader("Content-Description", getNormativeMediaType().getMimeType()); User user = new User(request); OutputStream os = response.getOutputStream(); besApi.writeDap2DataAsCovJson( resourceID, constraintExpression, "3.2", user.getMaxResponseSize(), os); os.flush(); log.debug("Sent {}",getServiceTitle()); } }
package org.bdgp.OpenHiCAMM.DB; import java.io.File; import org.bdgp.OpenHiCAMM.Dao; import org.bdgp.OpenHiCAMM.Util; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.MMStudio; import org.micromanager.acquisition.MMAcquisition; import org.micromanager.utils.MMScriptException; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable public class Acquisition { @DatabaseField(generatedId=true, canBeNull=false) private int id; @DatabaseField(canBeNull=false,dataType=DataType.LONG_STRING) private String name; @DatabaseField(canBeNull=false,dataType=DataType.LONG_STRING) private String prefix; @DatabaseField(canBeNull=false,dataType=DataType.LONG_STRING) private String directory; public Acquisition() {} public Acquisition (String name, String prefix, String directory) { this.name = name; this.prefix = prefix; this.directory = directory; } public int getId() {return this.id;} public String getName() {return this.name;} public String getPrefix() {return this.prefix;} public String getDirectory() { return this.directory; } public MMAcquisition getAcquisition(Dao<Acquisition> acquisitionDao) { return this.getAcquisition(acquisitionDao, true); } public MMAcquisition getAcquisition(Dao<Acquisition> acquisitionDao, boolean existing) { if (existing) { MMStudio mmstudio = MMStudio.getInstance(); try { MMAcquisition acquisition = mmstudio.getAcquisitionWithName(this.name); JSONObject summaryMetadata = acquisition.getImageCache().getSummaryMetadata(); if (summaryMetadata != null && summaryMetadata.has("Directory") && summaryMetadata.get("Directory").toString().equals(this.directory) && summaryMetadata.has("Prefix") && summaryMetadata.get("Prefix").toString().equals(this.prefix)) { return acquisition; } } catch (JSONException e) {throw new RuntimeException(e);} catch (MMScriptException e) { // this means there was no acquisition loaded with this name, that's OK. Let's try to // open the acquisition next... } try { File acquisitionPath = new File(this.directory, this.prefix); if (!acquisitionPath.exists()) throw new RuntimeException(String.format( "Acquisition path %s does not exist!", acquisitionPath.getPath())); this.name = mmstudio.openAcquisitionData(acquisitionPath.getPath(), false, false); MMAcquisition acquisition = mmstudio.getAcquisitionWithName(this.name); if (acquisitionDao != null) { acquisitionDao.update(this, "id"); } return acquisition; } catch (MMScriptException e1) {throw new RuntimeException(e1);} } else { try { MMAcquisition acquisition = new MMAcquisition(this.name, this.directory, false, true, false); acquisition.initialize(); // update the prefix metadata JSONObject summaryMetadata = acquisition.getSummaryMetadata(); if (summaryMetadata != null && summaryMetadata.has("Prefix")) { this.prefix = summaryMetadata.get("Prefix").toString(); if (acquisitionDao != null) { acquisitionDao.update(this, "id"); } } return acquisition; } catch (JSONException e) {throw new RuntimeException(e);} catch (MMScriptException e) {throw new RuntimeException(e);} } } public MMAcquisition getAcquisition() { return this.getAcquisition(null); } public String toString() { return String.format("%s(id=%d, name=%s, prefix=%s, directory=%s)", this.getClass().getSimpleName(), this.id, Util.escape(this.name), Util.escape(this.prefix), Util.escape(this.directory)); } }
package org.lantern; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.ArrayList; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StatsSimulator { private final Logger log = LoggerFactory.getLogger(getClass()); private final ArrayList<String> IPS = new ArrayList<String>(); public StatsSimulator() { populateIps(); } private void populateIps() { addIps("77.69.128.", 10); // Bahrain addIps("58.14.0.", 200); // China addIps("190.6.64.", 60); // Cuba //addIps("196.200.96.", 100); // Eritrea addIps("213.55.64.", 50); // Ethiopia addIps("46.36.195.", 100); // Indonesia addIps("212.95.136.", 100); // Iran addIps("49.1.0.", 120); // South Korea addIps("203.81.64.", 100); // Myanmar addIps("175.45.176.", 100); // North Korea addIps("46.36.195.", 80); // Oman addIps("46.36.195.", 80); // Qatar addIps("39.32.0.", 80); // Pakistan addIps("62.3.0.", 80); // Saudi Arabia addIps("31.201.1.", 60); // Sudan addIps("78.110.96.", 45); // Syria addIps("94.102.176.", 80); // Turkmenistan addIps("85.115.64.", 40); // United Arab Emirates addIps("62.209.128.", 60); // Uzbekistan addIps("58.186.0.", 70); // Vietnam addIps("82.114.160.", 100); // Yemen } private void addIps(final String base, final int num) { for (int i = 0; i < num; i++) { IPS.add(base+i); } } public void start() { final Thread sim = new Thread(new Runnable() { @Override public void run() { while (true) { addData(); final double rand = Math.random(); final long millis = (long) (rand * 1200); try { Thread.sleep(800 + millis); } catch (final InterruptedException e) { log.error("Sleep interrupted?", e); } } } }, "Stats-Simulator-Thread"); sim.setDaemon(true); sim.start(); } protected void addData() { final double newCountries = Math.random(); final int nc = (int) (newCountries * 3); for (int i = 0; i < nc; i++) { final String ip = randomIp(); final long bytes = (long) (Math.random() * 10000); LanternHub.statsTracker().incrementProxiedRequests(); LanternHub.statsTracker().addBytesProxied(bytes, new ChannelAdapter(ip)); } } private String randomIp() { final int index = (int) (Math.random() * (IPS.size() - 1)); return IPS.get(index); } private static class ChannelAdapter implements Channel { private final InetSocketAddress remoteAddress; private ChannelAdapter(final String address) { this.remoteAddress = new InetSocketAddress(address, 2781); } @Override public int compareTo(Channel o) { // TODO Auto-generated method stub return 0; } @Override public Integer getId() { // TODO Auto-generated method stub return null; } @Override public ChannelFactory getFactory() { // TODO Auto-generated method stub return null; } @Override public Channel getParent() { // TODO Auto-generated method stub return null; } @Override public ChannelConfig getConfig() { // TODO Auto-generated method stub return null; } @Override public ChannelPipeline getPipeline() { // TODO Auto-generated method stub return null; } @Override public boolean isOpen() { // TODO Auto-generated method stub return false; } @Override public boolean isBound() { // TODO Auto-generated method stub return false; } @Override public boolean isConnected() { // TODO Auto-generated method stub return false; } @Override public SocketAddress getLocalAddress() { // TODO Auto-generated method stub return null; } @Override public SocketAddress getRemoteAddress() { return remoteAddress; } @Override public ChannelFuture write(Object message) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture bind(SocketAddress localAddress) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture connect(SocketAddress remoteAddress) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture disconnect() { // TODO Auto-generated method stub return null; } @Override public ChannelFuture unbind() { // TODO Auto-generated method stub return null; } @Override public ChannelFuture close() { // TODO Auto-generated method stub return null; } @Override public ChannelFuture getCloseFuture() { // TODO Auto-generated method stub return null; } @Override public int getInterestOps() { // TODO Auto-generated method stub return 0; } @Override public boolean isReadable() { // TODO Auto-generated method stub return false; } @Override public boolean isWritable() { // TODO Auto-generated method stub return false; } @Override public ChannelFuture setInterestOps(int interestOps) { // TODO Auto-generated method stub return null; } @Override public ChannelFuture setReadable(boolean readable) { // TODO Auto-generated method stub return null; } @Override public Object getAttachment() { // TODO Auto-generated method stub return null; } @Override public void setAttachment(Object arg0) { // TODO Auto-generated method stub } } }
package org.bdgp.OpenHiCAMM; import java.awt.Color; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.nio.file.Paths; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.bdgp.OpenHiCAMM.DB.Acquisition; import org.bdgp.OpenHiCAMM.DB.Config; import org.bdgp.OpenHiCAMM.DB.Image; import org.bdgp.OpenHiCAMM.DB.ModuleConfig; import org.bdgp.OpenHiCAMM.DB.Pool; import org.bdgp.OpenHiCAMM.DB.PoolSlide; import org.bdgp.OpenHiCAMM.DB.ROI; import org.bdgp.OpenHiCAMM.DB.Slide; import org.bdgp.OpenHiCAMM.DB.SlidePosList; import org.bdgp.OpenHiCAMM.DB.Task; import org.bdgp.OpenHiCAMM.DB.TaskConfig; import org.bdgp.OpenHiCAMM.DB.TaskDispatch; import org.bdgp.OpenHiCAMM.DB.WorkflowModule; import org.bdgp.OpenHiCAMM.DB.Task.Status; import org.bdgp.OpenHiCAMM.Modules.ROIFinderDialog; import org.bdgp.OpenHiCAMM.Modules.SlideImager; import org.bdgp.OpenHiCAMM.Modules.SlideImagerDialog; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module; import org.bdgp.OpenHiCAMM.Modules.Interfaces.Report; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.MMStudio; import org.micromanager.api.MultiStagePosition; import org.micromanager.api.PositionList; import org.micromanager.api.StagePosition; import org.micromanager.utils.ImageLabelComparator; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMSerializationException; import com.google.common.base.Charsets; import com.google.common.io.Resources; import ij.IJ; import ij.ImagePlus; import ij.gui.ImageRoi; import ij.gui.NewImage; import ij.gui.Overlay; import ij.gui.Roi; import ij.io.FileSaver; import ij.process.Blitter; import ij.process.ImageProcessor; import javafx.scene.web.WebEngine; import mmcorej.CMMCore; import static org.bdgp.OpenHiCAMM.Util.where; import static org.bdgp.OpenHiCAMM.Tag.T.*; public class WorkflowReport implements Report { public static final int SLIDE_PREVIEW_WIDTH = 1280; public static final int ROI_GRID_PREVIEW_WIDTH = 425; private WorkflowRunner workflowRunner; private WebEngine webEngine; private String reportDir; private String reportIndex; private Integer prevPoolSlideId; private Map<Integer,Boolean> isLoaderInitialized; private Map<Integer,MultiStagePosition> msps; private Map<Integer,Map<String,ModuleConfig>> moduleConfig; private Map<Integer,Map<String,TaskConfig>> taskConfig; public void jsLog(String message) { IJ.log(String.format("[WorkflowReport:js] %s", message)); } public void log(String message, Object... args) { IJ.log(String.format("[WorkflowReport] %s", String.format(message, args))); } @Override public void initialize(WorkflowRunner workflowRunner, WebEngine webEngine, String reportDir, String reportIndex) { this.workflowRunner = workflowRunner; this.webEngine = webEngine; this.reportDir = reportDir; this.reportIndex = reportIndex; isLoaderInitialized = new HashMap<Integer,Boolean>(); this.msps = new HashMap<>(); this.moduleConfig = new HashMap<>(); this.taskConfig = new HashMap<>(); } private ModuleConfig getModuleConfig(int id, String key) { Map<String,ModuleConfig> confs = moduleConfig.get(id); if (confs == null) return null; return confs.get(key); } private TaskConfig getTaskConfig(int id, String key) { Map<String,TaskConfig> confs = taskConfig.get(id); if (confs == null) return null; return confs.get(key); } @Override public void runReport() { Dao<Pool> poolDao = this.workflowRunner.getWorkflowDb().table(Pool.class); Dao<PoolSlide> psDao = this.workflowRunner.getWorkflowDb().table(PoolSlide.class); // cache the module config log("Caching the module config..."); for (ModuleConfig moduleConf : this.workflowRunner.getModuleConfig().select()) { moduleConfig.putIfAbsent(moduleConf.getId(), new HashMap<>()); moduleConfig.get(moduleConf.getId()).put(moduleConf.getKey(), moduleConf); } // cache the task config log("Caching the task config..."); for (TaskConfig taskConf : this.workflowRunner.getTaskConfig().select()) { taskConfig.putIfAbsent(taskConf.getId(), new HashMap<>()); taskConfig.get(taskConf.getId()).put(taskConf.getKey(), taskConf); } // get the MSP from the task config PositionList posList = new PositionList(); List<TaskConfig> mspConfs = this.workflowRunner.getTaskConfig().select( where("key","MSP")); log("Creating task->MSP table for %s tasks...", mspConfs.size()); for (TaskConfig mspConf : mspConfs) { try { JSONObject posListJson = new JSONObject(). put("POSITIONS", new JSONArray().put(new JSONObject(mspConf.getValue()))). put("VERSION", 3). put("ID","Micro-Manager XY-position list"); posList.restore(posListJson.toString()); MultiStagePosition msp = posList.getPosition(0); msps.put(mspConf.getId(), msp); } catch (JSONException | MMSerializationException e) {throw new RuntimeException(e);} } // Find SlideImager modules where there is no associated posListModuleId module config // This is the starting SlideImager module. int[] reportCounter = new int[]{1}; Map<String,Runnable> runnables = new LinkedHashMap<String,Runnable>(); Tag index = Html().indent().with(()->{ Head().with(()->{ try { // CSS Style().raw(Resources.toString(Resources.getResource("bootstrap.min.css"), Charsets.UTF_8)); Style().raw(Resources.toString(Resources.getResource("bootstrap-theme.min.css"), Charsets.UTF_8)); Style().raw(Resources.toString(Resources.getResource("jquery.powertip.min.css"), Charsets.UTF_8)); // Javascript Script().raw(Resources.toString(Resources.getResource("jquery-2.1.4.min.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("bootstrap.min.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("jquery.maphilight.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("jquery.powertip.min.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("notify.min.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("WorkflowReport.js"), Charsets.UTF_8)); } catch (Exception e) {throw new RuntimeException(e);} }); Body().with(()->{ SLIDE_IMAGERS: for (Config canImageSlides : this.workflowRunner.getModuleConfig().select( where("key","canImageSlides"). and("value", "yes"))) { WorkflowModule slideImager = this.workflowRunner.getWorkflow().selectOne( where("id", canImageSlides.getId())); if (slideImager != null && getModuleConfig(slideImager.getId(), "posListModule") == null) { log("Working on slideImager: %s", slideImager); // get the loader module Integer loaderModuleId = slideImager.getParentId(); while (loaderModuleId != null) { WorkflowModule loaderModule = this.workflowRunner.getWorkflow().selectOneOrDie( where("id", loaderModuleId)); Config canLoadSlides = getModuleConfig(loaderModule.getId(), "canLoadSlides"); if (canLoadSlides != null && "yes".equals(canLoadSlides.getValue())) { log("Using loaderModule: %s", loaderModule); Config poolIdConf = getModuleConfig(loaderModule.getId(), "poolId"); if (poolIdConf != null) { Pool pool = poolDao.selectOneOrDie(where("id", poolIdConf.getValue())); List<PoolSlide> pss = psDao.select(where("poolId", pool.getId())); if (!pss.isEmpty()) { for (PoolSlide ps : pss) { String reportFile = String.format("report%03d.%s.cartridge%d.pos%02d.slide%05d.html", reportCounter[0]++, slideImager.getName(), ps.getCartridgePosition(), ps .getSlidePosition(), ps.getSlideId()); P().with(()->{ A(String.format("Module %s, Slide %s", slideImager.getName(), ps)). attr("href", reportFile); }); Integer loaderModuleId_ = loaderModuleId; runnables.put(reportFile, ()->{ log("Calling runReport(startModule=%s, poolSlide=%s, loaderModuleId=%s)", slideImager, ps, loaderModuleId_); WorkflowModule lm = this.workflowRunner.getWorkflow().selectOneOrDie(where("id", loaderModuleId_)); runReport(slideImager, ps, lm, reportFile); }); } continue SLIDE_IMAGERS; } } } loaderModuleId = loaderModule.getParentId(); } String reportFile = String.format("report%03d.%s.html", reportCounter[0]++, slideImager.getName()); P().with(()->{ A(String.format("Module %s", slideImager)). attr("href", reportFile); }); runnables.put(reportFile, ()->{ log("Calling runReport(startModule=%s, poolSlide=null, loaderModuleId=null)", slideImager); runReport(slideImager, null, null, reportFile); }); } } }); }); ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); List<Future<?>> futures = new ArrayList<>(); for (Map.Entry<String,Runnable> entry : runnables.entrySet()) { String reportFile = entry.getKey(); Runnable runnable = entry.getValue(); if (!new File(reportDir, reportFile).exists()) { futures.add(pool.submit(()->{ Html().indent().with(()->{ Head().with(()->{ try { // CSS Style().raw(Resources.toString(Resources.getResource("bootstrap.min.css"), Charsets.UTF_8)); Style().raw(Resources.toString(Resources.getResource("bootstrap-theme.min.css"), Charsets.UTF_8)); Style().raw(Resources.toString(Resources.getResource("jquery.powertip.min.css"), Charsets.UTF_8)); // Javascript Script().raw(Resources.toString(Resources.getResource("jquery-2.1.4.min.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("bootstrap.min.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("jquery.maphilight.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("jquery.powertip.min.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("notify.min.js"), Charsets.UTF_8)); Script().raw(Resources.toString(Resources.getResource("WorkflowReport.js"), Charsets.UTF_8)); } catch (Exception e) {throw new RuntimeException(e);} }); Body().with(()->{ runnable.run(); }); }).write(new File(reportDir, reportFile)); })); } } for (Future<?> f : futures) { try { f.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } // write the index last index.write(new File(this.reportDir, this.reportIndex)); } private void runReport(WorkflowModule startModule, PoolSlide poolSlide, WorkflowModule loaderModule, String reportFile) { log("Called runReport(startModule=%s, poolSlide=%s)", startModule, poolSlide); Dao<Slide> slideDao = this.workflowRunner.getWorkflowDb().table(Slide.class); Dao<Image> imageDao = this.workflowRunner.getWorkflowDb().table(Image.class); Dao<Acquisition> acqDao = this.workflowRunner.getWorkflowDb().table(Acquisition.class); Dao<ROI> roiDao = this.workflowRunner.getWorkflowDb().table(ROI.class); Dao<SlidePosList> slidePosListDao = this.workflowRunner.getWorkflowDb().table(SlidePosList.class); // get a ROI ID -> moduleId(s) mapping from the slideposlist Map<Integer, Set<Integer>> roiModules = new HashMap<>(); for (SlidePosList spl : slidePosListDao.select()) { if (spl.getModuleId() != null) { PositionList posList = spl.getPositionList(); for (MultiStagePosition msp : posList.getPositions()) { String roiIdConf = msp.getProperty("ROI"); if (roiIdConf != null) { Integer roiId = new Integer(roiIdConf); if (!roiModules.containsKey(roiId)) roiModules.put(roiId, new HashSet<>()); roiModules.get(roiId).add(spl.getModuleId()); } } } } // get the associated hi res slide imager modules for each ROI finder module // ROIFinder module ID -> List of associated imager module IDs Map<String,Set<String>> roiImagers = new HashMap<>(); for (Task task : workflowRunner.getTaskStatus().select( where("moduleId", startModule.getId()))) { TaskConfig imageIdConf = getTaskConfig(task.getId(), "imageId"); if (imageIdConf != null) { for (ROI roi : roiDao.select(where("imageId", imageIdConf.getValue()))) { Set<Integer> roiModuleSet = roiModules.get(roi.getId()); if (roiModuleSet == null) { log(String.format("No ROI modules found for ROI %s!", roi)); } else { for (Integer roiModuleId : roiModuleSet) { WorkflowModule roiModule = this.workflowRunner.getWorkflow().selectOne(where("id", roiModuleId)); if (roiModule != null) { for (ModuleConfig posListModuleConf : this.workflowRunner.getModuleConfig().select( where("key", "posListModule"). and("value", roiModule.getName()))) { Config canImageSlides = getModuleConfig(posListModuleConf.getId(), "canImageSlides"); if (canImageSlides != null && "yes".equals(canImageSlides.getValue())) { WorkflowModule imagerModule = this.workflowRunner.getWorkflow().selectOne( where("id", posListModuleConf.getId())); if (imagerModule != null) { if (!roiImagers.containsKey(roiModule.getName())) roiImagers.put(roiModule.getName(), new HashSet<>()); roiImagers.get(roiModule.getName()).add(imagerModule.getName()); } } } } } } } } } // display the title Slide slide; String slideName; if (poolSlide != null) { slide = slideDao.selectOneOrDie(where("id", poolSlide.getSlideId())); slideName = slide.getName(); String title = String.format("SlideImager %s, Slide %s, Pool %d, Cartridge %d, Slide Position %d", startModule.getName(), slide.getName(), poolSlide.getPoolId(), poolSlide.getCartridgePosition(), poolSlide.getSlidePosition()); P().with(()->{ A("Back to Index Page").attr("href", this.reportIndex); }); A().attr("name", String.format("report-%s-PS%s", startModule.getName(), poolSlide.getId())); H1().text(title); log("title = %s", title); } else { slide = null; slideName = "slide"; String title = String.format("SlideImager %s", startModule.getName()); A().attr("name", String.format("report-%s", startModule.getName())); H1().text(title); log("title = %s", title); } // get the pixel size of this slide imager config Config pixelSizeConf = getModuleConfig(startModule.getId(), "pixelSize"); Double pixelSize = pixelSizeConf != null? new Double(pixelSizeConf.getValue()) : SlideImagerDialog.DEFAULT_PIXEL_SIZE_UM; log("pixelSize = %f", pixelSize); // get invertXAxis and invertYAxis conf values Config invertXAxisConf = getModuleConfig(startModule.getId(), "invertXAxis"); boolean invertXAxis = invertXAxisConf == null || invertXAxisConf.getValue().equals("yes"); log("invertXAxis = %b", invertXAxis); Config invertYAxisConf = getModuleConfig(startModule.getId(), "invertYAxis"); boolean invertYAxis = invertYAxisConf == null || invertYAxisConf.getValue().equals("yes"); log("invertYAxis = %b", invertYAxis); // sort imageTasks by image position List<Task> imageTasks = this.workflowRunner.getTaskStatus().select( where("moduleId", startModule.getId())); Map<String,Task> imageTaskPosIdx = new TreeMap<String,Task>(new ImageLabelComparator()); for (Task imageTask : imageTasks) { Config slideIdConf = getTaskConfig(imageTask.getId(), "slideId"); if (poolSlide == null || new Integer(slideIdConf.getValue()).equals(poolSlide.getSlideId())) { Config imageLabelConf = getTaskConfig(imageTask.getId(), "imageLabel"); if (imageLabelConf != null) { imageTaskPosIdx.put(imageLabelConf.getValue(), imageTask); } } } imageTasks.clear(); imageTasks.addAll(imageTaskPosIdx.values()); log("imageTasks = %s", imageTasks); final String acquisitionTime; if (!imageTasks.isEmpty()) { Config acquisitionTimeConf = getTaskConfig(imageTasks.get(0).getId(), "acquisitionTime"); if (acquisitionTimeConf != null) { try { acquisitionTime = new SimpleDateFormat("yyyyMMddHHmmss").format( new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse( acquisitionTimeConf.getValue())); } catch (ParseException e) { throw new RuntimeException(e); } } else { acquisitionTime = null; } } else { acquisitionTime = null; } // determine the bounds of the stage coordinates Double minX_ = null, minY_ = null, maxX = null, maxY = null; Integer imageWidth_ = null, imageHeight_ = null; for (Task task : imageTasks) { MultiStagePosition msp = getMsp(task); if (minX_ == null || msp.getX() < minX_) minX_ = msp.getX(); if (maxX == null || msp.getX() > maxX) maxX = msp.getX(); if (minY_ == null || msp.getY() < minY_) minY_ = msp.getY(); if (maxY == null || msp.getY() > maxY) maxY = msp.getY(); if (imageWidth_ == null || imageHeight_ == null) { Config imageIdConf = getTaskConfig(task.getId(), "imageId"); if (imageIdConf != null) { Image image = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf.getValue()))); log("Getting image size for image %s", image); ImagePlus imp = null; try { imp = image.getImagePlus(acqDao); } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Couldn't retrieve image %s from the image cache!%n%s", image, sw); } if (imp != null) { imageWidth_ = imp.getWidth(); imageHeight_ = imp.getHeight(); } } } } Double minX = minX_, minY = minY_; Integer imageWidth = imageWidth_, imageHeight = imageHeight_; log("minX = %f, minY = %f, maxX = %f, maxY = %f, imageWidth = %d, imageHeight = %d", minX, minY, maxX, maxY, imageWidth, imageHeight); if (minX != null && minY != null && maxX != null && maxY != null && imageWidth != null && imageHeight != null) { int slideWidthPx = (int)Math.floor(((maxX - minX) / pixelSize) + (double)imageWidth); int slideHeightPx = (int)Math.floor(((maxY - minY) / pixelSize) + (double)imageHeight); log("slideWidthPx = %d, slideHeightPx = %d", slideWidthPx, slideHeightPx); // this is the scale factor for creating the thumbnail images double scaleFactor = (double)SLIDE_PREVIEW_WIDTH / (double)slideWidthPx; log("scaleFactor = %f", scaleFactor); int slidePreviewHeight = (int)Math.floor(scaleFactor * slideHeightPx); log("slidePreviewHeight = %d", slidePreviewHeight); ImagePlus slideThumb = NewImage.createRGBImage("slideThumb", SLIDE_PREVIEW_WIDTH, slidePreviewHeight, 1, NewImage.FILL_WHITE); Map<Integer,Roi> imageRois = new LinkedHashMap<Integer,Roi>(); List<Roi> roiRois = new ArrayList<Roi>(); Map().attr("name",String.format("map-%s-%s", startModule.getName(), slideName)).with(()->{ // TODO: parallelize for (Task task : imageTasks) { Config imageIdConf = getTaskConfig(task.getId(), "imageId"); if (imageIdConf != null) { MultiStagePosition msp = getMsp(task); // Get a thumbnail of the image Image image = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf.getValue()))); log("Working on image; %s", image); ImagePlus imp = null; try { imp = image.getImagePlus(acqDao); } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Couldn't retrieve image %s from the image cache!%n%s", image, sw); } if (imp != null) { int width = imp.getWidth(), height = imp.getHeight(); log("Image width: %d, height: %d", width, height); imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR); imp.setProcessor(imp.getTitle(), imp.getProcessor().resize( (int)Math.floor(imp.getWidth() * scaleFactor), (int)Math.floor(imp.getHeight() * scaleFactor))); log("Resized image width: %d, height: %d", imp.getWidth(), imp.getHeight()); int xloc = (int)Math.floor(((msp.getX() - minX) / pixelSize)); int xlocInvert = invertXAxis? slideWidthPx - (xloc + width) : xloc; int xlocScale = (int)Math.floor(xlocInvert * scaleFactor); log("xloc = %d, xlocInvert = %d, xlocScale = %d", xloc, xlocInvert, xlocScale); int yloc = (int)Math.floor(((msp.getY() - minY) / pixelSize)); int ylocInvert = invertYAxis? slideHeightPx - (yloc + height) : yloc; int ylocScale = (int)Math.floor(ylocInvert * scaleFactor); log("yloc = %d, ylocInvert = %d, ylocScale = %d", yloc, ylocInvert, ylocScale); // draw the thumbnail image slideThumb.getProcessor().copyBits(imp.getProcessor(), xlocScale, ylocScale, Blitter.COPY); // save the image ROI for the image map Roi imageRoi = new Roi(xlocScale, ylocScale, imp.getWidth(), imp.getHeight()); imageRoi.setName(image.getName()); imageRoi.setProperty("id", new Integer(image.getId()).toString()); imageRois.put(image.getId(), imageRoi); log("imageRoi = %s", imageRoi); for (ROI roi : roiDao.select(where("imageId", image.getId()))) { int roiX = (int)Math.floor(xlocScale + (roi.getX1() * scaleFactor)); int roiY = (int)Math.floor(ylocScale + (roi.getY1() * scaleFactor)); int roiWidth = (int)Math.floor((roi.getX2()-roi.getX1()+1) * scaleFactor); int roiHeight = (int)Math.floor((roi.getY2()-roi.getY1()+1) * scaleFactor); Roi r = new Roi(roiX, roiY, roiWidth, roiHeight); r.setName(roi.toString()); r.setProperty("id", new Integer(roi.getId()).toString()); r.setStrokeColor(new Color(1f, 0f, 0f, 0.4f)); r.setStrokeWidth(0.4); roiRois.add(r); log("roiRoi = %s", r); } } } } // write the ROI areas first so they take precedence for (Roi roi : roiRois) { Area().attr("shape","rect"). attr("coords", String.format("%d,%d,%d,%d", (int)Math.floor(roi.getXBase()), (int)Math.floor(roi.getYBase()), (int)Math.floor(roi.getXBase()+roi.getFloatWidth()), (int)Math.floor(roi.getYBase()+roi.getFloatHeight()))). attr("href", String.format("#area-ROI-%s", roi.getProperty("id"))). attr("title", roi.getName()); } // next write the image ROIs for (Roi roi : imageRois.values()) { Area().attr("shape", "rect"). attr("coords", String.format("%d,%d,%d,%d", (int)Math.floor(roi.getXBase()), (int)Math.floor(roi.getYBase()), (int)Math.floor(roi.getXBase()+roi.getFloatWidth()), (int)Math.floor(roi.getYBase()+roi.getFloatHeight()))). //attr("title", roi.getName()). attr("onClick", String.format("report.showImage(%d)", new Integer(roi.getProperty("id")))); } // now draw the ROI rois in red for (Roi roiRoi : roiRois) { slideThumb.getProcessor().setColor(roiRoi.getStrokeColor()); slideThumb.getProcessor().draw(roiRoi); } }); // write the slide thumbnail as an embedded HTML image. ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(slideThumb.getBufferedImage(), "jpg", baos); } catch (IOException e) {throw new RuntimeException(e);} Img().attr("src", String.format("data:image/jpg;base64,%s", Base64.getMimeEncoder().encodeToString(baos.toByteArray()))). attr("width", slideThumb.getWidth()). attr("height", slideThumb.getHeight()). attr("usemap", String.format("#map-%s-%s", startModule.getName(), slideName)). attr("class","map stageCoords"). attr("data-min-x", minX - imageWidth / 2.0 * pixelSize * (invertXAxis? -1.0 : 1.0)). attr("data-max-x", maxX + imageWidth / 2.0 * pixelSize * (invertXAxis? -1.0 : 1.0)). attr("data-min-y", minY - imageHeight / 2.0 * pixelSize * (invertYAxis? -1.0 : 1.0)). attr("data-max-y", maxY + imageHeight / 2.0 * pixelSize * (invertYAxis? -1.0 : 1.0)). attr("style", "border: 1px solid black"); // now render the individual ROI sections // TODO: parallelize for (Task task : imageTasks) { Config imageIdConf = getTaskConfig(task.getId(), "imageId"); if (imageIdConf != null) { Image image = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf.getValue()))); // make sure this image was included in the slide thumbnail image if (!imageRois.containsKey(image.getId())) continue; MultiStagePosition msp = getMsp(task); List<ROI> rois = roiDao.select(where("imageId", image.getId())); Collections.sort(rois, (a,b)->a.getId()-b.getId()); for (ROI roi : rois) { log("Working on ROI: %s", roi); Hr(); A().attr("name", String.format("area-ROI-%s", roi.getId())).with(()->{ H2().text(String.format("Image %s, ROI %s", image, roi)); }); // go through each attached SlideImager and look for MSP's with an ROI property // that matches this ROI's ID. for (Map.Entry<String, Set<String>> entry : roiImagers.entrySet()) { for (String imagerModuleName : entry.getValue()) { WorkflowModule imager = this.workflowRunner.getWorkflow().selectOneOrDie( where("name", imagerModuleName)); // get the hires pixel size for this imager Config hiResPixelSizeConf = getModuleConfig(imager.getId(), "pixelSize"); Double hiResPixelSize = hiResPixelSizeConf != null? new Double(hiResPixelSizeConf.getValue()) : ROIFinderDialog.DEFAULT_HIRES_PIXEL_SIZE_UM; log("hiResPixelSize = %f", hiResPixelSize); // determine the stage coordinate bounds of this ROI tile grid. // also get the image width and height of the acqusition. Double minX2_=null, minY2_=null, maxX2_=null, maxY2_=null; Integer imageWidth2_ = null, imageHeight2_ = null; Map<String,List<Task>> imagerTasks = new TreeMap<String,List<Task>>(new ImageLabelComparator()); for (Task imagerTask : this.workflowRunner.getTaskStatus().select( where("moduleId", imager.getId()))) { Config imageIdConf2 = getTaskConfig(imagerTask.getId(), "imageId"); if (imageIdConf2 != null) { MultiStagePosition imagerMsp = getMsp(imagerTask); if (imagerMsp.hasProperty("ROI") && imagerMsp.getProperty("ROI").equals(new Integer(roi.getId()).toString())) { TaskConfig imageLabelConf = getTaskConfig(imagerTask.getId(), "imageLabel"); if (imageLabelConf == null) continue; int[] indices = MDUtils.getIndices(imageLabelConf.getValue()); if (indices != null && indices.length >= 4) { String imageLabel = MDUtils.generateLabel(indices[0], indices[1], indices[2], 0); if (!imagerTasks.containsKey(imageLabel)) { imagerTasks.put(imageLabel, new ArrayList<Task>()); } imagerTasks.get(imageLabel).add(imagerTask); if (minX2_ == null || imagerMsp.getX() < minX2_) minX2_ = imagerMsp.getX(); if (minY2_ == null || imagerMsp.getY() < minY2_) minY2_ = imagerMsp.getY(); if (maxX2_ == null || imagerMsp.getX() > maxX2_) maxX2_ = imagerMsp.getX(); if (maxY2_ == null || imagerMsp.getY() > maxY2_) maxY2_ = imagerMsp.getY(); if (imageWidth2_ == null || imageHeight2_ == null) { Image image2 = imageDao.selectOneOrDie( where("id", new Integer(imageIdConf2.getValue()))); log("Getting image size for image %s", image2); ImagePlus imp = null; try { imp = image2.getImagePlus(acqDao); } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Couldn't retrieve image %s from the image cache!%n%s", image2, sw); } if (imp != null) { imageWidth2_ = imp.getWidth(); imageHeight2_ = imp.getHeight(); } } } } } } Double minX2 = minX2_, minY2 = minY2_, maxX2 = maxX2_, maxY2 = maxY2_; Integer imageWidth2 = imageWidth2_, imageHeight2 = imageHeight2_; log("minX2 = %f, minY2 = %f, maxX2 = %f, maxY2 = %f, imageWidth2 = %d, imageHeight2 = %d", minX2, minY2, maxX2_, maxY2_, imageWidth2_, imageHeight2_); if (!imagerTasks.isEmpty() && minX2 != null && minY2 != null && maxX2_ != null && maxY2_ != null && imageWidth2_ != null && imageHeight2_ != null) { int gridWidthPx = (int)Math.floor(((maxX2_ - minX2_) / hiResPixelSize) + (double)imageWidth2_); int gridHeightPx = (int)Math.floor(((maxY2_ - minY2_) / hiResPixelSize) + (double)imageHeight2_); log("gridWidthPx = %d, gridHeightPx = %d", gridWidthPx, gridHeightPx); // this is the scale factor for creating the thumbnail images double gridScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)gridWidthPx; int gridPreviewHeight = (int)Math.floor(gridScaleFactor * gridHeightPx); log("gridScaleFactor = %f, gridPreviewHeight = %d", gridScaleFactor, gridPreviewHeight); ImagePlus roiGridThumb = NewImage.createRGBImage( String.format("roiGridThumb-%s-ROI%d", imager.getName(), roi.getId()), ROI_GRID_PREVIEW_WIDTH, gridPreviewHeight, 1, NewImage.FILL_WHITE); log("roiGridThumb: width=%d, height=%d", roiGridThumb.getWidth(), roiGridThumb.getHeight()); Table().attr("class","table table-bordered table-hover table-striped"). with(()->{ Thead().with(()->{ Tr().with(()->{ Th().text("Image Properties"); Th().text("Source ROI Cutout"); Th().text("Tiled ROI Images"); Th().text("Stitched ROI Image"); Th().text("Curation"); }); }); Tbody().with(()->{ for (Map.Entry<String,List<Task>> imagerTaskEntry : imagerTasks.entrySet()) { String imageLabel = imagerTaskEntry.getKey(); int[] indices = MDUtils.getIndices(imageLabel); int channel = indices[0], slice = indices[1], frame = indices[2]; log("Working on channel %d, slice %d, frame %d", channel, slice, frame); Tr().with(()->{ Th().with(()->{ P(String.format("Channel %d, Slice %d, Frame %d", channel, slice, frame)); // get the average stage position of all the tiled ROI images int posCount = 0; double xPos = 0.0; double yPos = 0.0; for (Task imagerTask : imagerTaskEntry.getValue()) { MultiStagePosition imagerMsp = getMsp(imagerTask); Config imageIdConf2 = getTaskConfig(imagerTask.getId(), "imageId"); if (imageIdConf2 != null) { for (int i=0; i<imagerMsp.size(); ++i) { StagePosition sp = imagerMsp.get(i); if (sp.numAxes == 2 && sp.stageName.compareTo(imagerMsp.getDefaultXYStage()) == 0) { xPos += sp.x; yPos += sp.y; ++posCount; break; } } } } // add a link to load the slide and go to the stage position if (posCount > 0) { Double xPos_ = xPos / posCount; Double yPos_ = yPos / posCount; P().with(()->{ A().attr("onClick", String.format("report.goToPosition(%d,%d,%f,%f)", loaderModule.getId(), poolSlide != null? poolSlide.getId() : -1, xPos_, yPos_)). text(String.format("Go To Stage Position: (%.2f,%.2f)", xPos_, yPos_)); }); // add another link to put the slide back if (poolSlide != null) { P().with(()->{ A().attr("onClick", String.format("report.returnSlide(%d)", loaderModule.getId())). text("Return slide to loader"); }); } } }); Td().with(()->{ ImagePlus imp = null; try { imp = image.getImagePlus(acqDao); } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Couldn't retrieve image %s from the image cache!%n%s", image, sw); } if (imp != null) { imp.setRoi(new Roi(roi.getX1(), roi.getY1(), roi.getX2()-roi.getX1()+1, roi.getY2()-roi.getY1()+1)); double roiScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)(roi.getX2()-roi.getX1()+1); int roiPreviewHeight = (int)Math.floor((roi.getY2()-roi.getY1()+1) * roiScaleFactor); imp.setProcessor(imp.getTitle(), imp.getProcessor().crop().resize( ROI_GRID_PREVIEW_WIDTH, roiPreviewHeight)); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); //String dirs = new File(reportDir, reportFile).getPath().replaceAll("\\.html$", ""); //new File(dirs).mkdirs(); //new FileSaver(imp).saveAsJpeg(new File(dirs, String.format("ROI%s.roi_thumbnail.jpg", roi.getId())).getPath()); try { ImageIO.write(imp.getBufferedImage(), "jpg", baos2); } catch (IOException e) {throw new RuntimeException(e);} ImagePlus imp_ = imp; A().attr("onClick", String.format("report.showImage(%d)", image.getId())). with(()->{ Img().attr("src", String.format("data:image/jpg;base64,%s", Base64.getMimeEncoder().encodeToString(baos2.toByteArray()))). attr("width", imp_.getWidth()). attr("height", imp_.getHeight()). attr("data-min-x", msp.getX() + (roi.getX1() - (imp_.getWidth() / 2.0)) * pixelSize * (invertXAxis? -1.0 : 1.0)). attr("data-max-x", msp.getX() + (roi.getX2() - (imp_.getWidth() / 2.0)) * pixelSize * (invertXAxis? -1.0 : 1.0)). attr("data-min-y", msp.getY() + (roi.getY1() - (imp_.getHeight() / 2.0)) * pixelSize * (invertYAxis? -1.0 : 1.0)). attr("data-max-y", msp.getY() + (roi.getY2() - (imp_.getHeight() / 2.0)) * pixelSize * (invertYAxis? -1.0 : 1.0)). //attr("title", roi.toString()). attr("class", "stageCoords"); }); } }); Td().with(()->{ List<Runnable> makeLinks = new ArrayList<>(); Map().attr("name", String.format("map-roi-%s-ROI%d", imager.getName(), roi.getId())).with(()->{ for (Task imagerTask : imagerTaskEntry.getValue()) { Config imageIdConf2 = getTaskConfig(imagerTask.getId(), "imageId"); if (imageIdConf2 != null) { MultiStagePosition imagerMsp = getMsp(imagerTask); // Get a thumbnail of the image Image image2 = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf2.getValue()))); ImagePlus imp = null; try { imp = image2.getImagePlus(acqDao); } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Couldn't retrieve image %s from the image cache!%n%s", image2, sw); } if (imp != null) { int width = imp.getWidth(), height = imp.getHeight(); log("imp: width=%d, height=%d", width, height); imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR); imp.setProcessor(imp.getTitle(), imp.getProcessor().resize( (int)Math.floor(imp.getWidth() * gridScaleFactor), (int)Math.floor(imp.getHeight() * gridScaleFactor))); log("imp: resized width=%d, height=%d", imp.getWidth(), imp.getHeight()); int xloc = (int)Math.floor((imagerMsp.getX() - minX2) / hiResPixelSize); int xlocInvert = invertXAxis? gridWidthPx - (xloc + width) : xloc; int xlocScale = (int)Math.floor(xlocInvert * gridScaleFactor); log("xloc=%d, xlocInvert=%d, xlocScale=%d", xloc, xlocInvert, xlocScale); int yloc = (int)Math.floor((imagerMsp.getY() - minY2) / hiResPixelSize); int ylocInvert = invertYAxis? gridHeightPx - (yloc + height) : yloc; int ylocScale = (int)Math.floor(ylocInvert * gridScaleFactor); log("yloc=%d, ylocInvert=%d, ylocScale=%d", yloc, ylocInvert, ylocScale); roiGridThumb.getProcessor().copyBits(imp.getProcessor(), xlocScale, ylocScale, Blitter.COPY); Roi tileRoi = new Roi(xlocScale, ylocScale, imp.getWidth(), imp.getHeight()); // make the tile image clickable Area().attr("shape", "rect"). attr("coords", String.format("%d,%d,%d,%d", (int)Math.floor(tileRoi.getXBase()), (int)Math.floor(tileRoi.getYBase()), (int)Math.floor(tileRoi.getXBase()+tileRoi.getFloatWidth()), (int)Math.floor(tileRoi.getYBase()+tileRoi.getFloatHeight()))). attr("title", image2.getName()). attr("onClick", String.format("report.showImage(%d)", image2.getId())); makeLinks.add(()->{ P().with(()->{ A().attr("onClick",String.format("report.checkPosCalibration(%d,%d,%f,%f,%f,%f,%f,%f,%f,%f)", image.getId(), image2.getId(), pixelSize, hiResPixelSize, invertXAxis? -1.0 : 1.0, invertYAxis? -1.0 : 1.0, msp.getX(), msp.getY(), imagerMsp.getX(), imagerMsp.getY())). text(String.format("Check pos calibration for image %s", image2.getName())); }); }); } } } }); //String dirs = new File(reportDir, reportFile).getPath().replaceAll("\\.html$", ""); //new File(dirs).mkdirs(); //new FileSaver(roiGridThumb).saveAsJpeg(new File(dirs, String.format("ROI%s.grid_thumbnail.jpg", roi.getId())).getPath()); // write the grid thumbnail as an embedded HTML image. ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); try { ImageIO.write(roiGridThumb.getBufferedImage(), "jpg", baos2); } catch (IOException e) {throw new RuntimeException(e);} Img().attr("src", String.format("data:image/jpg;base64,%s", Base64.getMimeEncoder().encodeToString(baos2.toByteArray()))). attr("width", roiGridThumb.getWidth()). attr("height", roiGridThumb.getHeight()). attr("class", "map stageCoords"). attr("data-min-x", minX2 - imageWidth2 / 2.0 * hiResPixelSize * (invertXAxis? -1.0 : 1.0)). attr("data-max-x", maxX2 + imageWidth2 / 2.0 * hiResPixelSize * (invertXAxis? -1.0 : 1.0)). attr("data-min-y", minY2 - imageHeight2 / 2.0 * hiResPixelSize * (invertYAxis? -1.0 : 1.0)). attr("data-max-y", maxY2 + imageHeight2 / 2.0 * hiResPixelSize * (invertYAxis? -1.0 : 1.0)). attr("usemap", String.format("#map-roi-%s-ROI%d", imager.getName(), roi.getId())); for (Runnable r : makeLinks) { r.run(); } }); List<String> stitchedImageFiles = new ArrayList<>(); Td().with(()->{ // get the downstream stitcher tasks Set<Task> stitcherTasks = new HashSet<Task>(); for (Task imagerTask : imagerTaskEntry.getValue()) { for (TaskDispatch td : this.workflowRunner.getTaskDispatch().select(where("parentTaskId", imagerTask.getId()))) { Task stitcherTask = this.workflowRunner.getTaskStatus().selectOneOrDie( where("id", td.getTaskId())); Config canStitchImages = getModuleConfig(stitcherTask.getModuleId(), "canStitchImages"); if (canStitchImages != null && "yes".equals(canStitchImages.getValue()) && stitcherTask.getStatus().equals(Status.SUCCESS)) { stitcherTasks.add(stitcherTask); } } } for (Task stitcherTask : stitcherTasks) { log("Working on stitcher task: %s", stitcherTask); Config stitchedImageFile = getTaskConfig(stitcherTask.getId(), "stitchedImageFile"); log("stitchedImageFile = %s", stitchedImageFile.getValue()); if (stitchedImageFile != null && new File(stitchedImageFile.getValue()).exists()) { stitchedImageFiles.add(stitchedImageFile.getValue()); // Get a thumbnail of the image ImagePlus imp = new ImagePlus(stitchedImageFile.getValue()); log("stitchedImage width = %d, height = %d", imp.getWidth(), imp.getHeight()); double stitchScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)imp.getWidth(); log("stitchScaleFactor = %f", stitchScaleFactor); int stitchPreviewHeight = (int)Math.floor(imp.getHeight() * stitchScaleFactor); log("stitchPreviewHeight = %d", stitchPreviewHeight); imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR); imp.setProcessor(imp.getTitle(), imp.getProcessor().resize( ROI_GRID_PREVIEW_WIDTH, stitchPreviewHeight)); log("resized stitched image width=%d, height=%d", imp.getWidth(), imp.getHeight()); //String dirs = new File(reportDir, reportFile).getPath().replaceAll("\\.html$", ""); //new File(dirs).mkdirs(); //new FileSaver(imp).saveAsJpeg(new File(dirs, String.format("ROI%s.stitched_thumbnail.jpg", roi.getId())).getPath()); // write the stitched thumbnail as an embedded HTML image. ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); try { ImageIO.write(imp.getBufferedImage(), "jpg", baos2); } catch (IOException e) {throw new RuntimeException(e);} A().attr("onClick", String.format("report.showImageFile(\"%s\")", Util.escapeJavaStyleString(stitchedImageFile.getValue()))). with(()->{ Img().attr("src", String.format("data:image/jpg;base64,%s", Base64.getMimeEncoder().encodeToString(baos2.toByteArray()))). attr("width", imp.getWidth()). attr("height", imp.getHeight()). attr("title", stitchedImageFile.getValue()); }); } } }); // Curation buttons String[] orientations = new String[]{"lateral","ventral","dorsal"}; String[] stages = new String[]{"1-3","4-6","7-8","9-10","11-12","13-16"}; String experimentId = slide != null? slide.getExperimentId().replaceAll("[\\/ :]+","_") : acquisitionTime != null? acquisitionTime : "slide"; Td().with(()->{ Table().with(()->{ Tbody().with(()->{ for (String orientation : orientations) { Tr().with(()->{ for (String stage : stages) { Td().with(()->{ StringBuilder sb = new StringBuilder(); for (String stitchedImageFile : stitchedImageFiles) { sb.append(String.format("report.curate(\"%s\",\"%s\",\"%s\",\"%s\"); ", Util.escapeJavaStyleString(stitchedImageFile), Util.escapeJavaStyleString(experimentId), Util.escapeJavaStyleString(orientation), Util.escapeJavaStyleString(stage))); } Button(String.format("%s %s", orientation, stage)). attr("type","button"). attr("onclick", sb.toString()); }); } }); } }); }); }); }); } }); }); } } } } } } } } public void showImage(int imageId) { //log("called showImage(imageId=%d)", imageId); Dao<Image> imageDao = this.workflowRunner.getWorkflowDb().table(Image.class); Dao<Acquisition> acqDao = this.workflowRunner.getWorkflowDb().table(Acquisition.class); Image image = imageDao.selectOneOrDie(where("id", imageId)); ImagePlus imp = image.getImagePlus(acqDao); imp.show(); } public void goToPosition(Integer loaderModuleId, int poolSlideId, double xPos, double yPos) { synchronized(this) { Dao<PoolSlide> poolSlideDao = this.workflowRunner.getWorkflowDb().table(PoolSlide.class); PoolSlide poolSlide = poolSlideId > 0? poolSlideDao.selectOne(where("id", poolSlideId)) : null; SwingUtilities.invokeLater(()->{ Double xPos_ = xPos; Double yPos_ = yPos; PoolSlide poolSlide_ = poolSlide; Integer loaderModuleId_ = loaderModuleId; Integer poolSlideId_ = poolSlideId; Integer cartridgePosition = poolSlide_.getCartridgePosition(); Integer slidePosition = poolSlide_.getSlidePosition(); String slideMessage = poolSlide_ != null && loaderModuleId_ != null && prevPoolSlideId != poolSlideId_? String.format(" on cartridge %d, slide %d?", cartridgePosition, slidePosition) : "?"; String message = String.format("Would you like to move the stage to position (%.2f,%.2f)%s", xPos_, yPos_, slideMessage); if (JOptionPane.showConfirmDialog(null, message, "Move To Position", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { new Thread(()->{ // load the slide if (poolSlideId_ > 0 && loaderModuleId_ != null && this.prevPoolSlideId != poolSlideId_) { WorkflowModule loaderModule = this.workflowRunner.getWorkflow().selectOneOrDie( where("id", loaderModuleId_)); Module module = this.workflowRunner.getModuleInstances().get(loaderModule.getId()); if (module == null) throw new RuntimeException(String.format("Could not find instance for module %s!", loaderModule)); // init loader and scan for slides if (this.isLoaderInitialized.get(loaderModuleId_) == null || !this.isLoaderInitialized.get(loaderModuleId_)) { try { Method initSlideLoader = module.getClass().getDeclaredMethod("initSlideLoader", boolean.class); initSlideLoader.invoke(module, true); Method scanForSlides = module.getClass().getDeclaredMethod("scanForSlides"); scanForSlides.invoke(module); this.isLoaderInitialized.put(loaderModuleId_, true); } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Couldn't scan for slides!%n%s", sw); return; } } // unload the previous slide first if (this.prevPoolSlideId != null) { PoolSlide prevPoolSlide = poolSlideDao.selectOneOrDie(where("id", prevPoolSlideId)); try { Method unloadSlide = module.getClass().getDeclaredMethod("unloadSlide", PoolSlide.class); unloadSlide.invoke(module, prevPoolSlide); } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Couldn't unload slide %s from stage!%n%s", prevPoolSlide, sw); return; } } // now load the slide try { Method loadSlide = module.getClass().getDeclaredMethod("loadSlide", PoolSlide.class); loadSlide.invoke(module, poolSlide_); // set previous pool slide to this slide this.prevPoolSlideId = poolSlideId_; } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Couldn't unload slide %s from stage!%n%s", poolSlide, sw); return; } } // move the stage CMMCore core = MMStudio.getInstance().getMMCore(); try { SlideImager.moveStage(this.getClass().getSimpleName(), core, xPos_, yPos_, null); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Error while attempting to move stage to coordinates: (%.2f,%.2f)%n%s", xPos_, yPos_, sw); return; } // autofocus? SwingUtilities.invokeLater(()->{ if (JOptionPane.showConfirmDialog(null, "Autofocus now?", "Move To Position", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { new Thread(()->{ MMStudio.getInstance().autofocusNow(); }).start(); } }); }).start(); } }); } } public void returnSlide(Integer loaderModuleId) { synchronized(this) { if (this.prevPoolSlideId != null) { SwingUtilities.invokeLater(()->{ if (JOptionPane.showConfirmDialog(null, String.format("Would you like to return the slide to the loader?"), "Return Slide to Stage", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { new Thread(()->{ WorkflowModule loaderModule = this.workflowRunner.getWorkflow().selectOneOrDie( where("id", loaderModuleId)); Module module = this.workflowRunner.getModuleInstances().get(loaderModule.getId()); if (module == null) throw new RuntimeException(String.format("Could not find instance for module %s!", loaderModule)); Dao<PoolSlide> poolSlideDao = this.workflowRunner.getWorkflowDb().table(PoolSlide.class); PoolSlide prevPoolSlide = poolSlideDao.selectOneOrDie(where("id", prevPoolSlideId)); try { Method unloadSlide = module.getClass().getDeclaredMethod("unloadSlide", PoolSlide.class); unloadSlide.invoke(module, prevPoolSlide); this.prevPoolSlideId = null; } catch (Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log("Couldn't unload slide %s from stage!%n%s", prevPoolSlide, sw); return; } }).start(); } }); } } } public void showImageFile(String imagePath) { //log("called showImageFile(imagePath=%s)", imagePath); ImagePlus imp = new ImagePlus(imagePath); imp.show(); } public void goToURL(String url) { try { url = Paths.get(this.reportDir).resolve(url).toUri().toURL().toString(); } catch (MalformedURLException e) {throw new RuntimeException(e);} this.webEngine.load(url); } public void checkPosCalibration( int image1Id, int image2Id, double pixelSize, double hiResPixelSize, double invertX, double invertY, double image1X, double image1Y, double image2X, double image2Y) { Dao<Acquisition> acqDao = this.workflowRunner.getWorkflowDb().table(Acquisition.class); Dao<Image> imageDao = this.workflowRunner.getWorkflowDb().table(Image.class); Image image1 = imageDao.selectOneOrDie(where("id", image1Id)); ImagePlus imp1 = image1.getImagePlus(acqDao); Image image2 = imageDao.selectOneOrDie(where("id", image2Id)); ImagePlus imp2 = image2.getImagePlus(acqDao); imp2.setProcessor(imp2.getProcessor().resize( (int)Math.floor(imp2.getWidth() * (hiResPixelSize / pixelSize)), (int)Math.floor(imp2.getHeight() * (hiResPixelSize / pixelSize)))); int roiX = (int)Math.floor((image2X - image1X) / pixelSize * invertX + (imp1.getWidth() / 2.0) - (imp2.getWidth() / 2.0)); int roiY = (int)Math.floor((image2Y - image1Y) / pixelSize * invertY + (imp1.getHeight() / 2.0) - (imp2.getHeight() / 2.0)); int roiWidth = imp2.getWidth(); int roiHeight = imp2.getHeight(); ImageRoi roi = new ImageRoi(roiX, roiY, imp2.getProcessor()); roi.setName(image2.getName()); roi.setOpacity(0.3); Overlay overlayList = imp1.getOverlay(); if (overlayList == null) overlayList = new Overlay(); overlayList.add(roi); imp1.setOverlay(overlayList); // pop open the window imp1.setHideOverlay(false); imp1.show(); // wait for window to close, then calculate the ROI diff imp1.getWindow().addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Overlay overlayList = imp1.getOverlay(); if (overlayList != null) { for (int i=0; i<overlayList.size(); ++i) { Roi roi2 = overlayList.get(i); if (Objects.equals(roi2.getName(), image2.getName())) { int diffXPx = (int)Math.floor( (roi2.getXBase() + roi2.getFloatWidth() / 2.0) - (roiX + roiWidth / 2.0)); int diffYPx = (int)Math.floor( (roi2.getYBase() + roi2.getFloatHeight() / 2.0) - (roiY + roiHeight / 2.0)); double diffX = diffXPx * pixelSize * invertX; double diffY = diffYPx * pixelSize * invertY; // write the diff to the log and stderr String message = String.format("PosCalibrator\tref_image\t%s\tcompare_image\t%s\tpixel_offset\t%d\t%d\tstage_offset\t%.2f\t%.2f", image1.getName(), image2.getName(), diffXPx, diffYPx, diffX, diffY); IJ.log(message); System.err.println(message); } } } } }); } private MultiStagePosition getMsp(Task task) { MultiStagePosition msp = this.msps.get(task.getId()); if (msp == null) throw new RuntimeException(String.format("Could not find MSP conf for task %s!", task)); return msp; } /** * If the user presses a curation button, copy and rename the stitched image into the curation folder. * @param stitchedImagePath The path to the stitched image * @param orientation The embryo's orientation * @param stage Curated timepoint in hours */ public void curate(String stitchedImagePath, String experimentId, String orientation, String stage) { // /data/insitu_images/images/stage${stage}/lm(l|d|v)_${experiment_id}_${stage}.jpg String imagesFolder = "/data/insitu_images/images"; String stageFolderName = String.format("stage%s",stage); String fileName = String.format("lm%s_%s_%s.jpg", orientation.charAt(0), experimentId, stage); String outputFile = Paths.get(imagesFolder, stageFolderName, fileName).toString(); ImagePlus imp = new ImagePlus(stitchedImagePath); if (new FileSaver(imp).saveAsJpeg(outputFile)) { this.webEngine.executeScript(String.format( "(function(f,d){$.notify('Image \"'+f+'\" was created in \"'+d+'\".','success')})(\"%s\",\"%s\")", Util.escapeJavaStyleString(fileName), Util.escapeJavaStyleString(Paths.get(imagesFolder, stageFolderName).toString()))); } else { this.webEngine.executeScript(String.format( "(function(f){$.notify('Failed to write image \"'+f+'\"!','error')})(\"%s\")", Util.escapeJavaStyleString(outputFile))); } } }
package org.lantern.state; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Set; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.annotate.JsonView; import org.lantern.LanternConstants; import org.lantern.LanternUtils; import org.lantern.Whitelist; import org.lantern.state.Model.Persistent; import org.lantern.state.Model.Run; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** * Base Lantern settings. */ public class Settings { private String email = ""; private String lang = Locale.getDefault().getLanguage(); private boolean autoStart = true; private boolean autoReport = true; private Mode mode = Mode.none; private int proxyPort = LanternConstants.LANTERN_LOCALHOST_HTTP_PORT; private boolean systemProxy = true; private boolean proxyAllSites = false; private boolean useGoogleOAuth2 = false; private String clientID; private String clientSecret; private String accessToken; private String refreshToken; private Set<String> inClosedBeta = new HashSet<String>(); private Whitelist whitelist = new Whitelist(); private boolean startAtLogin = true; private Set<String> proxies = new LinkedHashSet<String>(); private boolean useTrustedPeers = true; private boolean useLaeProxies = true; private boolean useAnonymousPeers = true; private boolean useCentralProxies = true; private Set<String> stunServers = new HashSet<String>(); private int serverPort = LanternUtils.randomPort(); /** * Indicates whether use of keychains is enabled. * this can be disabled by command line option. */ private boolean keychainEnabled = true; /** * Whether or not we're running with a graphical UI. * Not stored or sent to the browser. */ private boolean uiEnabled = true; private boolean bindToLocalhost = true; private boolean autoConnectToPeers = true; private boolean useCloudProxies = true; public enum Mode { give, get, none } @JsonView({Run.class, Persistent.class}) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @JsonView(Run.class) public String getLang() { return lang; } public void setLang(String lang) { this.lang = lang; } @JsonView({Run.class, Persistent.class}) public boolean isAutoStart() { return autoStart; } public void setAutoStart(final boolean autoStart) { this.autoStart = autoStart; } @JsonView({Run.class, Persistent.class}) public boolean isAutoReport() { return autoReport; } public void setAutoReport(final boolean autoReport) { this.autoReport = autoReport; } @JsonView({Run.class, Persistent.class}) public Mode getMode() { return mode; } public void setMode(final Mode mode) { this.mode = mode; } @JsonView({Run.class, Persistent.class}) public int getProxyPort() { return proxyPort; } public void setProxyPort(final int proxyPort) { this.proxyPort = proxyPort; } @JsonView({Run.class, Persistent.class}) public boolean isSystemProxy() { return systemProxy; } public void setSystemProxy(final boolean systemProxy) { this.systemProxy = systemProxy; } @JsonView({Run.class, Persistent.class}) public boolean isProxyAllSites() { return proxyAllSites; } public void setProxyAllSites(final boolean proxyAllSites) { this.proxyAllSites = proxyAllSites; } @JsonView({Run.class}) public Collection<String> getProxiedSites() { return whitelist.getEntriesAsStrings(); } public void setProxiedSites(final String[] proxiedSites) { whitelist.setStringEntries(proxiedSites); } @JsonView({Persistent.class}) public Whitelist getWhitelist() { return whitelist; } public void setWhitelist(Whitelist whitelist) { this.whitelist = whitelist; } public void setClientID(final String clientID) { this.clientID = clientID; } public void setUseGoogleOAuth2(boolean useGoogleOAuth2) { this.useGoogleOAuth2 = useGoogleOAuth2; } @JsonView({Persistent.class}) public boolean isUseGoogleOAuth2() { return useGoogleOAuth2; } @JsonView({Persistent.class}) public String getClientID() { return clientID; } public void setClientSecret(final String clientSecret) { this.clientSecret = clientSecret; } @JsonView({Persistent.class}) public String getClientSecret() { return clientSecret; } public void setAccessToken(final String accessToken) { this.accessToken = accessToken; } @JsonView({Persistent.class}) public String getAccessToken() { return accessToken; } public void setRefreshToken(final String password) { this.refreshToken = password; } @JsonView({Persistent.class}) public String getRefreshToken() { return refreshToken; } @JsonView({Persistent.class}) public Set<String> getInClosedBeta() { return Sets.newHashSet(this.inClosedBeta); } public void setInClosedBeta(final Set<String> inClosedBeta) { this.inClosedBeta = ImmutableSet.copyOf(inClosedBeta); } public void setGetMode(final boolean getMode) { if (getMode) { setMode(Mode.get); } else { setMode(Mode.give); } } @JsonIgnore public boolean isGetMode() { return mode == Mode.get; } @JsonView({Run.class, Persistent.class}) public boolean isStartAtLogin() { return this.startAtLogin; } public void setStartAtLogin(final boolean startAtLogin) { this.startAtLogin = startAtLogin; } public void setProxies(final Set<String> proxies) { synchronized (this.proxies) { this.proxies = proxies; } } @JsonView({Persistent.class}) public Set<String> getProxies() { synchronized (this.proxies) { return ImmutableSet.copyOf(this.proxies); } } public void addProxy(final String proxy) { // Don't store peer proxies on disk. if (!proxy.contains("@")) { this.proxies.add(proxy); } } public void removeProxy(final String proxy) { this.proxies.remove(proxy); } public void setUseTrustedPeers(final boolean useTrustedPeers) { this.useTrustedPeers = useTrustedPeers; } @JsonIgnore public boolean isUseTrustedPeers() { return useTrustedPeers; } public void setUseLaeProxies(boolean useLaeProxies) { this.useLaeProxies = useLaeProxies; } @JsonIgnore public boolean isUseLaeProxies() { return useLaeProxies; } public void setUseAnonymousPeers(boolean useAnonymousPeers) { this.useAnonymousPeers = useAnonymousPeers; } @JsonIgnore public boolean isUseAnonymousPeers() { return useAnonymousPeers; } public void setUseCentralProxies(final boolean useCentralProxies) { this.useCentralProxies = useCentralProxies; } @JsonIgnore public boolean isUseCentralProxies() { return useCentralProxies; } public void setStunServers(final Set<String> stunServers){ this.stunServers = stunServers; } @JsonView({Run.class, Persistent.class}) public Collection<String> getStunServers() { return stunServers; } public void setServerPort(final int serverPort) { this.serverPort = serverPort; } @JsonView({Persistent.class}) public int getServerPort() { return serverPort; } public void setKeychainEnabled(boolean keychainEnabled) { this.keychainEnabled = keychainEnabled; } @JsonIgnore public boolean isKeychainEnabled() { return keychainEnabled; } public void setUiEnabled(boolean uiEnabled) { this.uiEnabled = uiEnabled; } @JsonIgnore public boolean isUiEnabled() { return uiEnabled; } public void setBindToLocalhost(final boolean bindToLocalhost) { this.bindToLocalhost = bindToLocalhost; } @JsonIgnore public boolean isBindToLocalhost() { return bindToLocalhost; } public void setAutoConnectToPeers(final boolean autoConnectToPeers) { this.autoConnectToPeers = autoConnectToPeers; } @JsonIgnore public boolean isAutoConnectToPeers() { return autoConnectToPeers; } public void setUseCloudProxies(final boolean useCloudProxies) { this.useCloudProxies = useCloudProxies; } @JsonView({Run.class, Persistent.class}) public boolean isUseCloudProxies() { return useCloudProxies; } }
package org.broad.igv.ga4gh; import com.google.gson.*; import org.apache.log4j.Logger; import org.broad.igv.sam.Alignment; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MessageUtils; import javax.swing.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; import java.util.List; import java.util.zip.GZIPInputStream; public class Ga4ghAPIHelper { private static Logger log = Logger.getLogger(Ga4ghAPIHelper.class); public static final String RESOURCE_TYPE = "ga4gh"; public static final Ga4ghProvider GA4GH_GOOGLE_PROVIDER = new Ga4ghProvider( "Google", "https://genomics.googleapis.com/v1", "AIzaSyC-dujgw4P1QvNd8i_c-I-S_P1uxVZzn0w", Arrays.asList( new Ga4ghDataset("10473108253681171589", "1000 Genomes", "hg19"), new Ga4ghDataset("383928317087", "PGP", "hg19"), new Ga4ghDataset("461916304629", "Simons Foundation", "hg19") )); public static final Ga4ghProvider GA4GH_NCBI_PROVIDER = new Ga4ghProvider("NCBI", "http://trace.ncbi.nlm.nih.gov/Traces/gg", null, Arrays.asList( new Ga4ghDataset("SRP034507", "SRP034507", "M74568"), new Ga4ghDataset("SRP029392", "SRP029392", "NC_004917") )); public static final Ga4ghProvider[] providers = { GA4GH_GOOGLE_PROVIDER}; final static Map<String, List<Ga4ghReadset>> readsetCache = new HashMap<String, List<Ga4ghReadset>>(); final static Map<String, List<JsonObject>> referenceCache = new HashMap<String, List<JsonObject>>(); public static List<Ga4ghReadset> searchReadGroupsets(Ga4ghProvider provider, String datasetId, int maxResults) throws IOException { List<Ga4ghReadset> readsets = readsetCache.get(datasetId); if (readsets == null) { readsets = new ArrayList(); String genomeId = genomeIdMap.get(provider.getName() + " " + datasetId); // Hack until meta data on readsets is available // Loop through pages int maxPages = 100; JsonPrimitive pageToken = null; while (maxPages String contentToPost = "{" + "\"datasetIds\": [\"" + datasetId + "\"]" + (pageToken == null ? "" : ", \"pageToken\": " + pageToken) + ", \"pageSize\":" + maxResults + "}"; String result = doPost(provider, "/readgroupsets/search", contentToPost, null, true); //"fields=readsets(id,name, fileData),nextPageToken"); if (result == null) return null; JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(result).getAsJsonObject(); Iterator<JsonElement> iter = obj.getAsJsonArray("readGroupSets").iterator(); while (iter.hasNext()) { JsonElement next = iter.next(); JsonObject jobj = next.getAsJsonObject(); String id = jobj.get("id").getAsString(); String name = jobj.get("name").getAsString(); readsets.add(new Ga4ghReadset(id, name, genomeId)); } if (readsets.size() >= maxResults) break; pageToken = obj.getAsJsonPrimitive("nextPageToken"); if (pageToken == null || pageToken.getAsString().equals("")) break; } Collections.sort(readsets, new Comparator<Ga4ghReadset>() { @Override public int compare(Ga4ghReadset o1, Ga4ghReadset o2) { return o1.getName().compareTo(o2.getName()); } }); readsetCache.put(datasetId, readsets); } return readsets; } public static List<JsonObject> searchReferences(Ga4ghProvider provider, String referenceSetId, int maxResults) throws IOException { List<JsonObject> references = referenceCache.get(referenceSetId); if (references == null) { references = new ArrayList(); // Loop through pages int maxPages = 100; JsonPrimitive pageToken = null; while (maxPages String contentToPost = "{" + "\"referenceSetId\": \"" + referenceSetId + "\"" + (pageToken == null ? "" : ", \"pageToken\": " + pageToken) + ", \"pageSize\":" + maxResults + "}"; String result = doPost(provider, "/references/search", contentToPost, null, true); //"fields=readsets(id,name, fileData),nextPageToken"); if (result == null) return null; JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(result).getAsJsonObject(); Iterator<JsonElement> iter = obj.getAsJsonArray("references").iterator(); while (iter.hasNext()) { JsonElement next = iter.next(); references.add(next.getAsJsonObject()); } if (references.size() >= maxResults) break; pageToken = obj.getAsJsonPrimitive("nextPageToken"); if (pageToken == null || pageToken.getAsString().equals("")) break; } referenceCache.put(referenceSetId, references); } return references; } public static List<Alignment> searchReads(Ga4ghProvider provider, String readGroupSetId, String chr, int start, int end, boolean handleError) throws IOException { List<Alignment> alignments = new ArrayList<Alignment>(10000); int maxPages = 10000; JsonPrimitive pageToken = null; StringBuffer result = new StringBuffer(); int counter = 0; while (maxPages String contentToPost = "{" + "\"readGroupSetIds\": [\"" + readGroupSetId + "\"]" + ", \"referenceName\": \"" + chr + "\"" + ", \"start\": \"" + start + "\"" + ", \"end\": \"" + end + "\"" + ", \"pageSize\": \"10000\"" + (pageToken == null ? "" : ", \"pageToken\": " + pageToken) + "}"; String readString = doPost(provider, "/reads/search", contentToPost, "", handleError); if (readString == null) { return null; } JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(readString).getAsJsonObject(); JsonArray reads = obj.getAsJsonArray("alignments"); Iterator<JsonElement> iter = reads.iterator(); while (iter.hasNext()) { JsonElement next = iter.next(); Ga4ghAlignment alignment = new Ga4ghAlignment(next.getAsJsonObject()); alignments.add(alignment); } //System.out.println("# reads = " + reads.size()); pageToken = obj.getAsJsonPrimitive("nextPageToken"); if (pageToken == null || pageToken.getAsString().equals("")) break; System.out.println("" + (++counter) + " " + alignments.size()); } //System.out.println("# pages= " + (10000 - maxPages)); return alignments; } private static String doPost(Ga4ghProvider provider, String command, String content, String fields, boolean handleError) throws IOException { String authKey = provider.getApiKey(); String baseURL = provider.getBaseURL(); String token = OAuthUtils.getInstance().getAccessToken(); String fullUrl = baseURL + command; if (authKey != null) { fullUrl += "?key=" + authKey; } if (fields != null) { fullUrl += (authKey == null ? "?" : "&") + fields; } URL url = new URL(fullUrl); byte[] bytes = content.getBytes(); // Create a URLConnection HttpURLConnection connection = null; BufferedReader br; OutputStream outputStream; try { connection = (HttpURLConnection) url.openConnection(); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); //connection.setRequestProperty("Content-Length", "" + bytes.length); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Cache-Control", "no-cache"); connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setRequestProperty("User-Agent", "IGV (gzip)"); if (token != null) { connection.setRequestProperty("Authorization", "Bearer " + token); } // Post content outputStream = connection.getOutputStream(); outputStream.write(bytes); outputStream.close(); // Read the response br = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()))); StringBuffer sb = new StringBuffer(); String str = br.readLine(); while (str != null) { sb.append(str); str = br.readLine(); } br.close(); return sb.toString(); } catch (Exception e) { if (handleError) { handleHttpException(url, connection, e); } return null; } } static void handleHttpException(URL url, HttpURLConnection connection, Exception e) throws IOException { int rs = connection.getResponseCode(); String sb = getErrorMessage(connection); if (sb != null && sb.length() > 0) { MessageUtils.showErrorMessage(sb, e); } else if (rs == 404) { MessageUtils.showErrorMessage("The requested resource was not found<br>" + url, e); } else if (rs == 401 || rs == 403) { displayAuthorizationDialog(url.getHost()); } else { MessageUtils.showErrorMessage("Error accessing resource", e); log.error("Error accessing resource", e); } } private static String getErrorMessage(HttpURLConnection connection) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getErrorStream()))); StringBuffer sb = new StringBuffer(); String str = br.readLine(); while (str != null) { sb.append(str); str = br.readLine(); } br.close(); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(sb.toString()).getAsJsonObject(); JsonObject errorObject = obj.getAsJsonObject("error"); if (errorObject != null) { JsonPrimitive msg = errorObject.getAsJsonPrimitive("message"); if (msg != null) return msg.getAsString(); } return sb.toString(); } static void displayAuthorizationDialog(String host) { String message = "The requested resource at '" + host + "' requires authorization."; Icon icon = null; int option = JOptionPane.showOptionDialog(IGV.getMainFrame(), message, "Error", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, new String[]{"Cancel", "Authorize"}, JOptionPane.YES_OPTION ); if (option == 1) { try { OAuthUtils.getInstance().openAuthorizationPage(); } catch (Exception e) { MessageUtils.showErrorMessage("Error fetching oAuth token", e); log.error("Error fetching oAuth tokens", e); } } } static Map<String, String> genomeIdMap = new HashMap<String, String>(); // A hack until readset meta data is available static { genomeIdMap = new HashMap<String, String>(); genomeIdMap.put("Google 10473108253681171589", "hg19"); genomeIdMap.put("Google 383928317087", "hg19"); genomeIdMap.put("Google 461916304629", "hg19"); genomeIdMap.put("Google 337315832689", "hg19"); } }
package org.mvel.block; import org.mvel.CompileException; import org.mvel.ExecutableStatement; import static org.mvel.MVEL.compileExpression; import org.mvel.Token; import org.mvel.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class AssertToken extends Token { public ExecutableStatement assertion; public AssertToken(char[] expr, int fields) { super(expr, fields); assertion = (ExecutableStatement) compileExpression(expr); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { try { Boolean bool = (Boolean) assertion.getValue(ctx, thisValue, factory); if (!bool) throw new AssertionError("assertion failed in expression: " + new String(this.name)); return bool; } catch (ClassCastException e) { throw new CompileException("assertion does not contain a boolean statement"); } } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } }
package org.concord.datagraph.ui; import java.awt.BorderLayout; import java.awt.Insets; import java.awt.geom.Point2D; import java.util.EventObject; import java.util.Hashtable; import javax.swing.JFrame; import javax.swing.JPanel; import org.concord.datagraph.engine.DataGraphAutoScaler; import org.concord.datagraph.engine.DataGraphAutoScroller; import org.concord.datagraph.engine.DataGraphable; import org.concord.framework.data.DataFlow; import org.concord.framework.data.stream.DataConsumer; import org.concord.framework.data.stream.DataProducer; import org.concord.framework.data.stream.DataStore; import org.concord.framework.data.stream.ProducerDataStore; import org.concord.graph.engine.AxisScale; import org.concord.graph.engine.CoordinateSystem; import org.concord.graph.engine.DefaultCoordinateSystem2D; import org.concord.graph.engine.GraphArea; import org.concord.graph.engine.GraphableList; import org.concord.graph.engine.MultiRegionAxisScale; import org.concord.graph.engine.SelectableList; import org.concord.graph.event.GraphWindowListener; import org.concord.graph.event.GraphWindowResizeEvent; import org.concord.graph.examples.DashedBox; import org.concord.graph.examples.GraphWindowToolBar; import org.concord.graph.ui.GraphWindow; import org.concord.graph.ui.Grid2D; import org.concord.graph.ui.SingleAxisGrid; /** * DataGraph * This is a panel with a graph and a toolbar on the right * The graph has one default graph area that is not the whole window, * The grid is drawn at the beginning (LEFT and BOTTOM) * and there is some space left for the axis labels. * * Date created: June 18, 2004 * * @author Scott Cytacki<p> * @author Ingrid Moncada<p> * */ public class DataGraph extends JPanel implements DataFlow, DataConsumer, GraphWindowListener { public final static int AUTO_FIT_NONE = 0; public final static int AUTO_SCALE_MODE = 1; public final static int AUTO_SCROLL_MODE = 2; //Graph, grid and toolbar protected GraphWindow graph; protected Grid2D grid; protected GraphWindowToolBar toolBar; protected Hashtable producers = new Hashtable(); protected GraphableList objList; protected DefaultCoordinateSystem2D defaultCS; protected GraphArea defaultGA; protected boolean adjustOriginOnReset = true; protected DashedBox selectionBox; protected boolean limitsSet = false; protected DataGraphAutoScaler scaler = null; protected DataGraphAutoScroller scroller = null; /** * Creates a default data graph that will have: a GraphWindow with a Grid2D that displays * the x axis at the bottom and the y axis at the left, with the origin at the bottom left * corner of the graph, with a default scale of 20 pixels per unit, with a default graph area * in the middle or the graph that has a margin of 5 pixels on the top/bottom, and 40 pixels * on the side. * It also has a toolbar to control the graph. */ public DataGraph() { // Graph //Create the graph graph = new GraphWindow(); defaultGA = graph.getDefaultGraphArea(); CoordinateSystem cs = defaultGA.getCoordinateSystem(); //Make sure we are using a DefaultCoordinateSystem2D if (!(cs instanceof DefaultCoordinateSystem2D)){ graph.setDefaultGraphArea(new GraphArea(new DefaultCoordinateSystem2D())); } defaultGA = graph.getDefaultGraphArea(); defaultCS = (DefaultCoordinateSystem2D)defaultGA.getCoordinateSystem(); defaultGA.setInsets(new Insets(5,40,40,5)); graph.addGraphWindowListener(this); //By default, the origin is the lower left corner of the graph area setOriginOffsetPercentage(0,0); //setOriginOffsetDisplay(20, 0); //defaultGA.setYCentered(true); // Grid grid = createGrid(); //Add the grid to the graph graph.addDecoration(grid); // Tool Bar toolBar = new GraphWindowToolBar(); toolBar.setGraphWindow(graph); toolBar.setGrid(grid); toolBar.setButtonsMargin(0); toolBar.setFloatable(false); selectionBox = new DashedBox(); selectionBox.setVisible(false); graph.add(selectionBox); // List of Graphable Objects objList = new SelectableList(); graph.add(objList); setLayout(new BorderLayout()); add(graph); add(toolBar, BorderLayout.EAST); initScaleObject(); } /** * Creates a default data graph with or without a tool bar * @param showToolbar indicates if the toolbar should be visible or not */ public DataGraph(boolean showToolbar) { this(); toolBar.setVisible(showToolbar); } protected Grid2D createGrid() { Grid2D gr = new Grid2D(); //gr.setInterval(1.0,1.0); //gr.setLabelFormat(new DecimalFormat(" gr.getXGrid().setAxisLabelSize(12); gr.getYGrid().setAxisLabelSize(12); gr.getXGrid().setAxisDrawMode(SingleAxisGrid.BEGINNING); gr.getYGrid().setAxisDrawMode(SingleAxisGrid.BEGINNING); gr.getXGrid().setDrawGridOnAxis(true); gr.getYGrid().setDrawGridOnAxis(true); gr.useAutoTickScaling(); return gr; } protected void initScaleObject() { addScaleAxis(defaultGA); } protected void addScaleAxis(GraphArea ga) { //Adding the scaling object for the graph area AxisScale axisScale = new MultiRegionAxisScale(getGrid()); axisScale.setGraphArea(ga); axisScale.setDragMode(AxisScale.DRAGMODE_NONE); axisScale.setShowMessage(false); axisScale.setShowCover(false); axisScale.setOriginDragFixPoint(false); graph.add(axisScale); toolBar.addAxisScale(axisScale); } /** * Returns the graph of this data graph (a GraphWindow object) * This is useful if you need to set the properties of the graph directly * @return */ public GraphWindow getGraph() { return graph; } /** * Returns the grid used in this data graph * @return */ public Grid2D getGrid() { return grid; } /** * Sets the selection on this data graph */ public void setSelection(float x, float y, float width, float height) { if(width < 0) { width=-width; x-=width; } if(height < 0) { height=-height; y-=height; } selectionBox.setBounds(x,y,width,height); } /** * Zooms to the selection of this data graph (set with setSelection()) */ public void zoomSelection() { selectionBox.zoom(); } /** * Sets the scale of the coordinate system given the number of pixels * desired in a world unit * @param xScale Number of pixels per world unit (x direction) * @param yScale Number of pixels per world unit (y direction) */ public void setScale(double xScale, double yScale) { CoordinateSystem coord = getGraph().getDefaultGraphArea().getCoordinateSystem(); Point2D.Double scale = new Point2D.Double(xScale, yScale); coord.setScale(scale); } /** * Returns the scale of the x axis * @return */ public double getXScale() { CoordinateSystem coord = getGraph().getDefaultGraphArea().getCoordinateSystem(); return coord.getScale().getX(); } /** * Returns the scale of the y axis * @return */ public double getYScale() { CoordinateSystem coord = getGraph().getDefaultGraphArea().getCoordinateSystem(); return coord.getScale().getY(); } /** * Sets the position of the axes' origin, relative to * the UPPER LEFT corner of the graph area * @param xPos Position of the origin in the x direction, relative to the left edge (DISPLAY COORDINATES) * @param yPos Position of the origin in the x direction, relative to the left edge (DISPLAY COORDINATES) */ public void setOriginOffsetDisplay(double xPos, double yPos) { setOriginOffsetPercentage(-1, -1); //xPos and yPos are relative to the UPPER LEFT CORNER of the window xPos = xPos + defaultGA.getInsets().left; yPos = yPos + defaultGA.getInsets().top; Point2D.Double origin = new Point2D.Double(xPos, yPos); defaultCS.setOriginOffsetDisplay(origin); } /** * Sets the percentage of the position of the axes' origin, relative to * the LOWER LEFT corner of the window * The parameters (between 0 and 1) represent values as a * PERCENTAGE of the SIZE of the graph area. * 0 means the origin will be AT the LOWER LEFT corner * 1 means it will be at the opposite corner * 0.2 means the origin will be at a distance of 20% the size of the grap area, * from the lower left corner * @param originPercentageX Distance (x direction) from the origin to the left edge, as a percentage of * the WIDTH of the graph area (a value from 0 to 1) * @param originPercentageY Distance (y direction) from the origin to the lower edge, as a percentage of * the HEIGHT of the graph area (a value from 0 to 1) */ public void setOriginOffsetPercentage(double originPercentageX, double originPercentageY) { getGraph().getDefaultGraphArea().setOriginPositionPercentage(originPercentageX, originPercentageY); } public double getXOriginOffsetDisplay() { CoordinateSystem coord = getGraph().getDefaultGraphArea().getCoordinateSystem(); double xPos = coord.getOriginOffsetDisplay().getX(); //xPos is relative to the UPPER LEFT CORNER of the window xPos = xPos - defaultGA.getInsets().left; return xPos; } public double getYOriginOffsetDisplay() { CoordinateSystem coord = getGraph().getDefaultGraphArea().getCoordinateSystem(); double yPos = coord.getOriginOffsetDisplay().getY(); //yPos is relative to the UPPER LEFT CORNER of the window yPos = yPos - defaultGA.getInsets().top; return yPos; } protected void resetGraphArea() { //Reset graph areas if (adjustOriginOnReset){ defaultGA.adjustCoordinateSystem(); } } /** * Sets up the axis of the graph. * It will display values from minX to maxX on the X axis and * from minY to maxY on the Y axis * The values are ALL in WORLD COORDINATES! * @param minX minimum value displayed in the x axis (WORLD COORDINATES) * @param maxX maximum value displayed in the x axis (WORLD COORDINATES) * @param minY minimum value displayed in the y axis (WORLD COORDINATES) * @param maxY maximum value displayed in the y axis (WORLD COORDINATES) */ public void setLimitsAxisWorld(double minX, double maxX, double minY, double maxY) { setOriginOffsetPercentage(-1, -1); setSelection((float)minX, (float)minY, (float)(maxX - minX), (float)(maxY - minY)); zoomSelection(); limitsSet = true; } /** * Returns the current minimum x value shown in the X Axis * @return */ public double getMinXAxisWorld() { return defaultGA.getLowerLeftCornerWorld().getX(); } /** * Returns the current maximum x value shown in the X Axis * @return */ public double getMaxXAxisWorld() { return defaultGA.getUpperRightCornerWorld().getX(); } /** * Returns the current minimum y value shown in the Y Axis * @return */ public double getMinYAxisWorld() { return defaultGA.getLowerLeftCornerWorld().getY(); } /** * Returns the current minimum x value shown in the X Axis * @return */ public double getMaxYAxisWorld() { return defaultGA.getUpperRightCornerWorld().getY(); } /** * Adds to the graph a data graphable associated with the specified data producer * By default, it will create a DataGraphable with -1 as the channel for the x axis (dt) * and 0 as the channel of the y axis, * so that means it will graph dt vs. channel 0 * @param dataProducer data producer that will produce the data for the data graphable * @see org.concord.framework.datastream.DataConsumer#addDataProducer(org.concord.framework.datastream.DataProducer) */ public void addDataProducer(DataProducer dataProducer) { addDataProducer(dataProducer, defaultGA); } /** * Adds to the graph a data graphable associated with the specified data producer * @param dataProducer * @param ga */ protected void addDataProducer(DataProducer dataProducer, GraphArea ga) { // Create a graphable for this data Producer // add it to the graph DataGraphable dGraphable = createDataGraphable(dataProducer); dGraphable.setGraphArea(ga); objList.add(dGraphable); } /** * Removes the first Data Graphable associated with the specified Data Producer * @see org.concord.framework.datastream.DataConsumer#removeDataProducer(org.concord.framework.datastream.DataProducer) */ public void removeDataProducer(DataProducer dataProducer) { //TODO it should use getGraphables (should return a Vector) and it should remove //ALL the graphables associated with the data producer, not only the first one //remove the associated dataProducer from //the graph DataGraphable dGraphable = getGraphable(dataProducer); if (dGraphable != null){ dGraphable.setDataProducer(null); objList.remove(dGraphable); } } /** * Returns the first Data Graphable in the graph that is associated with the specified * data producer. * @param dataProducer * @return */ public DataGraphable getGraphable(DataProducer dataProducer) { DataGraphable dGraphable = (DataGraphable)producers.get(dataProducer); if (dGraphable == null){ //Look for the first data graphable that has a data producer == dataProducer //TODO: it should actually return a list of graphables that have that data producer //specially for removeDataProducer //I think the vector thing should be returned in a new method: getGraphables() for (int i=0; i < objList.size(); i++){ Object obj = objList.elementAt(i); if (obj instanceof DataGraphable){ dGraphable = (DataGraphable)obj; if (dGraphable.getDataStore() instanceof ProducerDataStore){ if (((ProducerDataStore)dGraphable.getDataStore()).getDataProducer() == dataProducer){ return dGraphable; } } } } } return dGraphable; } /** * Creates a data graphable that will graph the data coming from the specified * data producer, using channelXAxis as the index for the channel that will be in the x axis * of the graph, and channelYAxis as the index for the channel that will be in the y axis. * If one of the indexes is -1, it will take the dt as the data for that axis * This data graphable can then be added to the graph * @param dataProducer * @param channelXAxis * @param channelYAxis */ public DataGraphable createDataGraphable(DataProducer dataProducer, int channelXAxis, int channelYAxis) { // Create a graphable for this dataProducer // add it to the graph DataGraphable dGraphable = new DataGraphable(); dGraphable.setDataProducer(dataProducer); dGraphable.setChannelX(channelXAxis); dGraphable.setChannelY(channelYAxis); producers.put(dataProducer, dGraphable); return dGraphable; } /** * Creates a data graphable that will graph the data coming from the specified * data store, using channelXAxis as the index for the channel that will be in the x axis * of the graph, and channelYAxis as the index for the channel that will be in the y axis. * If one of the indexes is -1, it will take the dt as the data for that axis * This data graphable can then be added to the graph * @param dataStore * @param channelXAxis * @param channelYAxis */ public DataGraphable createDataGraphable(DataStore dataStore, int channelXAxis, int channelYAxis) { // Create a graphable for this dataProducer // add it to the graph DataGraphable dGraphable = new DataGraphable(); dGraphable.setDataStore(dataStore); dGraphable.setChannelX(channelXAxis); dGraphable.setChannelY(channelYAxis); return dGraphable; } /** * Creates a data graphable that will graph the data coming from the specified * data store, using the first 2 channels of the data store (0 and 1) * It will use 0 as the index for the channel that will be in the x axis * of the graph, and 1 as the index for the channel that will be in the y axis. * This data graphable can then be added to the graph * @param dataStore */ public DataGraphable createDataGraphable(DataStore dataStore) { return createDataGraphable(dataStore, 0, 1); } /** * Creates a data graphable that will graph the data coming from the specified * data producer, using dt and the first channel for x and y respectively. * It will use -1 as the index for the channel that will be in the x axis (dt) * of the graph, and 0 as the index for the channel that will be in the y axis. * This data graphable can then be added to the graph * @param dataStore */ public DataGraphable createDataGraphable(DataProducer dataProducer) { return createDataGraphable(dataProducer, -1, 0); } /** * Adds a data graphable to the list of graphables * @param graphable data graphable to add */ public void add(DataGraphable graphable) { addDataGraphable(graphable); } /** * Adds a data graphable to the list of graphables * @param graphable data graphable to add */ public void addDataGraphable(DataGraphable graphable) { if (graphable.getGraphArea() == null){ graphable.setGraphArea(defaultGA); } objList.add(graphable); } /** * Removes a data graphable from the list of graphables * @param graphable data graphable to remove */ public void removeDataGraphable(DataGraphable graphable) { objList.remove(graphable); } /** * Returns the top-level list of graphables of this graph * @return */ public GraphableList getObjList() { return objList; } /** * Returns the toolbar of this graph * @return */ public GraphWindowToolBar getToolBar() { return toolBar; } /** * Returns if the graph should adjust the origin offset to the original origin offset * when the graph is reset * @return */ public boolean isAdjustOriginOffsetOnReset() { return adjustOriginOnReset; } /** * Sets if the graph should adjust the origin offset to the original origin offset * when the graph is reset * @param adjustOnReset */ public void setAdjustOriginOffsetOnReset(boolean adjustOnReset) { this.adjustOriginOnReset = adjustOnReset; } //Testing purposes public static void main(String args[]) { final JFrame frame = new JFrame(); final JPanel fa = new DataGraph(); frame.getContentPane().add(fa); frame.setSize(800,600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } /* (non-Javadoc) * @see org.concord.graph.event.GraphWindowListener#windowChanged(java.util.EventObject) */ public void windowChanged(EventObject e) { } /* (non-Javadoc) * @see org.concord.graph.event.GraphWindowListener#windowResized(org.concord.graph.event.GraphWindowResizeEvent) */ public void windowResized(GraphWindowResizeEvent e) { if (limitsSet){ zoomSelection(); } } /** * @see org.concord.framework.data.DataFlow#stop() */ public void stop() { //TODO: Not supported yet } /** * @see org.concord.framework.data.DataFlow#start() */ public void start() { //TODO: Not supported yet } /** * Resets all the graphables in the data graph * @see org.concord.framework.data.DataFlow#reset() */ public void reset() { //Reset each data graphable for(int i=0; i<objList.size(); i++) { if(objList.elementAt(i) instanceof DataGraphable) { DataGraphable dGraphable = (DataGraphable)objList.elementAt(i); dGraphable.reset(); } } resetGraphArea(); } /* public final static int AUTO_FIT_NONE = 0; public final static int AUTO_SCALE_MODE = 1; public final static int AUTO_SCROLL_MODE = 2; */ /** * sets the mode used to resize the graph as new points are added * AUTO_FIT_NONE - don't resize the graph automatically * AUTO_SCALE_MODE - change the scale of the graph so all the data is * visible. If you want to customize the behavior of this mode * you can use the getAutoScaler() method and customize the returned * object. * AUTO_SCROLL_MODE - change the position of the display origin, * so new data is visible. If you want to customize the behavior of * this mode you can use the getAutoScroller() method and customize * the returned object. */ public void setAutoFitMode(int mode) { switch(mode){ case AUTO_FIT_NONE: if (scaler != null) { scaler.setEnabled(false); } if (scroller != null) { scroller.setEnabled(false); } break; case AUTO_SCALE_MODE: getAutoScaler(); scaler.setEnabled(true); if (scroller != null) { scroller.setEnabled(false); } break; case AUTO_SCROLL_MODE: getAutoScroller(); scroller.setEnabled(true); if (scaler != null) { scaler.setEnabled(false); } break; default: throw new RuntimeException("Invalid fit mode: " + mode); } } /** * Get the object used for auto scaling. This object can be * configured to change the behavior of auto scaling. * @return */ public DataGraphAutoScaler getAutoScaler() { if(scaler == null) { scaler = new DataGraphAutoScaler(); scaler.setGraph(this); scaler.setGraphables(getObjList()); scaler.setEnabled(false); } return scaler; } /** * Get the object used for auto scrolling. This object can be * configured to change the behavior of auto scrolling. * @return */ public DataGraphAutoScroller getAutoScroller() { if(scroller == null) { // This needs to be adjust based on the graph dimensions scroller = new DataGraphAutoScroller(6,4); scroller.setGraph(this); scroller.setGraphables(getObjList()); scroller.setMinXValue(0); // This needs to be adjust based on the graph dimensions scroller.setXPadding(1,5); scroller.setEnabled(false); } return scroller; } }
package org.swingeasy; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Locale; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SwingConstants; import net.miginfocom.swing.MigLayout; /** * @author Jurgen */ public class SearchDialog extends JDialog implements EComponentI { private static final long serialVersionUID = -7658724511534306863L; protected final ETextArea textComponent; protected boolean replacing; protected EButton btnReplaceAll; protected EButton btnClose; protected ELabel lblFind; protected EButton btnHighlightAll; protected ETextField tfFind; protected EButton btnFind; protected ETextField tfReplace; protected EButton btnReplace; protected ECheckBox cbReplace; public SearchDialog(boolean replacing, ETextArea textComponent) { super(UIUtils.getRootWindow(textComponent), Messages.getString((Locale) null, "SearchDialog.title"), ModalityType.MODELESS); this.textComponent = textComponent; this.init(); this.setLocationRelativeTo(textComponent); this.setReplacing(replacing); UIUtils.registerLocaleChangeListener((EComponentI) this); } protected void closed() { // this.textComponent.removeHighlights(); } protected void find(String find) { this.textComponent.find(find); } protected EButton getBtnClose() { if (this.btnClose == null) { this.btnClose = new EButton(new EButtonConfig()); } return this.btnClose; } protected EButton getBtnFind() { if (this.btnFind == null) { this.btnFind = new EButton(new EButtonConfig()); } return this.btnFind; } protected EButton getBtnHighlightAll() { if (this.btnHighlightAll == null) { this.btnHighlightAll = new EButton(new EButtonConfig()); } return this.btnHighlightAll; } protected EButton getBtnReplace() { if (this.btnReplace == null) { this.btnReplace = new EButton(new EButtonConfig()); } return this.btnReplace; } protected EButton getBtnReplaceAll() { if (this.btnReplaceAll == null) { this.btnReplaceAll = new EButton(new EButtonConfig()); } return this.btnReplaceAll; } protected ECheckBox getCbReplace() { if (this.cbReplace == null) { this.cbReplace = new ECheckBox(new ECheckBoxConfig()); this.cbReplace.setHorizontalAlignment(SwingConstants.RIGHT); } return this.cbReplace; } protected ELabel getLblFind() { if (this.lblFind == null) { this.lblFind = new ELabel(new ELabelConfig("").setHorizontalAlignment(SwingConstants.RIGHT)); } return this.lblFind; } protected JTextField getTfFind() { if (this.tfFind == null) { this.tfFind = new ETextField(new ETextFieldConfig()); } return this.tfFind; } protected JTextField getTfReplace() { if (this.tfReplace == null) { this.tfReplace = new ETextField(new ETextFieldConfig()); } return this.tfReplace; } protected void highlightAll(String find) { this.textComponent.highlightAll(find); } protected void init() { this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { try { SearchDialog.this.closed(); } catch (Exception ex) { ex.printStackTrace(); } } }); String layoutConstraints = "wrap 4, insets 5 5 0 5"; String colConstraints = "[right,fill]rel[grow,fill,220::]14px[fill,sg grp1]14px[fill,sg grp1]"; String rowConstraints = "[]rel[]rel[]0px"; this.setLayout(new MigLayout(layoutConstraints, colConstraints, rowConstraints)); this.add(this.getLblFind()); this.add(this.getTfFind()); this.add(this.getBtnFind()); this.add(this.getBtnHighlightAll(), "wrap"); this.add(this.getCbReplace()); this.getCbReplace().addValueChangeListener(new ValueChangeListener<Boolean>() { @Override public void valueChanged(Boolean value) { SearchDialog.this.setReplacing(value); } }); this.add(this.getTfReplace()); this.add(this.getBtnReplace()); this.add(this.getBtnReplaceAll(), "wrap"); this.add(new JLabel(), "span 3"); this.add(this.getBtnClose()); ActionListener findAction = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (SearchDialog.this.getTfFind().getText().trim().length() > 0) { try { SearchDialog.this.find(SearchDialog.this.getTfFind().getText().trim()); } catch (Exception ex) { ex.printStackTrace(); } } } }; this.tfFind.addActionListener(findAction); this.getBtnFind().addActionListener(findAction); this.getBtnHighlightAll().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (SearchDialog.this.getTfFind().getText().trim().length() > 0) { try { SearchDialog.this.highlightAll(SearchDialog.this.getTfFind().getText().trim()); } catch (Exception ex) { ex.printStackTrace(); } } } }); ActionListener replaceAtion = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (SearchDialog.this.getTfFind().getText().trim().length() > 0) { try { SearchDialog.this.replace(SearchDialog.this.getTfFind().getText().trim(), SearchDialog.this.getTfReplace().getText().trim()); } catch (Exception ex) { ex.printStackTrace(); } } } }; this.getTfReplace().addActionListener(replaceAtion); this.getBtnReplace().addActionListener(replaceAtion); this.getBtnReplaceAll().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (SearchDialog.this.getTfFind().getText().trim().length() > 0) { try { SearchDialog.this.replaceAll(SearchDialog.this.getTfFind().getText().trim(), SearchDialog.this.getTfReplace().getText() .trim()); } catch (Exception ex) { ex.printStackTrace(); } } } }); this.getBtnClose().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { SearchDialog.this.dispose(); } catch (Exception ex) { ex.printStackTrace(); } } }); this.pack(); this.setResizable(false); } public boolean isReplacing() { return this.replacing; } protected void replace(String find, String replace) { this.textComponent.replace(find, replace); } protected void replaceAll(String find, String replace) { this.textComponent.replaceAll(find, replace); } /** * * @see java.awt.Component#setLocale(java.util.Locale) */ @Override public void setLocale(Locale l) { super.setLocale(l); this.setTitle(Messages.getString(l, "SearchDialog.title")); this.getBtnReplaceAll().setText(Messages.getString(l, "SearchDialog.replace-all")); this.getBtnClose().setText(Messages.getString(l, "SearchDialog.cancelButtonText")); this.getLblFind().setText(Messages.getString(l, "SearchDialog.find") + ": "); this.getBtnHighlightAll().setText(Messages.getString(l, "SearchDialog.highlight-all")); this.getBtnFind().setText(Messages.getString(l, "SearchDialog.find")); this.getCbReplace().setText(Messages.getString(l, "SearchDialog.replace-by") + ": "); this.getBtnReplace().setText(Messages.getString(l, "SearchDialog.replace")); } public void setReplacing(boolean replacing) { this.replacing = replacing; this.getTfReplace().setEnabled(replacing); this.getBtnReplace().setEnabled(replacing); this.getBtnReplaceAll().setEnabled(replacing); this.getCbReplace().setSelected(replacing); } }
package org.ensembl.healthcheck; import java.util.*; import java.util.logging.*; import java.sql.*; import java.io.*; import java.util.regex.*; import junit.framework.*; import org.ensembl.healthcheck.util.*; /** * <p>TestRunner is a base class that provides utilities for running tests - * logging, the ability to find and run tests from certain locations, etc.</p> */ public class TestRunner { protected List allTests; // will hold an instance of each test protected List groupsToRun; protected Properties dbProps; private static Logger logger = Logger.getLogger("HealthCheckLogger"); /** Creates a new instance of TestRunner */ public TestRunner() { groupsToRun = new ArrayList(); } // TestRunner protected void readPropertiesFile() { String propsFile = System.getProperty("user.dir") + System.getProperty("file.separator") + "database.properties"; dbProps = Utils.readPropertiesFile(propsFile); logger.fine("Read database properties from " + propsFile); Enumeration e = dbProps.propertyNames(); String propName; while (e.hasMoreElements()) { propName = (String)e.nextElement(); logger.finer("\t" + propName + " = " + dbProps.getProperty(propName)); } } // readPropertiesFile public String[] getListOfDatabaseNames(String regexp, String preFilterRegexp) { Connection conn; String[] databaseNames = null; // open connection try { conn = DBUtils.openConnection(dbProps.getProperty("driver", "org.gjt.mm.mysql.Driver"), dbProps.getProperty("databaseURL", "kaka.sanger.ac.uk"), dbProps.getProperty("user", "anonymous"), dbProps.getProperty("password", "")); logger.fine("Opened connection to " + dbProps.getProperty("databaseURL", "kaka.sanger.ac.uk") + " as " + dbProps.getProperty("user", "anonymous")); databaseNames = DBUtils.listDatabases(conn, regexp, preFilterRegexp); if (databaseNames.length == 0) { logger.warning("No database names matched"); } conn.close(); logger.fine("Connection closed"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } return databaseNames; } // getDatabaseList protected void showDatabaseList(String regexp, String preFilterRegexp) { logger.fine("Listing databases matching " + regexp + " :\n"); String[] databaseList = getListOfDatabaseNames(regexp, preFilterRegexp); for (int i = 0; i < databaseList.length; i++) { logger.fine("\t" + databaseList[i]); } } // showDatabaseList protected List findAllTests() { ArrayList allTests = new ArrayList(); // some variables that will come in useful later on String thisClassName = this.getClass().getName(); String packageName = thisClassName.substring(0, thisClassName.lastIndexOf(".")); String directoryName = packageName.replace('.', File.separatorChar); logger.finest("Package name: " + packageName + " Directory name: " + directoryName); String runDir = System.getProperty("user.dir") + File.separator; // places to look ArrayList locations = new ArrayList(); locations.add(runDir + "src" + File.separator + directoryName); // same directory as this class locations.add(runDir + "build" + File.separator + directoryName); // ../build/<packagename> // look in each of the locations defined above Iterator it = locations.iterator(); while (it.hasNext()) { String location = (String)it.next(); File dir = new File(location); if (dir.exists()) { if (location.lastIndexOf('.') > -1 && location.substring(location.lastIndexOf('.')).equalsIgnoreCase("jar")) { // ToDo -check this addUniqueTests(allTests, findTestsInJar(location, packageName)); } else { addUniqueTests(allTests, findTestsInDirectory(location, packageName)); } } else { logger.info(dir.getAbsolutePath() + " does not exist, skipping."); } // if dir.exists } logger.finer("Found " + allTests.size() + " test case classes of which ."); return allTests; } // findAllTests protected void runAllTests(List allTests, String preFilterRegexp, boolean forceDatabases) { // check if allTests() has been populated if (allTests == null) { logger.warning("No tests to run! Call findAllTests() first?"); } if (allTests.size() == 0) { logger.warning("Warning: no tests found!"); return; } Iterator it = allTests.iterator(); while (it.hasNext()) { EnsTestCase testCase = (EnsTestCase)it.next(); if (testCase.inGroups(groupsToRun)) { logger.info("\tRunning test of type " + testCase.getClass().getName()); if (preFilterRegexp != null) { testCase.setPreFilterRegexp(preFilterRegexp); } if (forceDatabases) { // override built-in database regexp with the one specified on the command line testCase.setDatabaseRegexp(preFilterRegexp); } TestResult tr = testCase.run(); System.out.println("\n" + tr.getName() + " " + tr.getResult() + " " + tr.getMessage() + "\n"); // TBC } } } // runAllTests public DatabaseConnectionIterator getDatabaseConnectionIterator(String[] databaseNames) { return new DatabaseConnectionIterator(dbProps.getProperty("driver"), dbProps.getProperty("databaseURL"), dbProps.getProperty("user"), dbProps.getProperty("password"), databaseNames); } // getDatabaseConnectionIterator public List findTestsInDirectory(String dir, String packageName) { logger.info("Looking for tests in " + dir); ArrayList tests = new ArrayList(); File f = new File(dir); // find all classes that extend org.ensembl.healthcheck.EnsTestCase ClassFileFilenameFilter cnff = new ClassFileFilenameFilter(); File[] classFiles = f.listFiles(cnff); logger.finer("Examining " + classFiles.length + " class files ..."); // check if each class file extends EnsTestCase by checking its type // need to avoid trying to instantiate the abstract class EnsTestCase iteslf Class newClass; Object obj = new Object(); String baseClassName; for (int i = 0; i < classFiles.length; i++) { logger.finest(classFiles[i].getName()); baseClassName = classFiles[i].getName().substring(0, classFiles[i].getName().lastIndexOf(".")); try { newClass = Class.forName(packageName + "." + baseClassName); String className = newClass.getName(); if (!className.equals("org.ensembl.healthcheck.EnsTestCase") && !className.substring(className.length()-4).equals("Test") ) { // ignore JUnit tests obj = newClass.newInstance(); } } catch (Exception e) { e.printStackTrace(); } if (obj instanceof org.ensembl.healthcheck.EnsTestCase && !tests.contains(obj)) { ((EnsTestCase)obj).init(this); tests.add(obj); // note we store an INSTANCE of the test, not just its name //logger.info("Added test case " + obj.getClass().getName()); } } // for classFiles return tests; } // findTestsInDirectory public List findTestsInJar(String jarFileName, String packageName) { ArrayList tests = new ArrayList(); // TBC return tests; } // findTestsInJar /** * Add all tests in subList to mainList, <em>unless</em> the test is already a member of mainList. */ public void addUniqueTests(List mainList, List subList) { Iterator it = subList.iterator(); while (it.hasNext()) { EnsTestCase test = (EnsTestCase)it.next(); if (!testInList(test, mainList)) { // can't really use List.contains() as the lists store objects which may be different mainList.add(test); logger.info("Added " + test.getShortTestName() + " to the list of tests to run"); } else { logger.fine("Skipped " + test.getShortTestName() + " as it is already in the list of tests to run"); } } } // addUniqueTests public boolean testInList(EnsTestCase test, List list) { boolean inList = false; Iterator it = list.iterator(); while (it.hasNext()) { EnsTestCase thisTest = (EnsTestCase)it.next(); if (thisTest.getTestName().equals(test.getTestName())) { inList = true; } } return inList; } // testInList } // TestRunner
package quantisan.qte_lmax; import com.lmax.api.*; import com.lmax.api.account.LoginCallback; import com.lmax.api.account.LoginRequest; import com.lmax.api.heartbeat.HeartbeatCallback; import com.lmax.api.heartbeat.HeartbeatEventListener; import com.lmax.api.heartbeat.HeartbeatRequest; import com.lmax.api.heartbeat.HeartbeatSubscriptionRequest; import com.lmax.api.orderbook.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class ThinBot implements LoginCallback, HeartbeatEventListener, OrderBookEventListener, StreamFailureListener, Runnable { final static Logger logger = LoggerFactory.getLogger(ThinBot.class); private final static int HEARTBEAT_PERIOD = 2 * 60 * 1000; private Session session; private JedisPool pool; public static void main(String[] args) { String demoUrl = "https://testapi.lmaxtrader.com"; LmaxApi lmaxApi = new LmaxApi(demoUrl); ThinBot thinBot = new ThinBot(); lmaxApi.login(new LoginRequest("quantisan2", "J63VFqmXBaQStdAxKnD7", LoginRequest.ProductType.CFD_DEMO), thinBot); } @Override public void onLoginSuccess(Session session) { logger.info("Logged in, account details: {}.", session.getAccountDetails()); this.session = session; session.registerHeartbeatListener(this); session.registerOrderBookEventListener(this); session.registerStreamFailureListener(this); // subscribe to heatbeat // session.subscribe(new HeartbeatSubscriptionRequest(), new Callback() { public void onSuccess() { } @Override public void onFailure(final FailureResponse failureResponse) { throw new RuntimeException("Heartbeat subscription failed"); } }); // subscribe to instrument data // for (long instrumentId = 4001; instrumentId < 4018; instrumentId++) subscribeToInstrument(session, instrumentId); subscribeToInstrument(session, 100637); // Gold subscribeToInstrument(session, 100639); // Silver pool = new JedisPool(new JedisPoolConfig(), "localhost"); new Thread(this).start(); // heartbeat request session.start(); pool.destroy(); } @Override public void onLoginFailure(FailureResponse failureResponse) { throw new RuntimeException("Unable to login: " + failureResponse.getDescription(), failureResponse.getException()); } @Override public void notifyStreamFailure(Exception e) { logger.error("Stream failure. {}.", e); } // // Market data @Override public void notify(OrderBookEvent orderBookEvent) { Tick tick = new Tick(orderBookEvent); logger.debug(tick.toString()); if(tick.isValid()) { Jedis jedis = pool.getResource(); try { jedis.lpush(tick.getInstrumentName(), tick.toString()); jedis.expire(tick.getInstrumentName(), 3600); } finally { pool.returnResource(jedis); } } } private void subscribeToInstrument(final Session session, final long instrumentId) { session.subscribe(new OrderBookSubscriptionRequest(instrumentId), new Callback() { public void onSuccess() { logger.debug("Subscribed to instrument {}.", instrumentId); } public void onFailure(final FailureResponse failureResponse) { logger.warn("Failed to subscribe to instrument: {}.", instrumentId); logger.warn("{}. : {}.", failureResponse.getMessage(), failureResponse.getDescription()); } }); } // // // Heart Beat @Override public void notify(long accountId, String token) { } private void requestHeartbeat() { this.session.requestHeartbeat(new HeartbeatRequest("token"), new HeartbeatCallback() { @Override public void onSuccess(String token) { } @Override public void onFailure(FailureResponse failureResponse) { logger.warn(failureResponse.getMessage(), failureResponse.getDescription()); throw new RuntimeException("Heartbeat receive failed"); } }); } @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { Thread.sleep(HEARTBEAT_PERIOD); requestHeartbeat(); } } catch (InterruptedException e) { logger.warn("Fail to request heartbeat: {}.", e); } } // }
package org.exist.xupdate; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.TreeMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.exist.dom.DocumentSet; import org.exist.dom.NodeListImpl; import org.exist.dom.XMLUtil; import org.exist.storage.DBBroker; import org.exist.util.FastStringBuffer; import org.exist.xquery.PathExpr; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.parser.XQueryLexer; import org.exist.xquery.parser.XQueryParser; import org.exist.xquery.parser.XQueryTreeParser; import org.exist.xquery.value.Item; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.Type; import org.w3c.dom.Attr; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.collections.AST; /** * XUpdateProcessor.java * * @author Wolfgang Meier * */ public class XUpdateProcessor implements ContentHandler, LexicalHandler { public static final String MODIFICATIONS = "modifications"; // Modifications public static final String INSERT_AFTER = "insert-after"; public static final String INSERT_BEFORE = "insert-before"; public static final String REPLACE = "replace"; public static final String RENAME = "rename"; public static final String REMOVE = "remove"; public static final String APPEND = "append"; public static final String UPDATE = "update"; // node constructors public static final String COMMENT = "comment"; public static final String PROCESSING_INSTRUCTION = "processing-instruction"; public static final String TEXT = "text"; public static final String ATTRIBUTE = "attribute"; public static final String ELEMENT = "element"; public static final String VALUE_OF = "value-of"; public static final String VARIABLE = "variable"; public static final String IF = "if"; public final static String XUPDATE_NS = "http: private final static Logger LOG = Logger.getLogger(XUpdateProcessor.class); private NodeListImpl contents = null; private boolean inModification = false; private boolean inAttribute = false; private boolean preserveWhitespace = false; private Stack spaceStack = null; private Modification modification = null; private DocumentBuilder builder; private Document doc; private Stack stack = new Stack(); private Node currentNode = null; private DBBroker broker; private DocumentSet documentSet; private List modifications = new ArrayList(); private FastStringBuffer charBuf = new FastStringBuffer(6, 15, 5); private Map variables = new TreeMap(); private Map namespaces = new HashMap(10); private Stack conditionals = new Stack(); /** * Constructor for XUpdateProcessor. */ public XUpdateProcessor(DBBroker broker, DocumentSet docs) throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); this.builder = factory.newDocumentBuilder(); this.broker = broker; this.documentSet = docs; namespaces.put("xml", "http: } public XUpdateProcessor() throws ParserConfigurationException { this(null, null); } public void setBroker(DBBroker broker) { this.broker = broker; } public void setDocumentSet(DocumentSet docs) { this.documentSet = docs; } /** * Parse the input source into a set of modifications. * * @param is * @return an array of type Modification * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public Modification[] parse(InputSource is) throws ParserConfigurationException, IOException, SAXException { XMLReader reader = broker.getBrokerPool().getParserPool().borrowXMLReader(); try { reader.setProperty("http://xml.org/sax/properties/lexical-handler", this); reader.setFeature("http://xml.org/sax/features/namespaces", true); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); reader.setContentHandler(this); reader.parse(is); Modification mods[] = new Modification[modifications.size()]; return (Modification[]) modifications.toArray(mods); } finally { broker.getBrokerPool().getParserPool().returnXMLReader(reader); } } /** * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) */ public void setDocumentLocator(Locator locator) { } /** * @see org.xml.sax.ContentHandler#startDocument() */ public void startDocument() throws SAXException { // The default... this.preserveWhitespace = false; this.spaceStack = new Stack(); this.spaceStack.push("default"); } /** * @see org.xml.sax.ContentHandler#endDocument() */ public void endDocument() throws SAXException { } /** * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) */ public void startPrefixMapping(String prefix, String uri) throws SAXException { namespaces.put(prefix, uri); } /** * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ public void endPrefixMapping(String prefix) throws SAXException { namespaces.remove(prefix); } /** * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ public void startElement( String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { // save accumulated character content if (inModification && charBuf.length() > 0) { String normalized = charBuf.toString(); // final String normalized = preserveWhitespace ? charBuf.toString() : // charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH); if (normalized.length() > 0) { Text text = doc.createTextNode(normalized); if (stack.isEmpty()) { //LOG.debug("appending text to fragment: " + text.getData()); contents.add(text); } else { Element last = (Element) stack.peek(); last.appendChild(text); } } charBuf.setLength(0); } if (namespaceURI.equals(XUPDATE_NS)) { String select = null; if (localName.equals(MODIFICATIONS)) { startModifications(atts); return; } else if (localName.equals(VARIABLE)) { // variable declaration startVariableDecl(atts); return; } else if (IF.equals(localName)) { if (inModification) throw new SAXException("xupdate:if is not allowed inside a modification"); select = atts.getValue("test"); Conditional cond = new Conditional(broker, documentSet, select, namespaces, variables); conditionals.push(cond); return; } else if (VALUE_OF.equals(localName)) { if(!inModification) throw new SAXException("xupdate:value-of is not allowed outside a modification"); } else if (APPEND.equals(localName) || INSERT_BEFORE.equals(localName) || INSERT_AFTER.equals(localName) || REMOVE.equals(localName) || RENAME.equals(localName) || UPDATE.equals(localName) || REPLACE.equals(localName)) { if (inModification) throw new SAXException("nested modifications are not allowed"); select = atts.getValue("select"); if (select == null) throw new SAXException( localName + " requires a select attribute"); doc = builder.newDocument(); contents = new NodeListImpl(); inModification = true; } else if ( (ELEMENT.equals(localName) || ATTRIBUTE.equals(localName) || TEXT.equals(localName) || PROCESSING_INSTRUCTION.equals(localName) || COMMENT.equals(localName))) { if(!inModification) throw new SAXException( "creation elements are only allowed inside " + "a modification"); charBuf.setLength(0); } else throw new SAXException("Unknown XUpdate element: " + qName); // start a new modification section if (APPEND.equals(localName)) { String child = atts.getValue("child"); modification = new Append(broker, documentSet, select, child, namespaces, variables); } else if (UPDATE.equals(localName)) modification = new Update(broker, documentSet, select, namespaces, variables); else if (INSERT_BEFORE.equals(localName)) modification = new Insert(broker, documentSet, select, Insert.INSERT_BEFORE, namespaces, variables); else if (INSERT_AFTER.equals(localName)) modification = new Insert(broker, documentSet, select, Insert.INSERT_AFTER, namespaces, variables); else if (REMOVE.equals(localName)) modification = new Remove(broker, documentSet, select, namespaces, variables); else if (RENAME.equals(localName)) modification = new Rename(broker, documentSet, select, namespaces, variables); else if (REPLACE.equals(localName)) modification = new Replace(broker, documentSet, select, namespaces, variables); // process commands for node creation else if (ELEMENT.equals(localName)) { String name = atts.getValue("name"); if (name == null) throw new SAXException("element requires a name attribute"); int p = name.indexOf(':'); String namespace = ""; String prefix = ""; if (p > -1) { prefix = name.substring(0, p); if (name.length() == p + 1) throw new SAXException( "illegal prefix in qname: " + name); name = name.substring(p + 1); namespace = atts.getValue("namespace"); if(namespace == null) namespace = (String) namespaces.get(prefix); if (namespace == null) { throw new SAXException( "no namespace defined for prefix " + prefix); } } Element elem; if (namespace != null && namespace.length() > 0) { elem = doc.createElementNS(namespace, name); elem.setPrefix(prefix); } else elem = doc.createElement(name); if (stack.isEmpty()) { contents.add(elem); } else { Element last = (Element) stack.peek(); last.appendChild(elem); } this.setWhitespaceHandling((Element) stack.push(elem)); } else if (ATTRIBUTE.equals(localName)) { String name = atts.getValue("name"); if (name == null) throw new SAXException("attribute requires a name attribute"); int p = name.indexOf(':'); String namespace = ""; if (p > -1) { String prefix = name.substring(0, p); if (name.length() == p + 1) throw new SAXException( "illegal prefix in qname: " + name); namespace = atts.getValue("namespace"); if(namespace == null) namespace = (String) namespaces.get(prefix); if (namespace == null) throw new SAXException( "no namespace defined for prefix " + prefix); } Attr attrib = namespace != null && namespace.length() > 0 ? doc.createAttributeNS(namespace, name) : doc.createAttribute(name); if (stack.isEmpty()) { for(int i = 0; i < contents.getLength(); i++) { Node n = contents.item(i); String ns = n.getNamespaceURI(); if(ns == null) ns = ""; if(n.getNodeType() == Node.ATTRIBUTE_NODE && n.getLocalName().equals(name) && ns.equals(namespace)) throw new SAXException("The attribute " + attrib.getNodeName() + " cannot be specified twice"); } contents.add(attrib); } else { Element last = (Element) stack.peek(); if(namespace != null && last.hasAttributeNS(namespace, name) || namespace == null && last.hasAttribute(name)) throw new SAXException("The attribute " + attrib.getNodeName() + " cannot be specified " + "twice on the same element"); if (namespace != null) last.setAttributeNodeNS(attrib); else last.setAttributeNode(attrib); } inAttribute = true; currentNode = attrib; // process value-of } else if (VALUE_OF.equals(localName)) { select = atts.getValue("select"); if (select == null) throw new SAXException("value-of requires a select attribute"); Sequence seq = processQuery(select); LOG.debug("Found " + seq.getLength() + " items for value-of"); Item item; for (SequenceIterator i = seq.iterate(); i.hasNext();) { item = i.nextItem(); if(Type.subTypeOf(item.getType(), Type.NODE)) { Node node = XMLUtil.copyNode(doc, ((NodeValue)item).getNode()); if (stack.isEmpty()) contents.add(node); else { Element last = (Element) stack.peek(); last.appendChild(node); } } else { try { String value = item.getStringValue(); characters(value.toCharArray(), 0, value.length()); } catch(XPathException e) { throw new SAXException(e.getMessage(), e); } } } } } else if (inModification) { Element elem = namespaceURI != null && namespaceURI.length() > 0 ? doc.createElementNS(namespaceURI, qName) : doc.createElement(qName); Attr a; for (int i = 0; i < atts.getLength(); i++) { String name = atts.getQName(i); String nsURI = atts.getURI(i); if (name.startsWith("xmlns")) { // Why are these showing up? They are supposed to be stripped out? } else { a = nsURI != null ? doc.createAttributeNS(nsURI, name) : doc.createAttribute(name); a.setValue(atts.getValue(i)); if (nsURI != null) elem.setAttributeNodeNS(a); else elem.setAttributeNode(a); } } if (stack.isEmpty()) { contents.add(elem); } else { Element last = (Element) stack.peek(); last.appendChild(elem); } this.setWhitespaceHandling((Element) stack.push(elem)); } } private void startVariableDecl(Attributes atts) throws SAXException { String select = atts.getValue("select"); if (select == null) throw new SAXException("variable declaration requires a select attribute"); String name = atts.getValue("name"); if (name == null) throw new SAXException("variable declarations requires a name attribute"); createVariable(name, select); } private void startModifications(Attributes atts) throws SAXException { String version = atts.getValue("version"); if (version == null) throw new SAXException( "version attribute is required for " + "element modifications"); if (!version.equals("1.0")) throw new SAXException( "Version " + version + " of XUpdate " + "not supported."); } /** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (inModification && charBuf.length() > 0) { final String normalized = preserveWhitespace ? charBuf.toString() : charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH); if (normalized.length() > 0) { Text text = doc.createTextNode(normalized); if (stack.isEmpty()) { contents.add(text); } else { Element last = (Element) stack.peek(); last.appendChild(text); } } charBuf.setLength(0); } if (XUPDATE_NS.equals(namespaceURI)) { if (IF.equals(localName)) { Conditional cond = (Conditional) conditionals.pop(); modifications.add(cond); } else if (localName.equals(ELEMENT)) { this.resetWhitespaceHandling((Element) stack.pop()); } else if (localName.equals(ATTRIBUTE)) { inAttribute = false; } else if (localName.equals(APPEND) || localName.equals(UPDATE) || localName.equals(REMOVE) || localName.equals(RENAME) || localName.equals(REPLACE) || localName.equals(INSERT_BEFORE) || localName.equals(INSERT_AFTER)) { inModification = false; modification.setContent(contents); if(!conditionals.isEmpty()) { Conditional cond = (Conditional) conditionals.peek(); cond.addModification(modification); } else { modifications.add(modification); } modification = null; } } else if (inModification) { this.resetWhitespaceHandling((Element) stack.pop()); } } /** * @see org.xml.sax.ContentHandler#characters(char, int, int) */ public void characters(char[] ch, int start, int length) throws SAXException { if (inModification) { if (inAttribute) { Attr attr = (Attr)currentNode; String val = attr.getValue(); if(val == null) val = new String(ch, start, length); else val += new String(ch, start, length); attr.setValue(val); } else { charBuf.append(ch, start, length); } } } /** * @see org.xml.sax.ContentHandler#ignorableWhitespace(char, int, int) */ public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (this.preserveWhitespace) { if (this.inModification) { if (this.inAttribute) { Attr attr = (Attr) this.currentNode; String val = attr.getValue(); if(val == null) val = new String(ch, start, length); else val += new String(ch, start, length); attr.setValue(val); } else { this.charBuf.append(ch, start, length); } } } } private void setWhitespaceHandling(Element e) { String wsSetting = e.getAttributeNS("http: if ("preserve".equals(wsSetting)) { this.spaceStack.push(wsSetting); this.preserveWhitespace = true; } else if ("default".equals(wsSetting)) { this.spaceStack.push(wsSetting); this.preserveWhitespace = false; } // Otherwise, don't change what's currently in effect! } private void resetWhitespaceHandling(Element e) { String wsSetting = e.getAttributeNS("http: if ("preserve".equals(wsSetting) || "default".equals(wsSetting)) { // Since an opinion was expressed, restore what was previously set: this.spaceStack.pop(); if (0 == this.spaceStack.size()) { // This is the default... this.preserveWhitespace = false; } else { this.preserveWhitespace = ("preserve".equals(this.spaceStack.peek())); } } } /** * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) */ public void processingInstruction(String target, String data) throws SAXException { if (inModification && charBuf.length() > 0) { final String normalized = charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH); if (normalized.length() > 0) { Text text = doc.createTextNode(normalized); if (stack.isEmpty()) { LOG.debug("appending text to fragment: " + text.getData()); contents.add(text); } else { Element last = (Element) stack.peek(); last.appendChild(text); } } charBuf.setLength(0); } if (inModification) { ProcessingInstruction pi = doc.createProcessingInstruction(target, data); if (stack.isEmpty()) { contents.add(pi); } else { Element last = (Element) stack.peek(); last.appendChild(pi); } } } /** * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ public void skippedEntity(String name) throws SAXException { } private void createVariable(String name, String select) throws SAXException { LOG.debug("creating variable " + name + " as " + select); Sequence result = processQuery(select); LOG.debug("found " + result.getLength() + " for variable " + name); variables.put(name, result); } private Sequence processQuery(String select) throws SAXException { try { XQueryContext context = new XQueryContext(broker); context.setStaticallyKnownDocuments(documentSet); Map.Entry entry; for (Iterator i = namespaces.entrySet().iterator(); i.hasNext();) { entry = (Map.Entry) i.next(); context.declareNamespace( (String) entry.getKey(), (String) entry.getValue()); } for (Iterator i = variables.entrySet().iterator(); i.hasNext(); ) { entry = (Map.Entry) i.next(); context.declareVariable(entry.getKey().toString(), entry.getValue()); } XQueryLexer lexer = new XQueryLexer(context, new StringReader(select)); XQueryParser parser = new XQueryParser(lexer); XQueryTreeParser treeParser = new XQueryTreeParser(context); parser.xpath(); if (parser.foundErrors()) { throw new SAXException(parser.getErrorMessage()); } AST ast = parser.getAST(); LOG.debug("generated AST: " + ast.toStringTree()); PathExpr expr = new PathExpr(context); treeParser.xpath(ast, expr); if (treeParser.foundErrors()) { throw new SAXException(treeParser.getErrorMessage()); } expr.analyze(null, 0); Sequence seq = expr.eval(null, null); return seq; } catch (RecognitionException e) { LOG.warn("error while creating variable", e); throw new SAXException(e); } catch (TokenStreamException e) { LOG.warn("error while creating variable", e); throw new SAXException(e); } catch (XPathException e) { throw new SAXException(e); } } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int) */ public void comment(char[] ch, int start, int length) throws SAXException { if (inModification && charBuf.length() > 0) { final String normalized = charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH); if (normalized.length() > 0) { Text text = doc.createTextNode(normalized); if (stack.isEmpty()) { //LOG.debug("appending text to fragment: " + text.getData()); contents.add(text); } else { Element last = (Element) stack.peek(); last.appendChild(text); } } charBuf.setLength(0); } if (inModification) { Comment comment = doc.createComment(new String(ch, start, length)); if (stack.isEmpty()) { contents.add(comment); } else { Element last = (Element) stack.peek(); last.appendChild(comment); } } } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#endCDATA() */ public void endCDATA() throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#endDTD() */ public void endDTD() throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String) */ public void endEntity(String name) throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#startCDATA() */ public void startCDATA() throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String, java.lang.String) */ public void startDTD(String name, String publicId, String systemId) throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String) */ public void startEntity(String name) throws SAXException { } public void reset() { this.preserveWhitespace = false; this.spaceStack = null; this.inModification = false; this.inAttribute = false; this.modification = null; this.doc = null; this.contents = null; this.stack.clear(); this.currentNode = null; this.broker = null; this.documentSet = null; this.modifications.clear(); this.charBuf = new FastStringBuffer(6, 15, 5); this.variables.clear(); this.namespaces.clear(); this.conditionals.clear(); this.namespaces.put("xml", "http: } }
package seedu.tasklist.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.tasklist.model.task.DeadlineTask; import seedu.tasklist.model.task.EventTask; import seedu.tasklist.model.task.FloatingTask; import seedu.tasklist.model.task.ReadOnlyDeadlineTask; import seedu.tasklist.model.task.ReadOnlyEventTask; import seedu.tasklist.model.task.ReadOnlyTask; public class TaskCard extends UiPart<Region> { private static final String FXML = "TaskListCard.fxml"; @FXML private HBox cardPane; @FXML private Label name; @FXML private Label id; @FXML private Label comment; @FXML private Label priority; @FXML private Label startDate; @FXML private Label endDate; @FXML private Label status; @FXML private FlowPane tags; public TaskCard(ReadOnlyTask task, int displayedIndex) { super(FXML); String taskType = task.getType(); name.setText(task.getName().fullName); id.setText(displayedIndex + ". "); comment.setText(task.getComment().value); priority.setText("Priority: " + task.getPriority().value); status.setText(task.getStatus().toString()); initTags(task); switch(taskType) { case DeadlineTask.TYPE: startDate.setText("Deadline: " + ((ReadOnlyDeadlineTask) task).getDeadlineString()); endDate.setVisible(false); break; case EventTask.TYPE: startDate.setText("Start Date: " + ((ReadOnlyEventTask) task).getStartDateString()); endDate.setText("End Date: " + ((ReadOnlyEventTask) task).getEndDateString()); break; case FloatingTask.TYPE: startDate.setVisible(false); endDate.setVisible(false); break; } } private void initTags(ReadOnlyTask task) { task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } }
package org.geodroid.app; import java.io.File; import org.jeo.android.geopkg.GeoPackage; import org.jeo.android.mbtiles.MBTiles; import org.jeo.carto.CartoCSS; import org.jeo.csv.CSV; import org.jeo.data.DataRepository; import org.jeo.data.DataRepositoryView; import org.jeo.data.DirectoryRepository; import org.jeo.data.DriverRegistry; import org.jeo.data.JSONRepository; import org.jeo.data.StaticDriverRegistry; import org.jeo.data.mem.Memory; import org.jeo.geojson.GeoJSON; import android.os.Environment; /** * Create a DataRepositoryView that exposes data from a directory. * <p> * If not overridden by the user the default directory is named "GeoData" on the root of the SDCard * of the device, obtained from {@link Environment#getExternalStorageDirectory()}. * </p> * <p> * The registry will operate in one of two modes. If the specified data directory contains an * <tt>index.json</tt> file it will operate as {@link JSONRegistry}. Otherwise it will simply scan * the directory contains as {@link DirectoryRegistry}. * </p> * @author Justin Deoliveira, OpenGeo */ public class GeoDataRepository { /** * Returns the GeoData directory handle. */ public static File directory() { return new File(Environment.getExternalStorageDirectory(), "Geodata"); } public static DataRepositoryView create() { return create(null, null); } public static DataRepositoryView create(DriverRegistry drivers) { return create(null, drivers); } public static DataRepositoryView create(File dir, DriverRegistry drivers) { if (dir == null) { dir = directory(); } if (drivers == null) { drivers = new StaticDriverRegistry(new GeoPackage(), new MBTiles(), new GeoJSON(), new CSV(), new Memory(), new CartoCSS()); } if (!dir.isDirectory()) { throw new IllegalArgumentException("not a directory: " + dir.getPath()); } File index = new File(dir, "index.json"); DataRepository repo; if (index.exists()) { repo = new JSONRepository(index, drivers); } else { repo = new DirectoryRepository(dir, drivers); } return new DataRepositoryView(repo); } }
// $Id: MagicNumberReader.java,v 1.3 2004/05/25 02:00:33 belaban Exp $ package org.jgroups.conf; /** * Reads and maintains mapping between magic numbers and classes * @author Filip Hanik (<a href="mailto:filip@filip.net">filip@filip.net) * @version 1.0 */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.util.Util; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class MagicNumberReader { private static boolean xml_debug=false; public static final String MAGIC_NUMBER_FILE="jg-magic-map.xml"; public String mMagicNumberFile=MAGIC_NUMBER_FILE; protected static Log log=LogFactory.getLog(MagicNumberReader.class); public void setFilename(String file) { mMagicNumberFile=file; } /** * try to read the magic number configuration file as a Resource form the classpath using getResourceAsStream * if this fails this method tries to read the configuration file from mMagicNumberFile using a FileInputStream (not in classpath but somewhere else in the disk) * @return an array of ClassMap objects that where parsed from the file (if found) or an empty array if file not found or had en exception */ public ClassMap[] readMagicNumberMapping() { try { InputStream stream=getClass().getClassLoader().getResourceAsStream(mMagicNumberFile); // try to load the map from file even if it is not a Resource in the class path if(stream == null){ try{ if(log.isInfoEnabled()) log.info("Could not read " + mMagicNumberFile +" as Resource from the CLASSPATH, will try to read it from file."); stream = new FileInputStream(mMagicNumberFile); if(stream != null &&log.isInfoEnabled() ) log.info("Magic number File found at '" + mMagicNumberFile+"'" ); }catch(FileNotFoundException fnfe){ if(log.isWarnEnabled()) log.warn("Failed reading - '" + mMagicNumberFile + "' is not found, got error '"+fnfe.getLocalizedMessage()+"'. Please make sure it is in the CLASSPATH or in the Specified location. Will " + "continue, but marshalling will be slower"); } } if(stream == null) { return new ClassMap[0]; } return parse(stream); } catch(Exception x) { if(xml_debug) x.printStackTrace(); String error=Util.getStackTrace(x); if(log.isErrorEnabled()) log.error(error); } return new ClassMap[0]; } protected static ClassMap[] parse(InputStream stream) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setValidating(false); //for now DocumentBuilder builder=factory.newDocumentBuilder(); builder.setEntityResolver(new ClassPathEntityResolver()); Document document=builder.parse(stream); NodeList class_list=document.getElementsByTagName("class"); java.util.Vector v=new java.util.Vector(); for(int i=0; i < class_list.getLength(); i++) { if(class_list.item(i).getNodeType() == Node.ELEMENT_NODE) { v.addElement(parseClassData(class_list.item(i))); } } ClassMap[] data=new ClassMap[v.size()]; v.copyInto(data); return data; }//parse protected static ClassMap parseClassData(Node protocol) throws java.io.IOException { try { protocol.normalize(); int pos=0; NodeList children=protocol.getChildNodes(); /** * there should be 4 Element Nodes if we are not overriding * 1. description * 2. class-name * 3. preload * 4. magic-number */ String clazzname=null; String desc=null; String preload=null; String magicnumber=null; for(int i=0; i < children.getLength(); i++) { if(children.item(i).getNodeType() == Node.ELEMENT_NODE) { pos++; switch(pos) { case 1: desc=children.item(i).getFirstChild().getNodeValue(); break; case 2: clazzname=children.item(i).getFirstChild().getNodeValue(); break; case 3: preload=children.item(i).getFirstChild().getNodeValue(); break; case 4: magicnumber=children.item(i).getFirstChild().getNodeValue(); break; }//switch }//end if }//for return new ClassMap(clazzname, desc, Boolean.valueOf(preload).booleanValue(), Integer.valueOf(magicnumber).intValue()); } catch(Exception x) { if(x instanceof java.io.IOException) throw (java.io.IOException)x; else { if(xml_debug) x.printStackTrace(); String error=Util.getStackTrace(x); if(log.isErrorEnabled()) log.error(error); throw new java.io.IOException(x.getMessage()); }//end if }//catch } }
package si.mazi.rescu; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthException; import oauth.signpost.http.HttpRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import si.mazi.rescu.oauth.RescuOAuthRequestAdapter; import si.mazi.rescu.utils.HttpUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; /** * Various HTTP utility methods */ class HttpTemplate { public final static String CHARSET_UTF_8 = "UTF-8"; /** * if log level DEBUG is set to this class, response body will be logged. * Maximum logged length is truncated at this static variable */ public static int responseMaxLogLen = 4096; /** * if log level DEBUG is set to this class, request body will be logged. * Maximum logged length is truncated at this static variable */ public static int requestMaxLogLen = 4096; private final Logger log = LoggerFactory.getLogger(HttpTemplate.class); /** * Default request header fields */ private final Map<String, String> defaultHttpHeaders = new HashMap<>(); private final int connTimeout; private final int readTimeout; private final Proxy proxy; private final SSLSocketFactory sslSocketFactory; private final HostnameVerifier hostnameVerifier; private final OAuthConsumer oAuthConsumer; HttpTemplate(int readTimeout, String proxyHost, Integer proxyPort, SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier, OAuthConsumer oAuthConsumer) { this(0, readTimeout, proxyHost, proxyPort, sslSocketFactory, hostnameVerifier, oAuthConsumer); } HttpTemplate(int connTimeout, int readTimeout, String proxyHost, Integer proxyPort, SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier, OAuthConsumer oAuthConsumer) { this.connTimeout = connTimeout; this.readTimeout = readTimeout; this.sslSocketFactory = sslSocketFactory; this.hostnameVerifier = hostnameVerifier; this.oAuthConsumer = oAuthConsumer; defaultHttpHeaders.put("Accept-Charset", CHARSET_UTF_8); // defaultHttpHeaders.put("Content-Type", "application/x-www-form-urlencoded"); defaultHttpHeaders.put("Accept", "application/json"); // User agent provides statistics for servers, but some use it for content negotiation so fake good agents defaultHttpHeaders.put("User-Agent", "ResCU JDK/6 AppleWebKit/535.7 Chrome/16.0.912.36 Safari/535.7"); // custom User-Agent if (proxyHost == null || proxyPort == null) { proxy = Proxy.NO_PROXY; } else { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); log.info("Using proxy {}", proxy); } } HttpURLConnection send(String urlString, String requestBody, Map<String, String> httpHeaders, HttpMethod method) throws IOException { if (requestBody != null && requestBody.length() > 0) { log.debug("Executing {} request at {} body \n{}", method, urlString, truncate(requestBody, requestMaxLogLen)); } else { log.debug("Executing {} request at {}", method, urlString); } log.trace("Request headers = {}", httpHeaders); preconditionNotNull(urlString, "urlString cannot be null"); preconditionNotNull(httpHeaders, "httpHeaders should not be null"); int contentLength = requestBody == null ? 0 : requestBody.getBytes().length; HttpURLConnection connection = configureURLConnection(method, urlString, httpHeaders, contentLength); if (oAuthConsumer != null) { HttpRequest request = new RescuOAuthRequestAdapter(connection, requestBody); try { oAuthConsumer.sign(request); } catch (OAuthException e) { throw new RuntimeException("OAuth error", e); } } if (contentLength > 0) { // Write the request body OutputStream out = connection.getOutputStream(); out.write(requestBody.getBytes(CHARSET_UTF_8)); out.flush(); } return connection; } InvocationResult receive(HttpURLConnection connection) throws IOException { int httpStatus = connection.getResponseCode(); log.debug("Request http status = {}", httpStatus); if (log.isTraceEnabled()) { for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) { if (entry.getKey() != null) { log.trace("Header response property: key='{}', value='{}'", entry.getKey(), entry.getValue()); } } } InputStream inputStream = !HttpUtils.isErrorStatusCode(httpStatus) ? connection.getInputStream() : connection.getErrorStream(); String responseString = readInputStreamAsEncodedString(inputStream, connection); if (responseString != null && responseString.startsWith("\uFEFF")) { responseString = responseString.substring(1); } log.debug("Http call returned {}; response body:\n{}", httpStatus, truncate(responseString, responseMaxLogLen)); return new InvocationResult(responseString, httpStatus); } /** * Provides an internal convenience method to allow easy overriding by test classes * * @param method The HTTP method (e.g. GET, POST etc) * @param urlString A string representation of a URL * @param httpHeaders The HTTP headers (will override the defaults) * @param contentLength The Content-Length request property * @return An HttpURLConnection based on the given parameters * @throws IOException If something goes wrong */ private HttpURLConnection configureURLConnection(HttpMethod method, String urlString, Map<String, String> httpHeaders, int contentLength) throws IOException { preconditionNotNull(method, "method cannot be null"); preconditionNotNull(urlString, "urlString cannot be null"); preconditionNotNull(httpHeaders, "httpHeaders cannot be null"); HttpURLConnection connection = getHttpURLConnection(urlString); connection.setRequestMethod(method.name()); Map<String, String> headerKeyValues = new HashMap<>(defaultHttpHeaders); headerKeyValues.putAll(httpHeaders); for (Map.Entry<String, String> entry : headerKeyValues.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); log.trace("Header request property: key='{}', value='{}'", entry.getKey(), entry.getValue()); } // Perform additional configuration for POST if (contentLength > 0) { connection.setDoOutput(true); connection.setDoInput(true); } connection.setRequestProperty("Content-Length", Integer.toString(contentLength)); return connection; } protected HttpURLConnection getHttpURLConnection(String urlString) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection(proxy); if (readTimeout > 0) { connection.setReadTimeout(readTimeout); } if (connTimeout > 0) { connection.setConnectTimeout(connTimeout); } if (connection instanceof HttpsURLConnection) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; if (sslSocketFactory != null) { httpsConnection.setSSLSocketFactory(sslSocketFactory); } if (hostnameVerifier != null) { httpsConnection.setHostnameVerifier(hostnameVerifier); } } return connection; } /** * <p> * Reads an InputStream as a String allowing for different encoding types. This closes the stream at the end. * </p> * * @param inputStream The input stream * @param connection The HTTP connection object * @return A String representation of the input stream * @throws IOException If something goes wrong */ String readInputStreamAsEncodedString(InputStream inputStream, HttpURLConnection connection) throws IOException { if (inputStream == null) { return null; } BufferedReader reader = null; try { String responseEncoding = getResponseEncoding(connection); if (izGzipped(connection)) { inputStream = new GZIPInputStream(inputStream); } final InputStreamReader in = responseEncoding != null ? new InputStreamReader(inputStream, responseEncoding) : new InputStreamReader(inputStream, CHARSET_UTF_8); reader = new BufferedReader(in); StringBuilder sb = new StringBuilder(); for (String line; (line = reader.readLine()) != null; ) { sb.append(line); } return sb.toString(); } finally { inputStream.close(); if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } } } boolean izGzipped(HttpURLConnection connection) { return "gzip".equalsIgnoreCase(connection.getHeaderField("Content-Encoding")); } /** * Determine the response encoding if specified * * @param connection The HTTP connection * @return The response encoding as a string (taken from "Content-Type") */ String getResponseEncoding(URLConnection connection) { String charset = null; String contentType = connection.getHeaderField("Content-Type"); if (contentType != null) { for (String param : contentType.replace(" ", "").split(";")) { if (param.startsWith("charset=")) { charset = param.split("=", 2)[1]; break; } } } return charset; } private static void preconditionNotNull(Object what, String message) { if (what == null) { throw new NullPointerException(message); } } /** * This will truncate string toTruncate to maximum length or return it as is if shorter * @param toTruncate * @param maxLen * @return */ private String truncate(String toTruncate, int maxLen) { if (toTruncate == null) { return null; } if (toTruncate.length() <= maxLen) { return toTruncate; } return toTruncate.substring(0, maxLen); } }
package org.joval.scap.xccdf.engine; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintStream; import java.math.BigDecimal; import java.net.ConnectException; import java.net.URL; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.Hashtable; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import java.util.Properties; import java.util.PropertyResourceBundle; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.datatype.DatatypeConfigurationException; import org.w3c.dom.Element; import cpe.schemas.dictionary.ListType; import oval.schemas.common.GeneratorType; import oval.schemas.definitions.core.OvalDefinitions; import oval.schemas.results.core.ResultEnumeration; import oval.schemas.results.core.DefinitionType; import oval.schemas.systemcharacteristics.core.InterfaceType; import oval.schemas.systemcharacteristics.core.SystemInfoType; import oval.schemas.variables.core.VariableType; import xccdf.schemas.core.CheckContentRefType; import xccdf.schemas.core.CheckType; import xccdf.schemas.core.CheckExportType; import xccdf.schemas.core.CPE2IdrefType; import xccdf.schemas.core.GroupType; import xccdf.schemas.core.IdrefType; import xccdf.schemas.core.IdentityType; import xccdf.schemas.core.Model; import xccdf.schemas.core.ObjectFactory; import xccdf.schemas.core.ProfileSetValueType; import xccdf.schemas.core.ProfileType; import xccdf.schemas.core.RuleResultType; import xccdf.schemas.core.RuleType; import xccdf.schemas.core.ResultEnumType; import xccdf.schemas.core.ScoreType; import xccdf.schemas.core.SelectableItemType; import xccdf.schemas.core.TestResultType; import org.joval.intf.oval.IDefinitions; import org.joval.intf.oval.IEngine; import org.joval.intf.oval.IResults; import org.joval.intf.oval.ISystemCharacteristics; import org.joval.intf.plugin.IPlugin; import org.joval.intf.system.IBaseSession; import org.joval.intf.system.ISession; import org.joval.intf.system.ISessionProvider; import org.joval.intf.util.IObserver; import org.joval.intf.util.IProducer; import org.joval.plugin.PluginFactory; import org.joval.plugin.PluginConfigurationException; import org.joval.scap.arf.Report; import org.joval.scap.cpe.CpeException; import org.joval.scap.ocil.Checklist; import org.joval.scap.oval.Factories; import org.joval.scap.oval.OvalException; import org.joval.scap.oval.OvalFactory; import org.joval.scap.sce.SCEScript; import org.joval.scap.xccdf.Benchmark; import org.joval.scap.xccdf.Profile; import org.joval.scap.xccdf.TestResult; import org.joval.scap.xccdf.XccdfException; import org.joval.scap.xccdf.handler.OCILHandler; import org.joval.scap.xccdf.handler.OVALHandler; import org.joval.scap.xccdf.handler.SCEHandler; import org.joval.util.JOVALMsg; import org.joval.util.JOVALSystem; import org.joval.util.LogFormatter; import org.joval.xml.DOMTools; /** * XCCDF Processing Engine and Reporting Tool (XPERT) engine class. * * @author David A. Solin * @version %I% %G% */ public class Engine implements Runnable, IObserver { private static DatatypeFactory datatypeFactory = null; static { try { datatypeFactory = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException e) { JOVALMsg.getLogger().warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e); } } private Benchmark xccdf; private IPlugin plugin; private SystemInfoType sysinfo; private Collection<String> platforms; private Profile profile; private Hashtable<String, Checklist> checklists; private File ocilDir; private List<RuleType> rules = null; private List<GroupType> groups = null; private String phase = null; private Logger logger; private boolean verbose; private Report arfReport; private ObjectFactory factory; /** * Create an XCCDF Processing Engine using the specified XCCDF document bundle and jOVAL plugin. */ public Engine(Benchmark xccdf, Profile profile, Hashtable<String, Checklist> checklists, File ocilDir, IPlugin plugin, boolean verbose, Report arfReport) { this.xccdf = xccdf; this.profile = profile; this.checklists = checklists; this.ocilDir = ocilDir; this.plugin = plugin; this.verbose = verbose; this.arfReport = arfReport; logger = XPERT.logger; factory = new ObjectFactory(); } // Implement Runnable /** * Process the XCCDF document bundle. */ public void run() { Collection<RuleType> rules = profile.getSelectedRules(); if (rules.size() == 0) { logger.severe("No reason to evaluate!"); List<ProfileType> profiles = xccdf.getBenchmark().getProfile(); if (profiles.size() > 0) { logger.info("Try selecting a profile:"); for (ProfileType pt : profiles) { logger.info(" " + pt.getProfileId()); } } } else { logger.info("There are " + rules.size() + " rules to process for the selected profile"); HashSet<String> selectedIds = new HashSet<String>(); for (RuleType rule : rules) { selectedIds.add(rule.getId()); } boolean ocilComplete = true; if (checklists.size() == 0) { OCILHandler oh = new OCILHandler(xccdf, profile); if (oh.exportFiles(ocilDir)) { ocilComplete = false; } } if (!ocilComplete) { logger.info( "\n ***************** ATTENTION *****************\n\n" + " This XCCDF content requires OCIL result data.\n" + " Content has been exported to: " + ocilDir + "\n"); } else if (plugin.connect()) { List<Element> reports = new ArrayList<Element>(); TestResultType testResult = initializeResult(); // Perform the applicability tests, and if applicable, the automated checks if (isApplicable(reports)) { logger.info("The target system is applicable to the specified XCCDF"); processXccdf(testResult, reports); } else { logger.info("The target system is not applicable to the specified XCCDF"); } plugin.disconnect(); // Print results to the console, and add them to the ARF report. HashMap<String, RuleResultType> resultIndex = new HashMap<String, RuleResultType>(); for (RuleResultType rrt : testResult.getRuleResult()) { resultIndex.put(rrt.getIdref(), rrt); } for (RuleType rule : listAllRules()) { String ruleId = rule.getId(); if (resultIndex.containsKey(ruleId)) { logger.info(ruleId + ": " + resultIndex.get(ruleId).getResult()); } else { // Record unselected/unchecked rules RuleResultType rrt = factory.createRuleResultType(); rrt.setIdref(rule.getId()); if (selectedIds.contains(ruleId)) { rrt.setResult(ResultEnumType.NOTCHECKED); } else { rrt.setResult(ResultEnumType.NOTSELECTED); } if (rule.isSetCheck()) { for (CheckType check : rule.getCheck()) { rrt.getCheck().add(check); } } testResult.getRuleResult().add(rrt); } } try { reports.add(DOMTools.toElement(new TestResult(testResult))); } catch (Exception e) { logger.severe(LogFormatter.toString(e)); } makeArfReport(reports); xccdf.getBenchmark().getTestResult().add(testResult); } else { logger.info("Failed to connect to the target system"); } } logger.info("XCCDF processing complete."); } // Implement IObserver public void notify(IProducer sender, int msg, Object arg) { switch(msg) { case IEngine.MESSAGE_OBJECT_PHASE_START: logger.info("Beginning scan"); break; case IEngine.MESSAGE_OBJECT: logger.info("Scanning object " + (String)arg); break; case IEngine.MESSAGE_OBJECT_PHASE_END: logger.info("Scan complete"); break; case IEngine.MESSAGE_DEFINITION_PHASE_START: logger.info("Evaluating definitions"); break; case IEngine.MESSAGE_DEFINITION: logger.info("Evaluating " + (String)arg); break; case IEngine.MESSAGE_DEFINITION_PHASE_END: logger.info("Completed evaluating definitions"); break; case IEngine.MESSAGE_SYSTEMCHARACTERISTICS: // no-op break; } } // Private /** * This is the main routine, from which the selected checks are executed and compiled into the result. */ private void processXccdf(TestResultType testResult, List<Element> reports) { testResult.setStartTime(getTimestamp()); phase = "evaluation"; // Integrate OCIL results if (checklists != null) { OCILHandler ocilHandler = new OCILHandler(xccdf, profile, checklists); ocilHandler.integrateResults(testResult); if (verbose) { for (Checklist checklist : checklists.values()) { try { reports.add(DOMTools.toElement(checklist)); } catch (Exception e) { logger.severe(LogFormatter.toString(e)); } } } } // Run the OVAL engines OVALHandler ovalHandler = null; try { ovalHandler = new OVALHandler(xccdf, profile, plugin); } catch (Exception e) { logger.severe(LogFormatter.toString(e)); return; } for (String href : ovalHandler.getHrefs()) { IEngine engine = ovalHandler.getEngine(href); engine.getNotificationProducer().addObserver(this, IEngine.MESSAGE_MIN, IEngine.MESSAGE_MAX); logger.info("Evaluating OVAL rules"); engine.run(); switch(engine.getResult()) { case OK: if (verbose) { try { reports.add(DOMTools.toElement(engine.getResults())); } catch (Exception e) { logger.severe(LogFormatter.toString(e)); } } break; case ERR: logger.severe(LogFormatter.toString(engine.getError())); return; } engine.getNotificationProducer().removeObserver(this); } try { ovalHandler.integrateResults(testResult); } catch (OvalException e) { logger.severe(LogFormatter.toString(e)); } // Run the SCE scripts logger.info("Evaluating SCE rules"); if (plugin instanceof ISessionProvider) { IBaseSession base = ((ISessionProvider)plugin).getSession(); if (base instanceof ISession) { ISession session = (ISession)base; SCEHandler sceHandler = new SCEHandler(xccdf, profile, session); for (SCEScript script : sceHandler.getScripts()) { logger.info("Running SCE script: " + script.getId()); if (!script.exec()) { logger.warning("SCE script execution failed!"); } } sceHandler.integrateResults(testResult); } } testResult.setEndTime(getTimestamp()); // Compute scores logger.info("Computing scores..."); HashMap<String, RuleResultType> resultMap = new HashMap<String, RuleResultType>(); for (RuleResultType rrt : testResult.getRuleResult()) { resultMap.put(rrt.getIdref(), rrt); } // Note - only selected rules will be in the resultMap at this point for (Model model : xccdf.getBenchmark().getModel()) { logger.info("Scoring method: " + model.getSystem()); ScoreKeeper sk = computeScore(resultMap, xccdf.getBenchmark().getGroupOrRule(), ScoringModel.fromModel(model)); ScoreType scoreType = factory.createScoreType(); scoreType.setSystem(model.getSystem()); scoreType.setValue(new BigDecimal(Float.toString(sk.getScore()))); if (sk instanceof FlatScoreKeeper) { scoreType.setMaximum(new BigDecimal(Float.toString(((FlatScoreKeeper)sk).getMaxScore()))); } testResult.getScore().add(scoreType); } } private void makeArfReport(List<Element> reports) { try { String requestId = arfReport.addRequest(DOMTools.toElement(xccdf)); String assetId = arfReport.addAsset(sysinfo); for (Element report : reports) { arfReport.addReport(requestId, assetId, report); } } catch (Exception e) { logger.severe(LogFormatter.toString(e)); } } /** * Create a Benchmark.TestResult node, initialized with information gathered from the profile and plugin. */ private TestResultType initializeResult() { TestResultType testResult = factory.createTestResultType(); String id = xccdf.getBenchmark().getBenchmarkId(); String name = "unknown"; String namespace = "unknown"; if (id.startsWith("xccdf_")) { String temp = id.substring(6); int ptr = temp.lastIndexOf("_benchmark_"); if (ptr > 0) { namespace = temp.substring(0,ptr); name = temp.substring(ptr+11); } } testResult.setTestResultId("xccdf_" + namespace + "_testresult_" + name); testResult.setVersion(xccdf.getBenchmark().getVersion().getValue()); testResult.setTestSystem(XPERT.getMessage("product.name")); TestResultType.Benchmark trb = factory.createTestResultTypeBenchmark(); trb.setId(xccdf.getBenchmark().getBenchmarkId()); trb.setHref(xccdf.getHref()); testResult.setBenchmark(trb); if (profile.getName() != null) { IdrefType profileRef = factory.createIdrefType(); profileRef.setIdref(profile.getName()); testResult.setProfile(profileRef); } String user = ((ISessionProvider)plugin).getSession().getUsername(); if (user != null) { IdentityType identity = factory.createIdentityType(); identity.setValue(user); if ("root".equals(user) || "Administrator".equals(user)) { identity.setPrivileged(true); } identity.setAuthenticated(true); testResult.setIdentity(identity); } for (String href : profile.getCpePlatforms()) { CPE2IdrefType cpeRef = factory.createCPE2IdrefType(); cpeRef.setIdref(href); testResult.getPlatform().add(cpeRef); } try { sysinfo = plugin.getSystemInfo(); if (!testResult.getTarget().contains(sysinfo.getPrimaryHostName())) { testResult.getTarget().add(sysinfo.getPrimaryHostName()); } for (InterfaceType intf : sysinfo.getInterfaces().getInterface()) { if (!testResult.getTargetAddress().contains(intf.getIpAddress())) { testResult.getTargetAddress().add(intf.getIpAddress()); } } } catch (OvalException e) { logger.severe(LogFormatter.toString(e)); } return testResult; } /** * Test whether the XCCDF bundle's applicability rules are satisfied. */ private boolean isApplicable(List<Element> reports) { phase = "discovery"; logger.info("Determining system applicability..."); Collection<String> hrefs = profile.getPlatformDefinitionHrefs(); if (hrefs.size() == 0) { logger.info("No platforms specified, skipping applicability checks..."); return true; } for (String href : hrefs) { try { if (!isApplicable(profile.getDefinitions(href), profile.getPlatformDefinitionIds(href), reports)) { return false; } } catch (OvalException e) { logger.severe(LogFormatter.toString(e)); return false; } catch (NoSuchElementException e) { logger.severe("Cannot perform applicability checks: CPE OVAL definitions " + e.getMessage() + " were not found in the XCCDF datastream!"); return false; } } return true; } private boolean isApplicable(IDefinitions cpeOval, List<String> definitions, List<Element> reports) { IEngine engine = OvalFactory.createEngine(IEngine.Mode.DIRECTED, plugin); engine.getNotificationProducer().addObserver(this, IEngine.MESSAGE_MIN, IEngine.MESSAGE_MAX); engine.setDefinitions(cpeOval); try { for (String definition : definitions) { ResultEnumeration result = engine.evaluateDefinition(definition); switch(result) { case TRUE: logger.info("Passed def " + definition); break; default: logger.warning("Bad result " + result + " for definition " + definition); return false; } } if (verbose) { reports.add(DOMTools.toElement(engine.getResults())); } return true; } catch (Exception e) { logger.severe(LogFormatter.toString(e)); return false; } finally { engine.getNotificationProducer().removeObserver(this); } } /** * Recursively get all rules within the XCCDF document. */ private List<RuleType> listAllRules() { List<RuleType> rules = new Vector<RuleType>(); for (SelectableItemType item : xccdf.getBenchmark().getGroupOrRule()) { rules.addAll(getRules(item)); } return rules; } /** * Recursively list all selected rules within the SelectableItem. */ private List<RuleType> getRules(SelectableItemType item) { List<RuleType> rules = new Vector<RuleType>(); if (item instanceof RuleType) { rules.add((RuleType)item); } else if (item instanceof GroupType) { for (SelectableItemType child : ((GroupType)item).getGroupOrRule()) { rules.addAll(getRules(child)); } } return rules; } private String encode(String s) { return s.replace(System.getProperty("file.separator"), "~"); } private XMLGregorianCalendar getTimestamp() { XMLGregorianCalendar tm = null; if (datatypeFactory != null) { tm = datatypeFactory.newXMLGregorianCalendar(new GregorianCalendar()); } return tm; } enum ScoringModel { DEFAULT("urn:xccdf:scoring:default"), FLAT("urn:xccdf:scoring:flat"), FLAT_UNWEIGHTED("urn:xccdf:scoring:flat-unweighted"), ABSOLUTE("urn:xccdf:scoring:absolute"); private String uri; private ScoringModel(String uri) { this.uri = uri; } static ScoringModel fromModel(Model model) throws IllegalArgumentException { return fromUri(model.getSystem()); } static ScoringModel fromUri(String uri) throws IllegalArgumentException { for (ScoringModel model : values()) { if (model.uri.equals(uri)) { return model; } } throw new IllegalArgumentException(uri); } } /** * Recursively compute the score of a list of items. * * @param results a HashMap containing the results of all (i.e., exclusively) the /selected/ rules */ ScoreKeeper computeScore(HashMap<String, RuleResultType> results, List<SelectableItemType> items, ScoringModel model) throws IllegalArgumentException { switch(model) { case DEFAULT: return DefaultScoreKeeper.compute(results, items); case FLAT: return FlatScoreKeeper.compute(true, results, items); case FLAT_UNWEIGHTED: return FlatScoreKeeper.compute(false, results, items); case ABSOLUTE: return AbsoluteScoreKeeper.compute(results, items); default: throw new IllegalArgumentException(model.toString()); } } abstract static class ScoreKeeper { HashMap<String, RuleResultType> results; float score, count; ScoreKeeper(HashMap<String, RuleResultType> results) { this.results = results; score = 0; count = 0; } float getScore() { return score; } } static class DefaultScoreKeeper extends ScoreKeeper { static DefaultScoreKeeper compute(HashMap<String, RuleResultType> results, List<SelectableItemType> items) throws IllegalArgumentException { return new DefaultScoreKeeper(new DefaultScoreKeeper(results), items); } private int accumulator; private float weightedScore; DefaultScoreKeeper(HashMap<String, RuleResultType> results) { super(results); accumulator = 0; weightedScore = 0; } DefaultScoreKeeper(DefaultScoreKeeper parent, RuleType rule) { this(parent.results); if (results.containsKey(rule.getId())) { switch(results.get(rule.getId()).getResult()) { case NOTAPPLICABLE: case NOTCHECKED: case INFORMATIONAL: case NOTSELECTED: break; case PASS: score++; // fall-thru default: count++; break; } if (count == 0) { score = 0; } else { count = 1; score = 100 * score / count; } weightedScore = rule.getWeight().intValue() * score; } } DefaultScoreKeeper(DefaultScoreKeeper parent, GroupType group) { this(parent, group.getGroupOrRule()); weightedScore = group.getWeight().intValue() * score; } DefaultScoreKeeper(DefaultScoreKeeper parent, List<SelectableItemType> items) throws IllegalArgumentException { super(parent.results); for (SelectableItemType item : items) { DefaultScoreKeeper child = null; if (item instanceof RuleType) { child = new DefaultScoreKeeper(this, (RuleType)item); } else if (item instanceof GroupType) { child = new DefaultScoreKeeper(this, (GroupType)item); } else { throw new IllegalArgumentException(item.getClass().getName()); } if (child.count != 0) { score += child.weightedScore; count++; accumulator += item.getWeight().intValue(); } } if (accumulator > 0) { score = (score / accumulator); } } } static class FlatScoreKeeper extends ScoreKeeper { static FlatScoreKeeper compute(boolean weighted, HashMap<String, RuleResultType> results, List<SelectableItemType> items) throws IllegalArgumentException { return new FlatScoreKeeper(new FlatScoreKeeper(weighted, results), items); } private boolean weighted; private float max_score; FlatScoreKeeper(boolean weighted, HashMap<String, RuleResultType> results) { super(results); this.weighted = weighted; max_score = 0; } FlatScoreKeeper(FlatScoreKeeper parent, RuleType rule) { this(parent.weighted, parent.results); if (results.containsKey(rule.getId())) { switch(results.get(rule.getId()).getResult()) { case NOTAPPLICABLE: case NOTCHECKED: case INFORMATIONAL: case NOTSELECTED: break; case PASS: score++; // fall-thru default: count++; break; } if (count != 0) { int weight = rule.getWeight().intValue(); if (weighted) { max_score += weight; score = (weight * score / count); } else { if (weight == 0) { score = 0; } else { score = (score / count); } } } } } FlatScoreKeeper(FlatScoreKeeper parent, List<SelectableItemType> items) throws IllegalArgumentException { this(parent.weighted, parent.results); for (SelectableItemType item : items) { FlatScoreKeeper child = null; if (item instanceof RuleType) { child = new FlatScoreKeeper(this, (RuleType)item); } else if (item instanceof GroupType) { child = new FlatScoreKeeper(this, ((GroupType)item).getGroupOrRule()); } else { throw new IllegalArgumentException(item.getClass().getName()); } score += child.score; max_score += child.max_score; } } float getMaxScore() { return max_score; } } static class AbsoluteScoreKeeper extends FlatScoreKeeper { static AbsoluteScoreKeeper compute(HashMap<String, RuleResultType> results, List<SelectableItemType> items) throws IllegalArgumentException { return new AbsoluteScoreKeeper(new AbsoluteScoreKeeper(results), items); } AbsoluteScoreKeeper(HashMap<String, RuleResultType> results) { super(true, results); } AbsoluteScoreKeeper(AbsoluteScoreKeeper parent, List<SelectableItemType> items) throws IllegalArgumentException { super(parent, items); } @Override float getScore() { if (super.getScore() == getMaxScore()) { return 1; } else { return 0; } } } }
/* * $Id: ReindexingTask.java,v 1.16 2014-08-29 20:47:04 pgust Exp $ */ package org.lockss.metadata; import java.io.*; import java.lang.management.*; import java.sql.*; import java.util.*; import org.lockss.app.LockssDaemon; import org.lockss.config.TdbAu; import org.lockss.daemon.*; import org.lockss.db.DbException; import org.lockss.db.DbManager; import org.lockss.extractor.*; import org.lockss.extractor.ArticleMetadataExtractor.Emitter; import org.lockss.extractor.MetadataException.ValidationException; import org.lockss.metadata.ArticleMetadataBuffer.ArticleMetadataInfo; import org.lockss.metadata.MetadataManager.ReindexingStatus; import org.lockss.plugin.*; import org.lockss.scheduler.*; import org.lockss.util.*; /** * Implements a reindexing task that extracts metadata from all the articles in * the specified AU. */ public class ReindexingTask extends StepTask { private static Logger log = Logger.getLogger(ReindexingTask.class); // The default number of steps for this task. private static final int default_steps = 10; // The archival unit for this task. private final ArchivalUnit au; // The article metadata extractor for this task. private final ArticleMetadataExtractor ae; // The article iterator for this task. private Iterator<ArticleFiles> articleIterator = null; // The hashes of the text strings of the log messages already emitted for this // task's AU. Used to prevent duplicate messages from being logged. private final HashSet<Integer> auLogTable = new HashSet<Integer>(); // An indication of whether the AU being indexed is new to the index. private volatile boolean isNewAu = true; // An indication of whether the AU being indexed needs a full reindex private volatile boolean needFullReindex = false; // The status of the task: successful if true. private volatile ReindexingStatus status = ReindexingStatus.Running; // The number of articles indexed by this task. private volatile long indexedArticleCount = 0; // The number of articles updated by this task. private volatile long updatedArticleCount = 0; // ThreadMXBean times. private volatile long startCpuTime = 0; private volatile long startUserTime = 0; private volatile long startClockTime = 0; private volatile long startUpdateClockTime = 0; private volatile long endCpuTime = 0; private volatile long endUserTime = 0; private volatile long endClockTime = 0; // Archival unit properties. private final String auName; private final String auId; private final boolean auNoSubstance; private ArticleMetadataBuffer articleMetadataInfoBuffer = null; // The database manager. private final DbManager dbManager; // The metadata manager. private final MetadataManager mdManager; private final Emitter emitter; private int extractedCount = 0; private LockssWatchdog watchDog; private static ThreadMXBean tmxb = ManagementFactory.getThreadMXBean(); static { log.debug3("current thread CPU time supported? " + tmxb.isCurrentThreadCpuTimeSupported()); if (tmxb.isCurrentThreadCpuTimeSupported()) { tmxb.setThreadCpuTimeEnabled(true); } } /** * Constructor. * * @param theAu * An ArchivalUnit with the AU for the task. * @param theAe * An ArticleMetadataExtractor with the article metadata extractor to * be used. */ public ReindexingTask(ArchivalUnit theAu, ArticleMetadataExtractor theAe) { // NOTE: estimated window time interval duration not currently used. super( new TimeInterval(TimeBase.nowMs(), TimeBase.nowMs() + Constants.HOUR), 0, // estimatedDuration. null, // TaskCallback. null); // Object cookie. this.au = theAu; this.ae = theAe; this.auName = au.getName(); this.auId = au.getAuId(); this.auNoSubstance = AuUtil.getAuState(au).hasNoSubstance(); dbManager = LockssDaemon.getLockssDaemon().getDbManager(); mdManager = LockssDaemon.getLockssDaemon().getMetadataManager(); // The accumulator of article metadata. emitter = new ReindexingEmitter(); // Set the task event handler callback after construction to ensure that the // instance is initialized. callback = new ReindexingEventHandler(); } public void setWDog(LockssWatchdog watchDog) { this.watchDog = watchDog; } void pokeWDog() { watchDog.pokeWDog(); } /** * Cancels the current task without rescheduling it. */ @Override public void cancel() { if (!isFinished() && (status == ReindexingStatus.Running)) { status = ReindexingStatus.Failed; super.cancel(); setFinished(); } } /** * Extracts the metadata from the next group of articles. * * @param n * An int with the amount of work to do. * TODO: figure out what the amount of work means */ @Override public int step(int n) { final String DEBUG_HEADER = "step(): "; int steps = (n <= 0) ? default_steps : n; log.debug3(DEBUG_HEADER + "step: " + steps + ", has articles: " + articleIterator.hasNext()); while (!isFinished() && (extractedCount <= steps) && articleIterator.hasNext()) { log.debug3(DEBUG_HEADER + "Getting the next ArticleFiles..."); ArticleFiles af = articleIterator.next(); try { ae.extract(MetadataTarget.OpenURL(), af, emitter); } catch (IOException ex) { log.error("Failed to index metadata for full text URL: " + af.getFullTextUrl(), ex); setFinished(); if (status == ReindexingStatus.Running) { status = ReindexingStatus.Rescheduled; indexedArticleCount = 0; } } catch (PluginException ex) { log.error("Failed to index metadata for full text URL: " + af.getFullTextUrl(), ex); setFinished(); if (status == ReindexingStatus.Running) { status = ReindexingStatus.Failed; indexedArticleCount = 0; } } catch (RuntimeException ex) { log.error(" Caught unexpected Throwable for full text URL: " + af.getFullTextUrl(), ex); setFinished(); if (status == ReindexingStatus.Running) { status = ReindexingStatus.Failed; indexedArticleCount = 0; } } pokeWDog(); } log.debug3(DEBUG_HEADER + "isFinished() = " + isFinished()); if (!isFinished()) { // finished if all articles handled if (!articleIterator.hasNext()) { setFinished(); log.debug3(DEBUG_HEADER + "isFinished() = " + isFinished()); } } log.debug3(DEBUG_HEADER + "extractedCount = " + extractedCount); return extractedCount; } /** * Cancels and marks the current task for rescheduling. */ void reschedule() { if (!isFinished() && (status == ReindexingStatus.Running)) { status = ReindexingStatus.Rescheduled; super.cancel(); setFinished(); } } /** * Returns the task AU. * * @return an ArchivalUnit with the AU of this task. */ ArchivalUnit getAu() { return au; } /** * Returns the name of the task AU. * * @return a String with the name of the task AU. */ String getAuName() { return auName; } /** * Returns the auid of the task AU. * * @return a String with the auid of the task AU. */ String getAuId() { return auId; } /** * Returns the substance state of the task AU. * * @return <code>true</code> if AU has no substance, <code>false</code> * otherwise. */ boolean hasNoAuSubstance() { return auNoSubstance; } /** * Returns an indication of whether the AU has not yet been indexed. * * @return <code>true</code> if the AU has not yet been indexed, * <code>false</code> otherwise. */ boolean isNewAu() { return isNewAu; } /** * Returns an indication of whether the AU needs a full reindex. * * @return <code>true</code> if the AU needs a full reindex, * <code>false</code> otherwise. */ boolean needsFullReindex() { return needFullReindex; } /** * Provides the start time for indexing. * * @return a long with the start time in miliseconds since epoch (0 if not * started). */ long getStartTime() { return startClockTime; } /** * Provides the update start time. * * @return a long with the update start time in miliseconds since epoch (0 if * not started). */ long getStartUpdateTime() { return startUpdateClockTime; } /** * Provides the end time for indexing. * * @return a long with the end time in miliseconds since epoch (0 if not * finished). */ long getEndTime() { return endClockTime; } /** * Returns the reindexing status of this task. * * @return a ReindexingStatus with the reindexing status. */ ReindexingStatus getReindexingStatus() { return status; } /** * Returns the number of articles extracted by this task. * * @return a long with the number of articles extracted by this task. */ long getIndexedArticleCount() { return indexedArticleCount; } /** * Returns the number of articles updated by this task. * * @return a long with the number of articles updated by this task. */ long getUpdatedArticleCount() { return updatedArticleCount; } /** * Increments by one the number of articles updated by this task. */ void incrementUpdatedArticleCount() { this.updatedArticleCount++; } /** * Temporary * * @param evt */ protected void handleEvent(Schedule.EventType evt) { callback.taskEvent(this, evt); } /** * Issues a warning for this re-indexing task. * * @param s * A String with the warning message. */ void taskWarning(String s) { int hashcode = s.hashCode(); if (auLogTable.add(hashcode)) { log.warning(s); } } /** * Accumulator of article metadata. */ private class ReindexingEmitter implements Emitter { private final Logger log = Logger.getLogger(ReindexingEmitter.class); @Override public void emitMetadata(ArticleFiles af, ArticleMetadata md) { final String DEBUG_HEADER = "emitMetadata(): "; if (log.isDebug3()) { log.debug3(DEBUG_HEADER+"\n"+md.ppString(2)); } Map<String, String> roles = new HashMap<String, String>(); for (String key : af.getRoleMap().keySet()) { String value = af.getRoleAsString(key); if (log.isDebug3()) { log.debug3(DEBUG_HEADER + "af.getRoleMap().key = " + key + ", af.getRoleUrl(key) = " + value); } roles.put(key, value); } if (log.isDebug3()) { log.debug3(DEBUG_HEADER + "field access url: " + md.get(MetadataField.FIELD_ACCESS_URL)); } if (md.get(MetadataField.FIELD_ACCESS_URL) == null) { // temporary -- use full text url if not set // (should be set by metadata extractor) md.put(MetadataField.FIELD_ACCESS_URL, af.getFullTextUrl()); } md.putRaw(MetadataField.FIELD_FEATURED_URL_MAP.getKey(), roles); // Get the earliest fetch time of the metadata items URLs. long fetchTime = AuUtil.getAuUrlsEarliestFetchTime(au, roles.values()); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "fetchTime = " + fetchTime); md.put(MetadataField.FIELD_FETCH_TIME, String.valueOf(fetchTime)); try { validateDataAgainstTdb(new ArticleMetadataInfo(md), au); articleMetadataInfoBuffer.add(md); } catch (IOException ex) { throw new RuntimeException(ex); } extractedCount++; indexedArticleCount++; } /** * Validate data against TDB information. * * @param mdinfo * the ArticleMetadataInfo * @param au * An ArchivalUnit with the archival unit. * @throws ValidationException * if field is invalid */ private void validateDataAgainstTdb(ArticleMetadataInfo mdinfo, ArchivalUnit au) { HashSet<String> isbns = new HashSet<String>(); if (mdinfo.isbn != null) { isbns.add(mdinfo.isbn); } if (mdinfo.eisbn != null) { isbns.add(mdinfo.eisbn); } HashSet<String> issns = new HashSet<String>(); if (mdinfo.issn != null) { issns.add(mdinfo.issn); } if (mdinfo.eissn != null) { issns.add(mdinfo.eissn); } TdbAu tdbau = au.getTdbAu(); boolean isTitleInTdb = !au.isBulkContent(); String tdbauName = (tdbau == null) ? null : tdbau.getName(); String tdbauStartYear = (tdbau == null) ? au.getName() : tdbau.getStartYear(); String tdbauYear = (tdbau == null) ? null : tdbau.getYear(); String tdbauIsbn = null; String tdbauIssn = null; String tdbauEissn = null; String tdbauJournalTitle = null; // Check whether the TDB has title information. if (isTitleInTdb && (tdbau != null)) { // Yes: Get the title information from the TDB. tdbauIsbn = tdbau.getIsbn(); tdbauIssn = tdbau.getPrintIssn(); tdbauEissn = tdbau.getEissn(); tdbauJournalTitle = tdbau.getJournalTitle(); } if (tdbau != null) { // Validate journal title against the TDB journal title. if (tdbauJournalTitle != null) { if (!tdbauJournalTitle.equals(mdinfo.publicationTitle)) { if (mdinfo.publicationTitle == null) { taskWarning("tdb title is " + tdbauJournalTitle + " for " + tdbauName + " -- metadata title is missing"); } else { taskWarning("tdb title " + tdbauJournalTitle + " for " + tdbauName + " -- does not match metadata journal title " + mdinfo.publicationTitle); } } } // Validate ISBN against the TDB ISBN. if (tdbauIsbn != null) { if (!tdbauIsbn.equals(mdinfo.isbn)) { isbns.add(tdbauIsbn); if (mdinfo.isbn == null) { taskWarning("using tdb isbn " + tdbauIsbn + " for " + tdbauName + " -- metadata isbn missing"); } else { taskWarning("also using tdb isbn " + tdbauIsbn + " for " + tdbauName + " -- different than metadata isbn: " + mdinfo.isbn); } } else if (mdinfo.isbn != null) { taskWarning("tdb isbn missing for " + tdbauName + " -- should be: " + mdinfo.isbn); } } else if (mdinfo.isbn != null) { if (isTitleInTdb) { taskWarning("tdb isbn missing for " + tdbauName + " -- should be: " + mdinfo.isbn); } } // validate ISSN against the TDB ISSN. if (tdbauIssn != null) { if (tdbauIssn.equals(mdinfo.eissn) && (mdinfo.issn == null)) { taskWarning("tdb print issn " + tdbauIssn + " for " + tdbauName + " -- reported by metadata as eissn"); } else if (!tdbauIssn.equals(mdinfo.issn)) { // add both ISSNs so it can be found either way issns.add(tdbauIssn); if (mdinfo.issn == null) { taskWarning("using tdb print issn " + tdbauIssn + " for " + tdbauName + " -- metadata print issn is missing"); } else { taskWarning("also using tdb print issn " + tdbauIssn + " for " + tdbauName + " -- different than metadata print issn: " + mdinfo.issn); } } } else if (mdinfo.issn != null) { if (mdinfo.issn.equals(tdbauEissn)) { taskWarning("tdb eissn " + tdbauEissn + " for " + tdbauName + " -- reported by metadata as print issn"); } else if (isTitleInTdb) { taskWarning("tdb issn missing for " + tdbauName + " -- should be: " + mdinfo.issn); } } // Validate EISSN against the TDB EISSN. if (tdbauEissn != null) { if (tdbauEissn.equals(mdinfo.issn) && (mdinfo.eissn == null)) { taskWarning("tdb eissn " + tdbauEissn + " for " + tdbauName + " -- reported by metadata as print issn"); } else if (!tdbauEissn.equals(mdinfo.eissn)) { // Add both ISSNs so that they can be found either way. issns.add(tdbauEissn); if (mdinfo.eissn == null) { taskWarning("using tdb eissn " + tdbauEissn + " for " + tdbauName + " -- metadata eissn is missing"); } else { taskWarning("also using tdb eissn " + tdbauEissn + " for " + tdbauName + " -- different than metadata eissn: " + mdinfo.eissn); } } } else if (mdinfo.eissn != null) { if (mdinfo.eissn.equals(tdbauIssn)) { taskWarning("tdb print issn " + tdbauIssn + " for " + tdbauName + " -- reported by metadata as print eissn"); } else if (isTitleInTdb) { taskWarning("tdb eissn missing for " + tdbauName + " -- should be: " + mdinfo.eissn); } } // Validate publication date against the TDB year. String pubYear = mdinfo.pubYear; if (pubYear != null) { if (!tdbau.includesYear(mdinfo.pubYear)) { if (tdbauYear != null) { taskWarning("tdb year " + tdbauYear + " for " + tdbauName + " -- does not match metadata year " + pubYear); } else { taskWarning("tdb year missing for " + tdbauName + " -- should include year " + pubYear); } } } else { pubYear = tdbauStartYear; if (mdinfo.pubYear != null) { taskWarning("using tdb start year " + mdinfo.pubYear + " for " + tdbauName + " -- metadata year is missing"); } } } } } /** * The handler for reindexing lifecycle events. */ private class ReindexingEventHandler implements TaskCallback { private final Logger log = Logger.getLogger(ReindexingEventHandler.class); /** * Handles an event. * * @param task * A SchedulableTask with the task that has changed state. * @param type * A Schedule.EventType indicating the type of event. */ @Override public void taskEvent(SchedulableTask task, Schedule.EventType type) { long threadCpuTime = 0; long threadUserTime = 0; long currentClockTime = TimeBase.nowMs(); if (tmxb.isCurrentThreadCpuTimeSupported()) { threadCpuTime = tmxb.getCurrentThreadCpuTime(); threadUserTime = tmxb.getCurrentThreadUserTime(); } // TODO: handle task Success vs. failure? if (type == Schedule.EventType.START) { // Handle the start event. handleStartEvent(threadCpuTime, threadUserTime, currentClockTime); } else if (type == Schedule.EventType.FINISH) { // Handle the finish event. handleFinishEvent(task, threadCpuTime, threadUserTime, currentClockTime); } else { log.error("Received unknown reindexing lifecycle event type '" + type + "' for AU '" + auName + "' - Ignored."); } } /** * Handles a starting event. * * @param threadCpuTime * A long with the thread CPU time. * @param threadUserTime * A long with the thread user time. * @param currentClockTime * A long with the current clock time. */ private void handleStartEvent(long threadCpuTime, long threadUserTime, long currentClockTime) { final String DEBUG_HEADER = "handleStartEvent(): "; log.debug3(DEBUG_HEADER + "Starting to reindex AU: " + auName); // Remember the times at startup. startCpuTime = threadCpuTime; startUserTime = threadUserTime; startClockTime = currentClockTime; if (log.isDebug2()) { log.debug2(DEBUG_HEADER + "Reindexing task start for AU: " + au.getName() + " startCpuTime: " + startCpuTime / 1.0e9 + ", startUserTime: " + startUserTime / 1.0e9 + ", startClockTime: " + startClockTime / 1.0e3); } // Indicate that only new metadata after the last extraction is to be // included. MetadataTarget target = MetadataTarget.OpenURL(); Connection conn = null; String message = null; try { // Get a connection to the database. message = "Cannot obtain a database connection"; conn = dbManager.getConnection(); // Get the AU database identifier, if any. message = "Cannot find the AU identifier for AU = " + auId + " in the database"; Long auSeq = findAuSeq(conn); log.debug2(DEBUG_HEADER + "auSeq = " + auSeq); // Determine whether this is a new, never indexed, AU; isNewAu = auSeq == null; log.debug2(DEBUG_HEADER + "isNewAu = " + isNewAu); // Check whether this same AU has been indexed before. if (!isNewAu) { // Only allow incremental extraction if not doing full reindex needFullReindex = mdManager.needAuFullReindexing(conn, au); log.debug2(DEBUG_HEADER + "needFullReindex = " + needFullReindex); if (!needFullReindex) { long lastExtractTime = mdManager.getAuExtractionTime(conn, auSeq); log.debug2(DEBUG_HEADER + "lastExtractTime = " + lastExtractTime); target.setIncludeFilesChangedAfter(lastExtractTime); } } } catch (DbException dbe) { log.error(message + ": " + dbe); } finally { DbManager.safeRollbackAndClose(conn); } // The article iterator won't be null because only AUs with article // iterators are queued for processing. articleIterator = au.getArticleIterator(target); if (log.isDebug2()) { long articleIteratorInitTime = TimeBase.nowMs() - startClockTime; log.debug2(DEBUG_HEADER + "Starting reindexing task for au: " + au.getName() + " has articles? " + articleIterator.hasNext() + " initializing iterator took " + articleIteratorInitTime + "ms"); } try { articleMetadataInfoBuffer = new ArticleMetadataBuffer(new File(PlatformUtil.getSystemTempDir())); mdManager.notifyStartReindexingAu(au); } catch (IOException ioe) { log.error("Failed to set up pending AU '" + au.getName() + "' for re-indexing", ioe); setFinished(); if (status == ReindexingStatus.Running) { status = ReindexingStatus.Rescheduled; } } } /** * Handles a finishing event. * * @param task * A SchedulableTask with the task that has finished. * @param threadCpuTime * A long with the thread CPU time. * @param threadUserTime * A long with the thread user time. * @param currentClockTime * A long with the current clock time. */ private void handleFinishEvent(SchedulableTask task, long threadCpuTime, long threadUserTime, long currentClockTime) { final String DEBUG_HEADER = "handleFinishEvent(): "; log.debug3(DEBUG_HEADER + "Finishing reindexing (" + status + ") for AU: " + auName); if (status == ReindexingStatus.Running) { status = ReindexingStatus.Success; } Connection conn = null; startUpdateClockTime = currentClockTime; switch (status) { case Success: try { long removedArticleCount = 0L; // Get a connection to the database. conn = dbManager.getConnection(); // Check whether the plugin version used to obtain the metadata // stored in the database is older than the current plugin version. if (needFullReindex) { // Yes: Remove old AU metadata before adding new. removedArticleCount = mdManager.removeAuMetadataItems(conn, auId); log.debug3(DEBUG_HEADER + "removedArticleCount = " + removedArticleCount); } Iterator<ArticleMetadataInfo> mditr = articleMetadataInfoBuffer.iterator(); // Check whether there is any metadata to record. if (mditr.hasNext()) { // Yes: Write the AU metadata to the database. new AuMetadataRecorder((ReindexingTask) task, mdManager, au) .recordMetadata(conn, mditr); pokeWDog(); } // turn off full reindexing flag once full reindexing is complete if (needFullReindex) { mdManager.updateAuFullReindexing(conn, au, false); } // Remove the AU just re-indexed from the list of AUs pending to be // re-indexed. mdManager.removeFromPendingAus(conn, auId); // Complete the database transaction. DbManager.commitOrRollback(conn, log); // Update the successful re-indexing count. mdManager.addToSuccessfulReindexingTasks(ReindexingTask.this); // Update the total article count. mdManager.addToMetadataArticleCount(updatedArticleCount - removedArticleCount); break; } catch (MetadataException me) { e = me; log.warning("Error updating metadata at FINISH for " + status + " -- NOT rescheduling", e); log.warning("ArticleMetadataInfo = " + me.getArticleMetadataInfo()); status = ReindexingStatus.Failed; } catch (DbException dbe) { e = dbe; log.warning("Error updating metadata at FINISH for " + status + " -- rescheduling", e); status = ReindexingStatus.Rescheduled; } catch (RuntimeException re) { e = re; log.warning("Error updating metadata at FINISH for " + status + " -- NOT rescheduling", e); status = ReindexingStatus.Failed; } finally { DbManager.safeRollbackAndClose(conn); } // Fall through if SQL exception occurred during update. case Failed: case Rescheduled: // Reindexing not successful, so try again later if status indicates // the operation should be rescheduled. log.debug2(DEBUG_HEADER + "Reindexing task (" + status + ") did not finish for au " + au.getName()); mdManager.addToFailedReindexingTasks(ReindexingTask.this); try { // Get a connection to the database. conn = dbManager.getConnection(); mdManager.removeFromPendingAus(conn, au.getAuId()); if (status == ReindexingStatus.Failed) { log.debug2(DEBUG_HEADER + "Marking as broken reindexing task au " + au.getName()); // Add the failed AU to the pending list with the right priority to // avoid processing it again before the underlying problem is fixed. mdManager.addFailedIndexingAuToPendingAus(conn, au.getAuId()); } else if (status == ReindexingStatus.Rescheduled) { log.debug2(DEBUG_HEADER + "Rescheduling reindexing task au " + au.getName()); // Add the re-schedulable AU to the end of the pending list. mdManager.addToPendingAusIfNotThere(conn, Collections.singleton(au)); } // require full reindexing for reschedule task // if this task required full reindexing if (needFullReindex) { mdManager.updateAuFullReindexing(conn, au, true); } // Complete the database transaction. DbManager.commitOrRollback(conn, log); } catch (DbException dbe) { log.warning("Error updating pending queue at FINISH" + " for " + status, dbe); } finally { DbManager.safeRollbackAndClose(conn); } } articleIterator = null; endClockTime = TimeBase.nowMs(); if (tmxb.isCurrentThreadCpuTimeSupported()) { endCpuTime = tmxb.getCurrentThreadCpuTime(); endUserTime = tmxb.getCurrentThreadUserTime(); } // Display timings. if (log.isDebug2()) { long elapsedCpuTime = threadCpuTime - startCpuTime; long elapsedUserTime = threadUserTime - startUserTime; long elapsedClockTime = currentClockTime - startClockTime; log.debug2(DEBUG_HEADER + "Reindexing task finished (" + status + ") for au: " + au.getName() + " CPU time: " + elapsedCpuTime / 1.0e9 + " (" + endCpuTime / 1.0e9 + "), UserTime: " + elapsedUserTime / 1.0e9 + " (" + endUserTime / 1.0e9 + ") Clock time: " + elapsedClockTime / 1.0e3 + " (" + endClockTime / 1.0e3 + ")"); } // Release collected metadata info once finished. articleMetadataInfoBuffer.close(); articleMetadataInfoBuffer = null; synchronized (mdManager.activeReindexingTasks) { mdManager.activeReindexingTasks.remove(au.getAuId()); mdManager.notifyFinishReindexingAu(au, status); try { // Get a connection to the database. conn = dbManager.getConnection(); // Schedule another task if available. mdManager.startReindexing(conn); // Complete the database transaction. DbManager.commitOrRollback(conn, log); } catch (DbException dbe) { log.error("Cannot restart indexing", dbe); } finally { DbManager.safeRollbackAndClose(conn); } } } /** * Provides the identifier of the AU for this task. * * @param conn * A Connection with the database connection to be used. * @return a Long with the identifier of the AU for this task, if any. * @throws DbException * if any problem occurred accessing the database. */ private Long findAuSeq(Connection conn) throws DbException { final String DEBUG_HEADER = "findAuSeq(): "; Long auSeq = null; // Find the plugin. Long pluginSeq = mdManager.findPlugin(conn, PluginManager.pluginIdFromAuId(auId)); // Check whether the plugin exists. if (pluginSeq != null) { // Yes: Get the database identifier of the AU. String auKey = PluginManager.auKeyFromAuId(auId); auSeq = mdManager.findAu(conn, pluginSeq, auKey); log.debug2(DEBUG_HEADER + "auSeq = " + auSeq); } return auSeq; } } }
package tigase.util; import tigase.server.AbstractMessageReceiver; import tigase.server.Packet; import tigase.server.XMPPServer; import tigase.xml.Element; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import java.util.logging.Logger; /** * Describe class UpdatesChecker here. * * * Created: Fri Apr 18 09:35:32 2008 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class UpdatesChecker extends Thread { /** * Variable <code>log</code> is a class logger. */ private static final Logger log = Logger.getLogger("tigase.util.UpdatesChecker"); private static final long SECOND = 1000; private static final long MINUTE = 60 * SECOND; private static final long HOUR = 60 * MINUTE; private static final long DAY = 24 * HOUR; private static final String VERSION_URL = "http: private static final String FILE_START = "tigase-server-"; private int bugfix_ver = 0; private String intro_msg = null; private int major_ver = 0; private int minor_ver = 0; private AbstractMessageReceiver receiver = null; private long interval = 7 * DAY; private boolean stopped = false; /** * Constructs ... * * * @param interval * @param receiver * @param intro_msg */ public UpdatesChecker(long interval, AbstractMessageReceiver receiver, String intro_msg) { super(); this.interval = interval * DAY; // this.interval = 30*SECOND; this.receiver = receiver; this.intro_msg = intro_msg; setName("UpdatesChecker"); } /** * Method description * */ @Override public void run() { String version = XMPPServer.getImplementationVersion(); int idx = version.indexOf('-'); if (idx > 0) { version = version.substring(0, idx); } log.info("Server version: " + version); String[] nums = version.split("\\."); try { major_ver = Integer.parseInt(nums[0]); minor_ver = Integer.parseInt(nums[1]); bugfix_ver = Integer.parseInt(nums[2]); } catch (NumberFormatException e) { log.warning("Can not detect the server version.... " + version); } catch (Exception e) { log.log(Level.WARNING, "Problem parsing server version.... " + version, e); } while ( !stopped) { Element message = null; try { sleep(interval); URLConnection connection = new URL(VERSION_URL).openConnection(); connection.setConnectTimeout(1000 * 60); connection.setReadTimeout(1000 * 60); BufferedReader buffr = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; int major = 0; int minor = 0; int bugfix = 0; String build = ""; while ((line = buffr.readLine()) != null) { if (line.startsWith(FILE_START)) { String file = line.substring(FILE_START.length()); idx = file.indexOf('-'); version = file.substring(0, idx); log.info("Found version: " + version); nums = version.split("\\."); try { int major_t = Integer.parseInt(nums[0]); int minor_t = Integer.parseInt(nums[1]); int bugfix_t = Integer.parseInt(nums[2]); if ((major_t > major) || ((major_t == major) && (minor_t > minor)) || ((major_t == major) && (minor_t == minor) && (bugfix_t > bugfix))) { major = major_t; minor = minor_t; bugfix = bugfix_t; int b_idx = file.indexOf('.', idx); build = file.substring(idx, b_idx); } } catch (NumberFormatException e) { log.warning("Problem detecting new server version.... " + version); } } } if ((major > major_ver) || ((major == major_ver) && (minor > minor_ver)) || ((major == major_ver) && (minor == minor_ver) && (bugfix > bugfix_ver))) { String os_name = System.getProperty("os.name"); String link = null; if (os_name.toLowerCase().contains("windows")) { link = "http: + major + "." + minor + "." + bugfix + build + ".exe"; } else { link = "http: + major + "." + minor + "." + bugfix + build + ".tar.gz"; } message = new Element("message", new String[] { "to", "from" }, new String[] { receiver.getDefHostName().getDomain(), "updates.checker@" + receiver.getDefHostName() }); Element subject = new Element("subject", "Updates checker - new version of the Tigase server"); message.addChild(subject); Element body = new Element("body", "You are currently using: '" + major_ver + "." + minor_ver + "." + bugfix_ver + "' version of Tigase" + " server. A new version of the server has been released: '" + major + "." + minor + "." + bugfix + "' and it is available for" + " download at address: " + link + "\n\n" + intro_msg); message.addChild(body); receiver.addPacket(Packet.packetInstance(message)); } } catch (TigaseStringprepException e) { log.log(Level.WARNING, "Incorrect stanza address settings: " + message.toString(), e); } catch (FileNotFoundException e) { log.log(Level.WARNING, "Can not check the server updates"); } catch (IOException e) { log.log(Level.WARNING, "Can not check updates for URL: " + VERSION_URL, e); } catch (InterruptedException e) { stopped = true; } catch (Exception e) { log.log(Level.WARNING, "Unknown exception for: " + VERSION_URL, e); } } } } //~ Formatted in Sun Code Convention
package mondrian.spi.impl; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Dialect for Cloudera's Impala DB. * * @author cboyden * @since 2/11/13 */ public class ImpalaDialect extends HiveDialect { private final String flagsRegexp = "^(\\(\\?([a-zA-Z])\\)).*$"; private final Pattern flagsPattern = Pattern.compile(flagsRegexp); private final String escapeRegexp = "(\\\\Q([^\\\\Q]+)\\\\E)"; private final Pattern escapePattern = Pattern.compile(escapeRegexp); /** * Creates an ImpalaDialect. * * @param connection Connection * @throws java.sql.SQLException on error */ public ImpalaDialect(Connection connection) throws SQLException { super(connection); } public static final JdbcDialectFactory FACTORY = new JdbcDialectFactory( ImpalaDialect.class, DatabaseProduct.HIVE) { protected boolean acceptsConnection(Connection connection) { return super.acceptsConnection(connection) && isDatabase(DatabaseProduct.IMPALA, connection); } }; protected String deduceIdentifierQuoteString( DatabaseMetaData databaseMetaData) { return null; } @Override public DatabaseProduct getDatabaseProduct() { return DatabaseProduct.IMPALA; } @Override protected String generateOrderByNulls( String expr, boolean ascending, boolean collateNullsLast) { if (ascending) { return expr + " ASC"; } else { return expr + " DESC"; } } @Override public String generateOrderItem( String expr, boolean nullable, boolean ascending, boolean collateNullsLast) { String ret = null; if (nullable && collateNullsLast) { ret = "CASE WHEN " + expr + " IS NULL THEN 1 ELSE 0 END, "; } else { ret = "CASE WHEN " + expr + " IS NULL THEN 0 ELSE 1 END, "; } if (ascending) { ret += expr + " ASC"; } else { ret += expr + " DESC"; } return ret; } @Override public boolean allowsMultipleCountDistinct() { return false; } @Override public boolean allowsCompoundCountDistinct() { return true; } @Override public boolean requiresOrderByAlias() { return false; } @Override public boolean requiresAliasForFromQuery() { return true; } @Override public boolean supportsGroupByExpressions() { return false; } @Override public boolean allowsSelectNotInGroupBy() { return false; } @Override public String generateInline( List<String> columnNames, List<String> columnTypes, List<String[]> valueList) { return generateInlineGeneric( columnNames, columnTypes, valueList, null, false); } public boolean allowsJoinOn() { return false; } @Override public void quoteStringLiteral( StringBuilder buf, String value) { String quote = "\'"; String s0 = value; if (s0.contains("\\")) { s0.replaceAll("\\\\", "\\\\"); } if (s0.contains(quote)) { s0 = s0.replaceAll(quote, "\\\\" + quote); } buf.append(quote); buf.append(s0); buf.append(quote); } public boolean allowsRegularExpressionInWhereClause() { return true; } public String generateRegularExpression( String source, String javaRegex) { try { Pattern.compile(javaRegex); } catch (PatternSyntaxException e) { // Not a valid Java regex. Too risky to continue. return null; } // We might have to use case-insensitive matching final Matcher flagsMatcher = flagsPattern.matcher(javaRegex); boolean caseSensitive = true; if (flagsMatcher.matches()) { final String flags = flagsMatcher.group(2); if (flags.contains("i")) { caseSensitive = false; } } if (flagsMatcher.matches()) { javaRegex = javaRegex.substring(0, flagsMatcher.start(1)) + javaRegex.substring(flagsMatcher.end(1)); } final Matcher escapeMatcher = escapePattern.matcher(javaRegex); while (escapeMatcher.find()) { javaRegex = javaRegex.replace( escapeMatcher.group(1), escapeMatcher.group(2)); } final StringBuilder sb = new StringBuilder(); // Now build the string. if (caseSensitive) { sb.append(source); } else { sb.append("UPPER("); sb.append(source); sb.append(")"); } sb.append(" REGEXP "); if (caseSensitive) { quoteStringLiteral(sb, javaRegex); } else { quoteStringLiteral(sb, javaRegex.toUpperCase()); } return sb.toString(); } public boolean allowsDdl() { return true; } } // End ImpalaDialect.java
package org.ownage.dmdirc.parser; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.Enumeration; /** * IRC Parser. * * @author Shane Mc Cormack * @version $Id$ */ public class IRCParser implements Runnable { /** General Debug Information. */ public static final int ndInfo = 1; // Information /** Socket Debug Information. */ public static final int ndSocket = 2; // Socket Errors // public static final int ndSomething = 4; //Next thingy /** Used in Error Reporting, Error is potentially Fatal, Desync 99% Guarenteed! */ public static final int errFatal = 1; /** Used in Error Reporting, Error is not fatal, but is more severe than a warning. */ public static final int errError = 2; /** Used in Error Reporting, Error was an unexpected occurance, but shouldn't be anything to worry about. */ public static final int errWarning = 4; /** * Used in Error Reporting. * If an Error has this flag, it means the parser is able to continue running * Most errWarnings should have this flag. if Fatal or Error are not accomanied * with this flag, you should disconnect or risk problems further on. */ public static final int errCanContinue = 8; /** * Enable Development Debugging info - Outputs directly to console. * * This is used for debugging info that is generally of no use to most people * If this is set to false, self-test and any the "useless" debugging that relies on * this being true are not compiled. */ protected static final boolean bDebug = true; private Socket socket = null; private PrintWriter out = null; private BufferedReader in = null; /** * This is what the user wants settings to be. * Nickname here is *not* always accurate. * ClientInfo variable cMyself should be used for accurate info. */ public MyInfo me = new MyInfo(); /** Server Info requested by user. */ public ServerInfo server = new ServerInfo(); /** Name the server calls itself. */ protected String sServerName; /** This is what we think the nickname should be. */ protected String sThinkNickname; /** When using inbuilt pre-001 NickInUse handler, have we tried our AltNick. */ protected boolean TriedAlt = false; /** Have we recieved the 001. */ protected boolean Got001 = false; /** Has the thread started execution yet, (Prevents run() being called multiple times). */ protected boolean HasBegan = false; /** Is this line the first line we have seen? */ protected boolean IsFirst = true; // Better alternative to hashtable? /** Hashtable storing known prefix modes (ohv). */ protected Hashtable<Character,Integer> hPrefixModes = new Hashtable<Character,Integer>(); /** * Hashtable maping known prefix modes (ohv) to prefixes (@%+) - Both ways. * Prefix map contains 2 pairs for each mode. (eg @ => o and o => @) */ protected Hashtable<Character,Character> hPrefixMap = new Hashtable<Character,Character>(); /** Integer representing the next avaliable integer value of a prefix mode. */ protected int nNextKeyPrefix = 1; /** Hashtable storing known user modes (owxis etc). */ protected Hashtable<Character,Integer> hUserModes = new Hashtable<Character,Integer>(); /** Integer representing the next avaliable integer value of a User mode */ protected int nNextKeyUser = 1; /** * Hashtable storing known boolean chan modes (cntmi etc). * Valid Boolean Modes are stored as Hashtable.pub('m',1); where 'm' is the mode and 1 is a numeric value * Numeric values are powers of 2. This allows up to 32 modes at present (expandable to 64) * ChannelInfo/ChannelClientInfo etc provide methods to view the modes in a human way. * * Channel modes discovered but not listed in 005 are stored as boolean modes automatically (and a errWarning Error is called) */ protected Hashtable<Character,Integer> hChanModesBool = new Hashtable<Character,Integer>(); /** Integer representing the next avaliable integer value of a Boolean mode. */ protected int nNextKeyCMBool = 1; /** * Hashtable storing known non-boolean chan modes (klbeI etc). * Non Boolean Modes (for Channels) are stored together in this arraylist, the value param * is used to show the type of variable. (List (1), Param just for set (2), Param for Set and Unset (2+4=6)) * * @see cmList * @see cmSet * @see cmUnset */ protected Hashtable<Character,Byte> hChanModesOther = new Hashtable<Character,Byte>(); /** Byte used to show that a non-boolean mode is a list (b). */ protected static final byte cmList = 1; /** Byte used to show that a non-boolean mode is not a list, and requires a parameter to set (lk). */ protected static final byte cmSet = 2; /** Byte used to show that a non-boolean mode is not a list, and requires a parameter to unset (k). */ protected static final byte cmUnset = 4; /** * Channel Prefixes (ie # + etc). * The "value" for these is always true. */ protected Hashtable<Character,Boolean> hChanPrefix = new Hashtable<Character,Boolean>(); /** Hashtable storing all known clients based on nickname (in lowercase). */ protected Hashtable<String,ClientInfo> hClientList = new Hashtable<String,ClientInfo>(); /** Hashtable storing all known channels based on chanel name (inc prefix - in lowercase). */ protected Hashtable<String,ChannelInfo> hChannelList = new Hashtable<String,ChannelInfo>(); /** Reference to the ClientInfo object that references ourself. */ protected ClientInfo cMyself = null; /** Hashtable storing all information gathered from 005. */ protected Hashtable<String,String> h005Info = new Hashtable<String,String>(); // Callbacks // TODO: This would probably be more efficient (for deleting anyway) as hashtables // with the key being the callback-to object? /** Used to give Debug Information. */ public interface IDebugInfo { public void onDebug(IRCParser tParser, int nLevel, String sData); } ArrayList<IDebugInfo> cbDebugInfo = new ArrayList<IDebugInfo>(); /** Called when "End of MOTD" or "No MOTD". */ public interface IMOTDEnd { public void onMOTDEnd(IRCParser tParser); } ArrayList<IMOTDEnd> cbEndOfMOTD = new ArrayList<IMOTDEnd>(); /** Called after 001. */ public interface IServerReady { public void onServerReady(IRCParser tParser); } ArrayList<IServerReady> cbServerReady = new ArrayList<IServerReady>(); /** Called on every incomming line BEFORE parsing. */ public interface IDataIn { public void onDataIn(IRCParser tParser, String sData); } ArrayList<IDataIn> cbDataIn = new ArrayList<IDataIn>(); /** Called on every incomming line BEFORE being sent. */ public interface IDataOut { public void onDataOut(IRCParser tParser, String sData, boolean FromParser); } ArrayList<IDataOut> cbDataOut = new ArrayList<IDataOut>(); /** Called when requested nickname is in use. */ public interface INickInUse { public void onNickInUse(IRCParser tParser); } ArrayList<INickInUse> cbNickInUse = new ArrayList<INickInUse>(); /** Called to give Error Information. */ public interface IErrorInfo { public void onError(IRCParser tParser, int nLevel, String sData); } ArrayList<IErrorInfo> cbErrorInfo = new ArrayList<IErrorInfo>(); /** * Called When we, or another client joins a channel. * This is called AFTER client has been added to channel as a ChannelClientInfo */ public interface IChannelJoin { public void onJoinChannel(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cChannelClient ); } ArrayList<IChannelJoin> cbChannelJoin = new ArrayList<IChannelJoin>(); /** * Called When we, or another client parts a channel. * This is called BEFORE client has been removed from the channel. */ public interface IChannelPart { public void onPartChannel(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sReason ); } ArrayList<IChannelPart> cbChannelPart = new ArrayList<IChannelPart>(); /** * Called When we, or another client quits IRC (Called once per channel the user was on). * This is called BEFORE client has been removed from the channel. */ public interface IChannelQuit { public void onQuitChannel(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sReason ); } ArrayList<IChannelQuit> cbChannelQuit = new ArrayList<IChannelQuit>(); /** * Called when the topic is changed or discovered for the first time. * bIsNewTopic is true if someone sets the topic, false if the topic is discovered on join */ public interface IChannelTopic { public void onTopic(IRCParser tParser, ChannelInfo cChannel, boolean bIsNewTopic); } ArrayList<IChannelTopic> cbChannelTopic = new ArrayList<IChannelTopic>(); /** * Called when the channel modes are changed or discovered. * cChannelClient is null if the modes were found from raw 324 (/MODE #Chan reply) or if a server set the mode * If a Server set the mode, sHost is the servers name, else it is the full host of the user who set it */ public interface IChannelModesChanged { public void onModeChange(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sHost); } ArrayList<IChannelModesChanged> cbChannelModesChanged = new ArrayList<IChannelModesChanged>(); /** * Called when user modes are changed. * cClient represents the user who's modes were changed (should ALWAYS be us) * sSetby is the host of the person who set the mode (usually us, may be an oper or server in some cases) */ public interface IUserModesChanged { public void onUserModeChange(IRCParser tParser, ClientInfo cClient, String sSetBy); } ArrayList<IUserModesChanged> cbUserModesChanged = new ArrayList<IUserModesChanged>(); /** * Called when we or another user change nickname. * This is called after the nickname change has been done internally */ public interface INickChanged { public void onNickChanged(IRCParser tParser, ClientInfo cClient, String sOldNick); } ArrayList<INickChanged> cbNickChanged = new ArrayList<INickChanged>(); /** * Called when a person is kicked. * cKickedByClient can be null if kicked by a server. sKickedByHost is the hostname of the person/server doing the kicking. */ public interface IChannelKick { public void onChannelKick(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cKickedClient, ChannelClientInfo cKickedByClient, String sReason, String sKickedByHost); } ArrayList<IChannelKick> cbChannelKick = new ArrayList<IChannelKick>(); /** * Called when a person sends a message to a channel. * sHost is the hostname of the person sending the message. (Can be a server or a person) * cChannelClient is null if user is a server, or not on the channel. */ public interface IChannelMessage { public void onChannelMessage(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sMessage, String sHost ); } ArrayList<IChannelMessage> cbChannelMessage = new ArrayList<IChannelMessage>(); /** * Called when a person does an action in a channel. * sHost is the hostname of the person sending the action. (Can be a server or a person) * cChannelClient is null if user is a server, or not on the channel. */ public interface IChannelAction { public void onChannelAction(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sMessage, String sHost ); } ArrayList<IChannelAction> cbChannelAction = new ArrayList<IChannelAction>(); /** * Called when a person sends a notice to a channel. * sHost is the hostname of the person sending the notice. (Can be a server or a person) * cChannelClient is null if user is a server, or not on the channel. */ public interface IChannelNotice { public void onChannelNotice(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sMessage, String sHost ); } ArrayList<IChannelNotice> cbChannelNotice = new ArrayList<IChannelNotice>(); /** * Called when a person sends a message to you directly (PM). * sHost is the hostname of the person sending the message. (Can be a server or a person) * cClient is null if user is a server, or not on any common channel. */ public interface IPrivateMessage { public void onPrivateMessage(IRCParser tParser, ClientInfo cClient, String sMessage, String sHost ); } ArrayList<IPrivateMessage> cbPrivateMessage = new ArrayList<IPrivateMessage>(); /** * Called when a person does an action to you (PM). * sHost is the hostname of the person sending the action. (Can be a server or a person) * cClient is null if user is a server, or not on any common channel. */ public interface IPrivateAction { public void onPrivateAction(IRCParser tParser, ClientInfo cClient, String sMessage, String sHost ); } ArrayList<IPrivateAction> cbPrivateAction = new ArrayList<IPrivateAction>(); /** * Called when a person sends a notice to you. * sHost is the hostname of the person sending the notice. (Can be a server or a person) * cClient is null if user is a server, or not on any common channel. */ public interface IPrivateNotice { public void onPrivateNotice(IRCParser tParser, ClientInfo cClient, String sMessage, String sHost ); } ArrayList<IPrivateNotice> cbPrivateNotice = new ArrayList<IPrivateNotice>(); /** * Called when a person sends a message not aimed specifically at you or a channel (ie $*). * sHost is the hostname of the person sending the message. (Can be a server or a person) * cClient is null if user is a server, or not on any common channel. */ public interface IUnknownMessage { public void onUnknownMessage(IRCParser tParser, ClientInfo cClient, String sMessage, String sTarget, String sHost ); } ArrayList<IUnknownMessage> cbUnknownMessage = new ArrayList<IUnknownMessage>(); /** * Called when a person sends an action not aimed specifically at you or a channel (ie $*). * sHost is the hostname of the person sending the message. (Can be a server or a person) * cClient is null if user is a server, or not on any common channel. */ public interface IUnknownAction { public void onUnknownAction(IRCParser tParser, ClientInfo cClient, String sMessage, String sTarget, String sHost ); } ArrayList<IUnknownAction> cbUnknownAction = new ArrayList<IUnknownAction>(); /** * Called when a person sends a notice not aimed specifically at you or a channel (ie $*). * sHost is the hostname of the person sending the message. (Can be a server or a person) * cClient is null if user is a server, or not on any common channel. */ public interface IUnknownNotice { public void onUnknownNotice(IRCParser tParser, ClientInfo cClient, String sMessage, String sTarget, String sHost ); } ArrayList<IUnknownNotice> cbUnknownNotice = new ArrayList<IUnknownNotice>(); /** * Called when a person sends a CTCP to a channel. * sHost is the hostname of the person sending the CTCP. (Can be a server or a person) * cChannelClient is null if user is a server. */ public interface IChannelCTCP { public void onChannelCTCP(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sType, String sMessage, String sHost ); } ArrayList<IChannelCTCP> cbChannelCTCP = new ArrayList<IChannelCTCP>(); /** * Called when a person sends a CTCP to you directly. * sHost is the hostname of the person sending the CTCP. (Can be a server or a person) * cClient is null if user is a server, or not on any common channels. */ public interface IPrivateCTCP { public void onPrivateCTCP(IRCParser tParser, ClientInfo cClient, String sType, String sMessage, String sHost ); } ArrayList<IPrivateCTCP> cbPrivateCTCP = new ArrayList<IPrivateCTCP>(); /** * Called when a person sends a CTCP not aimed at you or a channel (ie $*). * sHost is the hostname of the person sending the CTCP. (Can be a server or a person) * cClient is null if user is a server, or not on any common channels. */ public interface IUnknownCTCP { public void onUnknownCTCP(IRCParser tParser, ClientInfo cClient, String sType, String sMessage, String sHost ); } ArrayList<IUnknownCTCP> cbUnknownCTCP = new ArrayList<IUnknownCTCP>(); /** * Called when a person sends a CTCPRReply to a channel. * sHost is the hostname of the person sending the CTCPReply. (Can be a server or a person) * cChannelClient is null if user is a server. */ public interface IChannelCTCPReply { public void onChannelCTCPReply(IRCParser tParser, ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sType, String sMessage, String sHost ); } ArrayList<IChannelCTCPReply> cbChannelCTCPReply = new ArrayList<IChannelCTCPReply>(); /** * Called when a person sends a CTCPRReply to you directly. * sHost is the hostname of the person sending the CTCPRReply. (Can be a server or a person) * cClient is null if user is a server, or not on any common channels. */ public interface IPrivateCTCPReply { public void onPrivateCTCPReply(IRCParser tParser, ClientInfo cClient, String sType, String sMessage, String sHost ); } ArrayList<IPrivateCTCPReply> cbPrivateCTCPReply = new ArrayList<IPrivateCTCPReply>(); /** * Called when a person sends a CTCP not aimed at you or a channel (ie $*). * sHost is the hostname of the person sending the CTCP. (Can be a server or a person) * cClient is null if user is a server, or not on any common channels. */ public interface IUnknownCTCPReply { public void onUnknownCTCPReply(IRCParser tParser, ClientInfo cClient, String sType, String sMessage, String sTarget, String sHost ); } ArrayList<IUnknownCTCPReply> cbUnknownCTCPReply = new ArrayList<IUnknownCTCPReply>(); /** * Called When we, or another client quits IRC (Called once in total). * This is called BEFORE client has been removed from the channel. */ public interface IQuit { public void onQuit(IRCParser tParser, ClientInfo cClient, String sReason ); } ArrayList<IQuit> cbQuit = new ArrayList<IQuit>(); /** Called when a names reply is parsed */ public interface IGotNames { public void onGotNames(IRCParser tParser, ChannelInfo cChannel); } ArrayList<IGotNames> cbGotNames = new ArrayList<IGotNames>(); /** Add a callback pointer to the appropriate ArrayList. */ @SuppressWarnings("unchecked") private void AddCallback(Object eMethod, ArrayList CallbackList) { for (int i = 0; i < CallbackList.size(); i++) { if (eMethod.equals(CallbackList.get(i))) { return; } } CallbackList.add(eMethod); } /** Delete a callback pointer from the appropriate ArrayList. */ private void DelCallback(Object eMethod, ArrayList CallbackList) { for (int i = 0; i < CallbackList.size(); i++) { if (eMethod.equals(CallbackList.get(i))) { CallbackList.remove(i); break; } } } /** * Add callback for DebugInfo (onDebug). * * @see IRCParser.IDebugInfo * @param eMethod Reference to object that handles the callback */ public void AddDebugInfo(Object eMethod) { AddCallback(eMethod, cbDebugInfo); } /** * Delete callback for DebugInfo (onDebug). * * @see IRCParser.IDebugInfo * @param eMethod Reference to object that handles the callback */ public void DelDebugInfo(Object eMethod) { DelCallback(eMethod, cbDebugInfo); } /** * Callback to all objects implementing the IRCParser.IDebugInfo Interface. * * @see IRCParser.IDebugInfo * @param level Debugging Level (ndInfo, ndSocket etc) * @param data Debugging Information */ protected boolean CallDebugInfo(int level, String data) { if (bDebug) { System.out.printf("[DEBUG] {%d} %s\n", level, data); } boolean bResult = false; for (int i = 0; i < cbDebugInfo.size(); i++) { cbDebugInfo.get(i).onDebug(this, level, data); bResult = true; } return bResult; } /** * Add callback for MOTDEnd (onMOTDEnd). * * @see IRCParser.IMOTDEnd * @param eMethod Reference to object that handles the callback */ public void AddMOTDEnd(Object eMethod) { AddCallback(eMethod, cbEndOfMOTD); } /** * Delete callback for MOTDEnd (onMOTDEnd). * * @see IRCParser.IMOTDEnd * @param eMethod Reference to object that handles the callback */ public void DelMOTDEnd(Object eMethod) { DelCallback(eMethod, cbEndOfMOTD); } /** * Callback to all objects implementing the IRCParser.IMotdEnd Interface. * * @see IRCParser.IMotdEnd */ protected boolean CallMOTDEnd() { boolean bResult = false; for (int i = 0; i < cbEndOfMOTD.size(); i++) { cbEndOfMOTD.get(i).onMOTDEnd(this); bResult = true; } return bResult; } /** * Add callback for ServerReady (onServerReady). * * @see IRCParser.IServerReady * @param eMethod Reference to object that handles the callback */ public void AddServerReady(Object eMethod) { AddCallback(eMethod, cbServerReady); } /** * Delete callback for ServerReady (onServerReady). * * @see IRCParser.IServerReady * @param eMethod Reference to object that handles the callback */ public void DelServerReady(Object eMethod) { DelCallback(eMethod, cbServerReady); } /** * Callback to all objects implementing the IRCParser.IServerReady Interface. * * @see IRCParser.IServerReady */ protected boolean CallServerReady() { boolean bResult = false; for (int i = 0; i < cbServerReady.size(); i++) { cbServerReady.get(i).onServerReady(this); bResult = true; } return bResult; } /** * Add callback for DataIn (onDataIn). * * @see IRCParser.IDataIn * @param eMethod Reference to object that handles the callback */ public void AddDataIn(Object eMethod) { AddCallback((IDataIn)eMethod, cbDataIn); } /** * Delete callback for DataIn (onDebug). * * @see IRCParser.IDataIn * @param eMethod Reference to object that handles the callback */ public void DelDataIn(Object eMethod) { DelCallback((IDataIn)eMethod, cbDataIn); } /** * Callback to all objects implementing the IRCParser.IDataIn Interface. * * @see IRCParser.IDataIn * @param data Incomming Line. */ protected boolean CallDataIn(String data) { boolean bResult = false; for (int i = 0; i < cbDataIn.size(); i++) { cbDataIn.get(i).onDataIn(this, data); bResult = true; } return bResult; } /** * Add callback for DataOut (onDataOut). * * @see IRCParser.IDataOut * @param eMethod Reference to object that handles the callback */ public void AddDataOut(Object eMethod) { AddCallback((IDataOut)eMethod, cbDataOut); } /** * Delete callback for DataOut (onDataOut). * * @see IRCParser.IDataOut * @param eMethod Reference to object that handles the callback */ public void DelDataOut(Object eMethod) { DelCallback((IDataOut)eMethod, cbDataOut); } /** * Callback to all objects implementing the IRCParser.IDataOut Interface. * * @see IRCParser.IDataOut * @param data Outgoing Data */ protected boolean CallDataOut(String data, boolean FromParser) { boolean bResult = false; for (int i = 0; i < cbDataOut.size(); i++) { cbDataOut.get(i).onDataOut(this, data, FromParser); bResult = true; } return bResult; } /** * Add callback for NickInUse (onNickInUse). * * @see IRCParser.INickInUse * @param eMethod Reference to object that handles the callback */ public void AddNickInUse(Object eMethod) { AddCallback(eMethod, cbNickInUse); } /** * Delete callback for NickInUse (onNickInUse). * * @see IRCParser.INickInUse * @param eMethod Reference to object that handles the callback */ public void DelNickInUse(Object eMethod) { DelCallback(eMethod, cbNickInUse); } /** * Callback to all objects implementing the IRCParser.INickInUse Interface. * * @see IRCParser.INickInUse */ protected boolean CallNickInUse() { boolean bResult = false; for (int i = 0; i < cbNickInUse.size(); i++) { cbNickInUse.get(i).onNickInUse(this); bResult = true; } return bResult; } /** * Add callback for ErrorInfo (onError). * * @see IRCParser.IErrorInfo * @param eMethod Reference to object that handles the callback */ public void AddErrorInfo(Object eMethod) { AddCallback(eMethod, cbErrorInfo); } /** * Delete callback for ErrorInfo (onError). * * @see IRCParser.IErrorInfo * @param eMethod Reference to object that handles the callback */ public void DelErrorInfo(Object eMethod) { DelCallback(eMethod, cbErrorInfo); } /** * Callback to all objects implementing the IRCParser.IErrorInfo Interface. * * @see IRCParser.IErrorInfo * @param level Debugging Level (errFatal, errWarning etc) * @param data Error Information */ protected boolean CallErrorInfo(int level, String data) { if (bDebug) { System.out.printf("[ERROR] {%d} %s\n", level, data); } boolean bResult = false; for (int i = 0; i < cbErrorInfo.size(); i++) { cbErrorInfo.get(i).onError(this, level, data); bResult = true; } return bResult; } /** * Add callback for ChannelJoin (onJoinChannel). * * @see IRCParser.IChannelJoin * @param eMethod Reference to object that handles the callback */ public void AddChannelJoin(Object eMethod) { AddCallback(eMethod, cbChannelJoin); } /** * Delete callback for ChannelJoin (onJoinChannel). * * @see IRCParser.IChannelJoin * @param eMethod Reference to object that handles the callback */ public void DelChannelJoin(Object eMethod) { DelCallback(eMethod, cbChannelJoin); } /** * Callback to all objects implementing the IRCParser.IChannelJoin Interface. * * @see IRCParser.IChannelJoin * @param cChannel Channel Object * @param cChannelClient ChannelClient object for new person */ protected boolean CallChannelJoin(ChannelInfo cChannel, ChannelClientInfo cChannelClient) { boolean bResult = false; for (int i = 0; i < cbChannelJoin.size(); i++) { cbChannelJoin.get(i).onJoinChannel(this, cChannel, cChannelClient); bResult = true; } return bResult; } /** * Add callback for ChannelPart (onPartChannel). * * @see IRCParser.IChannelPart * @param eMethod Reference to object that handles the callback */ public void AddChannelPart(Object eMethod) { AddCallback(eMethod, cbChannelPart); } /** * Delete callback for ChannelPart (onPartChannel). * * @see IRCParser.IChannelPart * @param eMethod Reference to object that handles the callback */ public void DelChannelPart(Object eMethod) { DelCallback(eMethod, cbChannelPart); } /** * Callback to all objects implementing the IRCParser.IChannelPart Interface. * * @see IRCParser.IChannelPart * @param cChannel Channel that the user parted * @param cChannelClient Client that parted * @param sReason Reason given for parting (May be "") */ protected boolean CallChannelPart(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sReason) { boolean bResult = false; for (int i = 0; i < cbChannelPart.size(); i++) { cbChannelPart.get(i).onPartChannel(this, cChannel, cChannelClient, sReason); bResult = true; } return bResult; } /** * Add callback for ChannelQuit (onQuitChannel). * * @see IRCParser.IChannelQuit * @param eMethod Reference to object that handles the callback */ public void AddChannelQuit(Object eMethod) { AddCallback(eMethod, cbChannelQuit); } /** * Delete callback for ChannelQuit (onQuitChannel). * * @see IRCParser.IChannelQuit * @param eMethod Reference to object that handles the callback */ public void DelChannelQuit(Object eMethod) { DelCallback(eMethod, cbChannelQuit); } /** * Callback to all objects implementing the IRCParser.IChannelQuit Interface. * * @see IRCParser.IChannelQuit * @param cChannel Channel that user was on * @param cChannelClient User thats quitting * @param sReason Quit reason */ protected boolean CallChannelQuit(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sReason) { boolean bResult = false; for (int i = 0; i < cbChannelQuit.size(); i++) { cbChannelQuit.get(i).onQuitChannel(this, cChannel, cChannelClient, sReason); bResult = true; } return bResult; } /** * Add callback for Quit (onQuit). * * @see IRCParser.IQuit * @param eMethod Reference to object that handles the callback */ public void AddQuit(Object eMethod) { AddCallback(eMethod, cbQuit); } /** * Delete callback for Quit (onQuit). * * @see IRCParser.IQuit * @param eMethod Reference to object that handles the callback */ public void DelQuit(Object eMethod) { DelCallback(eMethod, cbQuit); } /** * Callback to all objects implementing the IRCParser.IQuit Interface. * * @see IRCParser.IQuit * @param cClient Client Quitting * @param sReason Reason for quitting (may be "") */ protected boolean CallQuit(ClientInfo cClient, String sReason) { boolean bResult = false; for (int i = 0; i < cbQuit.size(); i++) { cbQuit.get(i).onQuit(this, cClient, sReason); bResult = true; } return bResult; } /** * Add callback for ChannelTopic (onTopic). * * @see IRCParser.IChannelTopic * @param eMethod Reference to object that handles the callback */ public void AddTopic(Object eMethod) { AddCallback(eMethod, cbChannelTopic); } /** * Delete callback for ChannelTopic (onTopic). * * @see IRCParser.IChannelTopic * @param eMethod Reference to object that handles the callback */ public void DelTopic(Object eMethod) { DelCallback(eMethod, cbChannelTopic); } /** * Callback to all objects implementing the IRCParser.IChannelTopic Interface. * * @see IRCParser.IChannelTopic * @param cChannel Channel that topic was set on * @param bIsJoinTopic True when getting topic on join, false if set by user/server */ protected boolean CallTopic(ChannelInfo cChannel, boolean bIsJoinTopic) { boolean bResult = false; for (int i = 0; i < cbChannelTopic.size(); i++) { cbChannelTopic.get(i).onTopic(this, cChannel, bIsJoinTopic); bResult = true; } return bResult; } /** * Add callback for ChannelModesChanged (onModeChange). * * @see IRCParser.IChannelModesChanged * @param eMethod Reference to object that handles the callback */ public void AddModesChanged(Object eMethod) { AddCallback(eMethod, cbChannelModesChanged); } /** * Delete callback for ChannelModesChanged (onModeChange). * * @see IRCParser.IChannelModesChanged * @param eMethod Reference to object that handles the callback */ public void DelModesChanged(Object eMethod) { DelCallback(eMethod, cbChannelModesChanged); } /** * Callback to all objects implementing the IRCParser.IChannelModesChanged Interface. * * @see IRCParser.IChannelModesChanged * @param cChannel Channel where modes were changed * @param cChannelClient Client chaning the modes (null if server) * @param sHost Host doing the mode changing (User host or server name) */ protected boolean CallModesChanged(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sHost) { boolean bResult = false; for (int i = 0; i < cbChannelModesChanged.size(); i++) { cbChannelModesChanged.get(i).onModeChange(this, cChannel, cChannelClient, sHost); bResult = true; } return bResult; } /** * Add callback for UserModesChanged (onUserModeChange). * * @see IRCParser.IUserModesChanged * @param eMethod Reference to object that handles the callback */ public void AddUserModesChanged(Object eMethod) { AddCallback(eMethod, cbUserModesChanged); } /** * Delete callback for UserModesChanged (onUserModeChange). * * @see IRCParser.IUserModesChanged * @param eMethod Reference to object that handles the callback */ public void DelUserModesChanged(Object eMethod) { DelCallback(eMethod, cbUserModesChanged); } /** * Callback to all objects implementing the IRCParser.IUserModesChanged Interface. * * @see IRCParser.IUserModesChanged * @param cClient Client that had the mode changed (almost always us) * @param sSetby Host that set the mode (us or servername) */ protected boolean CallUserModesChanged(ClientInfo cClient, String sSetby) { boolean bResult = false; for (int i = 0; i < cbUserModesChanged.size(); i++) { cbUserModesChanged.get(i).onUserModeChange(this, cClient, sSetby); bResult = true; } return bResult; } /** * Add callback for UserNickChanged (onNickChanged). * * @see IRCParser.INickChanged * @param eMethod Reference to object that handles the callback */ public void AddNickChanged(Object eMethod) { AddCallback(eMethod, cbNickChanged); } /** * Delete callback for UserNickChanged (onNickChanged). * * @see IRCParser.INickChanged * @param eMethod Reference to object that handles the callback */ public void DelNickChanged(Object eMethod) { DelCallback(eMethod, cbNickChanged); } /** * Callback to all objects implementing the IRCParser.INickChanged Interface. * * @see IRCParser.INickChanged * @param cClient Client changing nickname * @param sOldNick Nickname before change */ protected boolean CallNickChanged(ClientInfo cClient, String sOldNick) { boolean bResult = false; for (int i = 0; i < cbNickChanged.size(); i++) { cbNickChanged.get(i).onNickChanged(this, cClient, sOldNick); bResult = true; } return bResult; } /** * Add callback for ChannelKick (onChannelKick). * * @see IRCParser.IChannelKick * @param eMethod Reference to object that handles the callback */ public void AddChannelKick(Object eMethod) { AddCallback(eMethod, cbChannelKick); } /** * Delete callback for ChannelKick (onChannelKick). * * @see IRCParser.IChannelKick * @param eMethod Reference to object that handles the callback */ public void DelChannelKick(Object eMethod) { DelCallback(eMethod, cbChannelKick); } /** * Callback to all objects implementing the IRCParser.IChannelKick Interface. * * @see IRCParser.IChannelKick * @param cChannel Channel where the kick took place * @param cKickedClient ChannelClient that got kicked * @param cKickedByClient ChannelClient that did the kicking (may be null if server) * @param sReason Reason for kick (may be "") * @param sKickedByHost Hostname of Kicker (or servername) */ protected boolean CallChannelKick(ChannelInfo cChannel, ChannelClientInfo cKickedClient, ChannelClientInfo cKickedByClient, String sReason, String sKickedByHost) { boolean bResult = false; for (int i = 0; i < cbChannelKick.size(); i++) { cbChannelKick.get(i).onChannelKick(this, cChannel, cKickedClient, cKickedByClient, sReason, sKickedByHost); bResult = true; } return bResult; } /** * Add callback for ChannelMessage (onChannelMessage). * * @see IRCParser.IChannelMessage * @param eMethod Reference to object that handles the callback */ public void AddChannelMessage(Object eMethod) { AddCallback(eMethod, cbChannelMessage); } /** * Delete callback for ChannelMessage (onChannelMessage). * * @see IRCParser.IChannelMessage * @param eMethod Reference to object that handles the callback */ public void DelChannelMessage(Object eMethod) { DelCallback(eMethod, cbChannelMessage); } /** * Callback to all objects implementing the IRCParser.IChannelMessage Interface. * * @see IRCParser.IChannelMessage * @param cChannel Channel where the message was sent to * @param cChannelClient ChannelClient who sent the message (may be null if server) * @param sMessage Message contents * @param sHost Hostname of sender (or servername) */ protected boolean CallChannelMessage(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbChannelMessage.size(); i++) { cbChannelMessage.get(i).onChannelMessage(this, cChannel, cChannelClient, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for ChannelAction (onChannelAction). * * @see IRCParser.IChannelAction * @param eMethod Reference to object that handles the callback */ public void AddChannelAction(Object eMethod) { AddCallback(eMethod, cbChannelAction); } /** * Delete callback for ChannelAction (onChannelAction). * * @see IRCParser.IChannelAction * @param eMethod Reference to object that handles the callback */ public void DelChannelAction(Object eMethod) { DelCallback(eMethod, cbChannelAction); } /** * Callback to all objects implementing the IRCParser.IChannelAction Interface. * * @see IRCParser.IChannelAction * @param cChannel Channel where the action was sent to * @param cChannelClient ChannelClient who sent the action (may be null if server) * @param sMessage action contents * @param sHost Hostname of sender (or servername) */ protected boolean CallChannelAction(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbChannelAction.size(); i++) { cbChannelAction.get(i).onChannelAction(this, cChannel, cChannelClient, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for ChannelNotice (onChannelNotice). * * @see IRCParser.IChannelNotice * @param eMethod Reference to object that handles the callback */ public void AddChannelNotice(Object eMethod) { AddCallback(eMethod, cbChannelNotice); } /** * Delete callback for ChannelNotice (onChannelNotice). * * @see IRCParser.IChannelNotice * @param eMethod Reference to object that handles the callback */ public void DelChannelNotice(Object eMethod) { DelCallback(eMethod, cbChannelNotice); } /** * Callback to all objects implementing the IRCParser.IChannelNotice Interface. * * @see IRCParser.IChannelNotice * @param cChannel Channel where the notice was sent to * @param cChannelClient ChannelClient who sent the notice (may be null if server) * @param sMessage notice contents * @param sHost Hostname of sender (or servername) */ protected boolean CallChannelNotice(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbChannelNotice.size(); i++) { cbChannelNotice.get(i).onChannelNotice(this, cChannel, cChannelClient, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for PrivateMessage (onPrivateMessage). * * @see IRCParser.IPrivateMessage * @param eMethod Reference to object that handles the callback */ public void AddPrivateMessage(Object eMethod) { AddCallback(eMethod, cbPrivateMessage); } /** * Delete callback for PrivateMessage (onPrivateMessage). * * @see IRCParser.IPrivateMessage * @param eMethod Reference to object that handles the callback */ public void DelPrivateMessage(Object eMethod) { DelCallback(eMethod, cbPrivateMessage); } /** * Callback to all objects implementing the IRCParser.IPrivateMessage Interface. * * @see IRCParser.IPrivateMessage * @param cClient Client who sent the message (may be null if no common channels or server) * @param sMessage Message contents * @param sHost Hostname of sender (or servername) */ protected boolean CallPrivateMessage(ClientInfo cClient, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbPrivateMessage.size(); i++) { cbPrivateMessage.get(i).onPrivateMessage(this, cClient, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for PrivateAction (onPrivateAction). * * @see IRCParser.IPrivateAction * @param eMethod Reference to object that handles the callback */ public void AddPrivateAction(Object eMethod) { AddCallback(eMethod, cbPrivateAction); } /** * Delete callback for PrivateAction (onPrivateAction). * * @see IRCParser.IPrivateAction * @param eMethod Reference to object that handles the callback */ public void DelPrivateAction(Object eMethod) { DelCallback(eMethod, cbPrivateAction); } /** * Callback to all objects implementing the IRCParser.IPrivateAction Interface. * * @see IRCParser.IPrivateAction * @param cClient Client who sent the action (may be null if no common channels or server) * @param sMessage action contents * @param sHost Hostname of sender (or servername) */ protected boolean CallPrivateAction(ClientInfo cClient, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbPrivateAction.size(); i++) { cbPrivateAction.get(i).onPrivateAction(this, cClient, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for PrivateNotice (onPrivateNotice). * * @see IRCParser.IPrivateNotice * @param eMethod Reference to object that handles the callback */ public void AddPrivateNotice(Object eMethod) { AddCallback(eMethod, cbPrivateNotice); } /** * Delete callback for PrivateNotice (onPrivateNotice). * * @see IRCParser.IPrivateNotice * @param eMethod Reference to object that handles the callback */ public void DelPrivateNotice(Object eMethod) { DelCallback(eMethod, cbPrivateNotice); } /** * Callback to all objects implementing the IRCParser.IPrivateNotice Interface. * * @see IRCParser.IPrivateNotice * @param cClient Client who sent the notice (may be null if no common channels or server) * @param sMessage Notice contents * @param sHost Hostname of sender (or servername) */ protected boolean CallPrivateNotice(ClientInfo cClient, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbPrivateNotice.size(); i++) { cbPrivateNotice.get(i).onPrivateNotice(this, cClient, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for UnknownMessage (onUnknownMessage). * * @see IRCParser.IUnknownMessage * @param eMethod Reference to object that handles the callback */ public void AddUnknownMessage(Object eMethod) { AddCallback(eMethod, cbUnknownMessage); } /** * Delete callback for UnknownMessage (onUnknownMessage). * * @see IRCParser.IUnknownMessage * @param eMethod Reference to object that handles the callback */ public void DelUnknownMessage(Object eMethod) { DelCallback(eMethod, cbUnknownMessage); } /** * Callback to all objects implementing the IRCParser.IUnknownMessage Interface. * * @see IRCParser.IUnknownMessage * @param cClient Client who sent the message (may be null if no common channels or server) * @param sMessage Message contents * @param sTarget Actual target of message * @param sHost Hostname of sender (or servername) */ protected boolean CallUnknownMessage(ClientInfo cClient, String sMessage, String sTarget, String sHost) { boolean bResult = false; for (int i = 0; i < cbUnknownMessage.size(); i++) { cbUnknownMessage.get(i).onUnknownMessage(this, cClient, sMessage, sTarget, sHost); bResult = true; } return bResult; } /** * Add callback for UnknownAction (onUnknownAction). * * @see IRCParser.IUnknownAction * @param eMethod Reference to object that handles the callback */ public void AddUnknownAction(Object eMethod) { AddCallback(eMethod, cbUnknownAction); } /** * Delete callback for UnknownAction (onUnknownAction). * * @see IRCParser.IUnknownAction * @param eMethod Reference to object that handles the callback */ public void DelUnknownAction(Object eMethod) { DelCallback(eMethod, cbUnknownAction); } /** * Callback to all objects implementing the IRCParser.IUnknownAction Interface. * * @see IRCParser.IUnknownAction * @param cClient Client who sent the action (may be null if no common channels or server) * @param sMessage Action contents * @param sTarget Actual target of action * @param sHost Hostname of sender (or servername) */ protected boolean CallUnknownAction(ClientInfo cClient, String sMessage, String sTarget, String sHost) { boolean bResult = false; for (int i = 0; i < cbUnknownAction.size(); i++) { cbUnknownAction.get(i).onUnknownAction(this, cClient, sMessage, sTarget, sHost); bResult = true; } return bResult; } /** * Add callback for UnknownNotice (onUnknownNotice). * * @see IRCParser.IUnknownNotice * @param eMethod Reference to object that handles the callback */ public void AddUnknownNotice(Object eMethod) { AddCallback(eMethod, cbUnknownNotice); } /** * Delete callback for UnknownNotice (onUnknownNotice). * * @see IRCParser.IUnknownNotice * @param eMethod Reference to object that handles the callback */ public void DelUnknownNotice(Object eMethod) { DelCallback(eMethod, cbUnknownNotice); } /** * Callback to all objects implementing the IRCParser.IUnknownNotice Interface. * * @see IRCParser.IUnknownNotice * @param cClient Client who sent the notice (may be null if no common channels or server) * @param sMessage Notice contents * @param sTarget Actual target of notice * @param sHost Hostname of sender (or servername) */ protected boolean CallUnknownNotice(ClientInfo cClient, String sMessage, String sTarget, String sHost) { boolean bResult = false; for (int i = 0; i < cbUnknownNotice.size(); i++) { cbUnknownNotice.get(i).onUnknownNotice(this, cClient, sMessage, sTarget, sHost); bResult = true; } return bResult; } /** * Add callback for ChannelCTCP (onChannelCTCP). * * @see IRCParser.IChannelCTCP * @param eMethod Reference to object that handles the callback */ public void AddChannelCTCP(Object eMethod) { AddCallback(eMethod, cbChannelCTCP); } /** * Delete callback for ChannelCTCP (onChannelCTCP). * * @see IRCParser.IChannelCTCP * @param eMethod Reference to object that handles the callback */ public void DelChannelCTCP(Object eMethod) { DelCallback(eMethod, cbChannelCTCP); } /** * Callback to all objects implementing the IRCParser.IChannelCTCP Interface. * * @see IRCParser.IChannelCTCP * @param cChannel Channel where CTCP was sent * @param cChannelClient ChannelClient who sent the message (may be null if server) * @param sType Type of CTCP (VERSION, TIME etc) * @param sMessage Additional contents * @param sHost Hostname of sender (or servername) */ protected boolean CallChannelCTCP(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sType, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbChannelCTCP.size(); i++) { cbChannelCTCP.get(i).onChannelCTCP(this, cChannel, cChannelClient, sType, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for PrivateCTCP (onPrivateCTCP). * * @see IRCParser.IPrivateCTCP * @param eMethod Reference to object that handles the callback */ public void AddPrivateCTCP(Object eMethod) { AddCallback(eMethod, cbPrivateCTCP); } /** * Delete callback for PrivateCTCP (onPrivateCTCP). * * @see IRCParser.IPrivateCTCP * @param eMethod Reference to object that handles the callback */ public void DelPrivateCTCP(Object eMethod) { DelCallback(eMethod, cbPrivateCTCP); } /** * Callback to all objects implementing the IRCParser.IPrivateCTCP Interface. * * @see IRCParser.IPrivateCTCP * @param cClient Client who sent the CTCP (may be null if no common channels or server) * @param sType Type of CTCP (VERSION, TIME etc) * @param sMessage Additional contents * @param sHost Hostname of sender (or servername) */ protected boolean CallPrivateCTCP(ClientInfo cClient, String sType, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbPrivateCTCP.size(); i++) { cbPrivateCTCP.get(i).onPrivateCTCP(this, cClient, sType, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for UnknownCTCP (onUnknownCTCP). * * @see IRCParser.IUnknownCTCP * @param eMethod Reference to object that handles the callback */ public void AddUnknownCTCP(Object eMethod) { AddCallback(eMethod, cbUnknownCTCP); } /** * Delete callback for UnknownCTCP (onUnknownCTCP). * * @see IRCParser.IUnknownCTCP * @param eMethod Reference to object that handles the callback */ public void DelUnknownCTCP(Object eMethod) { DelCallback(eMethod, cbUnknownCTCP); } /** * Callback to all objects implementing the IRCParser.IUnknownCTCP Interface. * * @see IRCParser.IUnknownCTCP * @param cClient Client who sent the CTCP (may be null if no common channels or server) * @param sType Type of CTCP (VERSION, TIME etc) * @param sMessage Additional contents * @param sTarget Actual Target of CTCP * @param sHost Hostname of sender (or servername) */ protected boolean CallUnknownCTCP(ClientInfo cClient, String sType, String sMessage, String sTarget, String sHost) { boolean bResult = false; for (int i = 0; i < cbUnknownCTCP.size(); i++) { cbUnknownCTCP.get(i).onUnknownCTCP(this, cClient, sType, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for ChannelCTCPReply (onChannelCTCPReply). * * @see IRCParser.IChannelCTCPReply * @param eMethod Reference to object that handles the callback */ public void AddChannelCTCPReply(Object eMethod) { AddCallback(eMethod, cbChannelCTCPReply); } /** * Delete callback for ChannelCTCPReply (onChannelCTCPReply). * * @see IRCParser.IChannelCTCPReply * @param eMethod Reference to object that handles the callback */ public void DelChannelCTCPReply(Object eMethod) { DelCallback(eMethod, cbChannelCTCPReply); } /** * Callback to all objects implementing the IRCParser.IChannelCTCPReply Interface. * * @see IRCParser.IChannelCTCPReply * @param cChannel Channel where CTCPReply was sent * @param cChannelClient ChannelClient who sent the message (may be null if server) * @param sType Type of CTCPRReply (VERSION, TIME etc) * @param sMessage Reply Contents * @param sHost Hostname of sender (or servername) */ protected boolean CallChannelCTCPReply(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sType, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbChannelCTCPReply.size(); i++) { cbChannelCTCPReply.get(i).onChannelCTCPReply(this, cChannel, cChannelClient, sType, sMessage, sHost); bResult = true; } return bResult; } /** * Add callback for PrivateCTCPReply (onPrivateCTCPReply). * * @see IRCParser.IPrivateCTCPReply * @param eMethod Reference to object that handles the callback */ public void AddPrivateCTCPReply(Object eMethod) { AddCallback(eMethod, cbPrivateCTCPReply); } /** * Delete callback for PrivateCTCPReply (onPrivateCTCPReply). * * @see IRCParser.IPrivateCTCPReply * @param eMethod Reference to object that handles the callback */ public void DelPrivateCTCPReply(Object eMethod) { DelCallback(eMethod, cbPrivateCTCPReply); } /** * Callback to all objects implementing the IRCParser.IPrivateCTCPReply Interface. * * @see IRCParser.IPrivateCTCPReply * @param cClient Client who sent the CTCPReply (may be null if no common channels or server) * @param sType Type of CTCPRReply (VERSION, TIME etc) * @param sMessage Reply Contents * @param sHost Hostname of sender (or servername) */ protected boolean CallPrivateCTCPReply(ClientInfo cClient, String sType, String sMessage, String sHost) { boolean bResult = false; for (int i = 0; i < cbPrivateCTCPReply.size(); i++) { cbPrivateCTCPReply.get(i).onPrivateCTCPReply(this, cClient, sType, sMessage, sTarget, sHost); bResult = true; } return bResult; } /** * Add callback for UnknownCTCPReply (onUnknownCTCPReply). * * @see IRCParser.IUnknownCTCPReply * @param eMethod Reference to object that handles the callback */ public void AddUnknownCTCPReply(Object eMethod) { AddCallback(eMethod, cbUnknownCTCPReply); } /** * Delete callback for UnknownCTCPReply (onUnknownCTCPReply). * * @see IRCParser.IUnknownCTCPReply * @param eMethod Reference to object that handles the callback */ public void DelUnknownCTCPReply(Object eMethod) { DelCallback(eMethod, cbUnknownCTCPReply); } /** * Callback to all objects implementing the IRCParser.IUnknownCTCPReply Interface. * * @see IRCParser.IUnknownCTCPReply * @param cClient Client who sent the CTCPReply (may be null if no common channels or server) * @param sType Type of CTCPRReply (VERSION, TIME etc) * @param sMessage Reply Contents * @param sTarget Actual Target of CTCPReply * @param sHost Hostname of sender (or servername) */ protected boolean CallUnknownCTCPReply(ClientInfo cClient, String sType, String sMessage, String sTarget, String sHost) { boolean bResult = false; for (int i = 0; i < cbUnknownCTCPReply.size(); i++) { cbUnknownCTCPReply.get(i).onUnknownCTCPReply(this, cClient, sType, sMessage, sTarget, sHost); bResult = true; } return bResult; } /** * Add callback for GotNames (onGotNames). * * @see IRCParser.IGotNames * @param eMethod Reference to object that handles the callback */ public void AddGotNames(Object eMethod) { AddCallback(eMethod, cbGotNames); } /** * Delete callback for GotNames (onGotNames). * * @see IRCParser.IGotNames * @param eMethod Reference to object that handles the callback */ public void DelGotNames(Object eMethod) { DelCallback(eMethod, cbGotNames); } /** * Callback to all objects implementing the IRCParser.IGotNames Interface. * * @see IRCParser.IGotNames * @param cChannel Channel which the names reply is for */ protected boolean CallGotNames(ChannelInfo cChannel) { boolean bResult = false; for (int i = 0; i < cbGotNames.size(); i++) { cbGotNames.get(i).onGotNames(this, cChannel); bResult = true; } return bResult; } /** * Perform a silent test on certain functions. * * @return Boolean result of test. (True only if ALL tests pass) */ public boolean DoSelfTest() { return DoSelfTest(true); } /** * Perform a test on certain functions. * * @param bSilent Should output be given? (Sent to Console) * @return Boolean result of test. (True only if ALL tests pass) */ public boolean DoSelfTest(boolean bSilent) { if (bDebug) { boolean bResult = false; ParserTestClass ptc = new ParserTestClass(); if (bSilent) { bResult = ptc.SelfTest(); } else { System.out.printf(" System.out.printf(" Beginning Tests\n"); System.out.printf(" ptc.RunTests(); System.out.printf(" System.out.printf(" End\n"); System.out.printf(" System.out.printf(" Total Tests: %d\n",ptc.GetTotalTests()); System.out.printf(" Passed Tests: %d\n",ptc.GetPassedTests()); System.out.printf(" Failed Tests: %d\n",ptc.GetFailedTests()); System.out.printf(" bResult = (ptc.GetTotalTests() == ptc.GetPassedTests()); } ptc = null; return bResult; } else { return true; } } /** * Default constructor. */ public IRCParser() { } /** * Constructor with ServerInfo. * * @param serverDetails Server information. */ public IRCParser(ServerInfo serverDetails) { this(null,serverDetails); } /** * Constructor with MyInfo. * * @param myDetails Client information.| */ public IRCParser(MyInfo myDetails) { this(myDetails,null); } /** * Constructor with ServerInfo and MyInfo. * * @param serverDetails Server information. * @param myDetails Client information.| */ public IRCParser(MyInfo myDetails, ServerInfo serverDetails) { if (myDetails != null) { this.me = myDetails; } if (serverDetails != null) { this.server = serverDetails; } } /** Reset internal state (use before connect). */ private void ResetState() { // Reset General State info TriedAlt = false; Got001 = false; // Clear the hash tables hChannelList.clear(); hClientList.clear(); h005Info.clear(); hPrefixModes.clear(); hPrefixMap.clear(); hChanModesOther.clear(); hChanModesBool.clear(); hUserModes.clear(); hChanPrefix.clear(); // Reset the mode indexes nNextKeyPrefix = 1; nNextKeyCMBool = 1; nNextKeyUser = 1; } /** Connect to IRC. */ private void connect() throws Exception { try { ResetState(); CallDebugInfo(ndSocket,"Connecting to "+server.sHost+":"+server.nPort); socket = new Socket(server.sHost,server.nPort); if (bDebug) { System.out.printf("\t\t-> 1\n"); } out = new PrintWriter(socket.getOutputStream(), true); if (bDebug) { System.out.printf("\t\t-> 2\n"); } in = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (bDebug) { System.out.printf("\t\t-> 3\n"); } } catch (Exception e) { throw e; } } /** * Begin execution. * Connect to server, and start parsing incomming lines */ public void run() { CallDebugInfo(ndInfo,"Begin Thread Execution"); if (HasBegan) { return; } else { HasBegan = true; } try { connect(); } catch (Exception e) { CallDebugInfo(ndSocket,"Error Connecting, Aborted"); return; } // :HACK: While true loops really really suck. CallDebugInfo(ndSocket,"Socket Connected"); String line = ""; while(true) { try { line = in.readLine(); // Blocking :/ if (line == null) { CallDebugInfo(ndSocket,"Socket Closed"); break; } else { if (IsFirst) { if (!server.sPassword.equals("")) { SendString("PASS "+server.sPassword); } SetNickname(me.sNickname); SendString("USER "+me.sUsername.toLowerCase()+" * * :"+me.sRealname); IsFirst = false; } ProcessLine(line); } } catch (IOException e) { CallDebugInfo(ndSocket,"Socket Closed"); break; } } CallDebugInfo(ndInfo,"End Thread Execution"); } /** Close socket on destroy. */ protected void finalize(){ try { socket.close(); } catch (IOException e) { CallDebugInfo(ndInfo,"Could not close socket"); } } /** * Get the parameter for a line. * * @param line Line to get parameter for * @return Parameter of the line */ protected String GetParam(String line) { String[] params = null; params = line.split(" :",2); return params[params.length-1]; } /** * Tokenise a line. * splits by " " up to the first " :" everything after this is a single token * * @param line Line to tokenise * @return Array of tokens */ protected String[] IRCTokenise(String line) { if (line == null) { String[] tokens = new String[1]; tokens[0] = ""; return tokens; // Return empty string[] }; String[] params = null; String[] tokens = null; params = line.split(" :",2); tokens = params[0].split(" "); if (params.length == 2) { String[] temp = new String[tokens.length+1]; System.arraycopy(tokens, 0, temp, 0, tokens.length); tokens = temp; tokens[tokens.length-1] = params[1]; } return tokens; } /** * Get the ClientInfo object for a person. * * @param sWho Who can be any valid identifier for a client as long as it contains a nickname (?:)nick(?!ident)(?@host) * @return ClientInfo Object for the client, or null */ public ClientInfo GetClientInfo(String sWho) { if (bDebug) { System.out.printf("\t\tInput: %s | ",sWho); } sWho = ClientInfo.ParseHost(sWho); if (bDebug) { System.out.printf("Client Name: %s\n",sWho); } sWho = sWho.toLowerCase(); if (hClientList.containsKey(sWho)) { return hClientList.get(sWho); } else { return null; } } /** * Get the ChannelInfo object for a channel. * * @param sWhat This is the name of the channel. * @return ChannelInfo Object for the channel, or null */ public ChannelInfo GetChannelInfo(String sWhat) { sWhat = sWhat.toLowerCase(); if (hChannelList.containsKey(sWhat)) { return hChannelList.get(sWhat); } else { return null; } } // TODO: This should do some checks on stuff? /** * Send a line to the server. * * @param line Line to send (\r\n termination is added automatically) */ public void SendLine(String line) { CallDataOut(line,false); out.printf("%s\r\n",line);} /** Send a line to the server and add proper line ending. */ protected void SendString(String line) { CallDataOut(line,true); out.printf("%s\r\n",line); } /** * Process a line and call relevent methods for handling. * * @param line IRC Line to process */ private void ProcessLine(String line) { String[] token = IRCTokenise(line); // String mainParam = token[token.length-1]; int nParam; CallDataIn(line); String sParam = token[1]; try {nParam = Integer.parseInt(token[1]);} catch (Exception e) { nParam = -1;} try { if (token[0].equals("PING") || token[1].equals("PING")) { SendString("PONG :"+sParam); } else { if (token[0].substring(0,1).equals(":")) { // Post Connect switch (nParam) { case -1: ProcessStringParam(sParam,token); break; case 1: // 001 - Welcome to IRC Got001 = true; Process001(nParam,token); break; case 4: // 004 - ISUPPORT case 5: // 005 - ISUPPORT Process004_005(nParam,token); break; case 332: // Topic on Join case 333: // Topic Setter On Join ProcessTopic(sParam,token); break; case 375: // MOTD Start break; case 353: // Names case 366: // End of Names ProcessNames(nParam,token); break; case 324: // Modes ProcessMode(sParam,token); case 329: // Channel Time case 368: // End of ban list break; case 376: // End of MOTD case 422: // No MOTD ProcessEndOfMOTD(nParam,token); break; case 433: // Nick In Use ProcessNickInUse(nParam,token); break; default: // Unknown break; } } else { // Pre Connect } } } catch (Exception e) { CallErrorInfo(errFatal,"Exception in Parser. {"+line+"} ["+e.getMessage()+"]"); e.getStackTrace(); } } /** * Process an IRC Line with a string parameter rather than a Numeric. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessStringParam(String sParam, String token[]) { // Process a line where the parameter is a string (IE PRIVMSG, NOTICE etc - Not including PING!) if (sParam.equalsIgnoreCase("PRIVMSG") || sParam.equalsIgnoreCase("NOTICE")) { ProcessIRCMessage(sParam,token); } else if (sParam.equalsIgnoreCase("JOIN")) { ProcessJoinChannel(sParam,token); } else if (sParam.equalsIgnoreCase("NICK")) { ProcessNickChange(sParam,token); } else if (sParam.equalsIgnoreCase("KICK")) { ProcessKickChannel(sParam,token); } else if (sParam.equalsIgnoreCase("PART")) { ProcessPartChannel(sParam,token); } else if (sParam.equalsIgnoreCase("QUIT")) { ProcessQuit(sParam,token); } else if (sParam.equalsIgnoreCase("TOPIC")) { ProcessTopic(sParam,token); } else if (sParam.equalsIgnoreCase("MODE")) { ProcessMode(sParam,token); } } /** * Process a Nickname change. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessNickChange(String sParam, String token[]) { ClientInfo iClient; iClient = GetClientInfo(token[0]); if (iClient != null) { if (iClient.getHost().equals("")) { iClient.setUserBits(token[0],false); } hClientList.remove(iClient.getNickname().toLowerCase()); iClient.setUserBits(token[2],true); hClientList.put(iClient.getNickname().toLowerCase(),iClient); CallNickChanged(iClient, ClientInfo.ParseHost(token[0])); } } /** * Process a kick. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessKickChannel(String sParam, String token[]) { ChannelClientInfo iChannelClient; ChannelClientInfo iChannelKicker; ChannelInfo iChannel; ClientInfo iClient; ClientInfo iKicker; String sReason = ""; iClient = GetClientInfo(token[3]); iKicker = GetClientInfo(token[0]); iChannel = GetChannelInfo(token[2]); if (iClient == null) { return; } if (iChannel == null) { if (iClient != cMyself) { CallErrorInfo(errWarning+errCanContinue, "Got kick for channel ("+token[2]+") that I am not on. [User: "+token[3]+"]"); } return; } else { if (token.length > 4) { sReason = token[token.length-1]; } iChannelClient = iChannel.getUser(iClient); iChannelKicker = iChannel.getUser(iClient); CallChannelKick(iChannel,iChannelClient,iChannelKicker,sReason,token[0]); iChannel.delClient(iClient); if (iClient == cMyself) { iChannel.emptyChannel(); hChannelList.remove(iChannel.getName().toLowerCase()); } else { if (!iClient.checkVisability()) { hClientList.remove(iClient.getNickname().toLowerCase()); } } } } /** * Process a Mode change (hands off to ProcessUserMode for usermodes). * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessMode(String sParam, String token[]) { String[] sModestr; String sChannelName; String sModeParam; int nCurrent = 0, nParam = 1, nValue = 0; boolean bPositive = true, bBooleanMode = true; ChannelInfo iChannel; ChannelClientInfo iChannelClientInfo; ClientInfo iClient; if (sParam.equals("324")) { sChannelName = token[3]; // Java 6 Only // sModestr = Arrays.copyOfRange(token,4,token.length); sModestr = new String[token.length-4]; System.arraycopy(token, 4, sModestr, 0, token.length-4); } else { sChannelName = token[2]; // Java 6 Only // sModestr = Arrays.copyOfRange(token,3,token.length); sModestr = new String[token.length-3]; System.arraycopy(token, 3, sModestr, 0, token.length-3); } if (!ChannelInfo.isValidChannelName(this, sChannelName)) { ProcessUserMode(sParam, token, sModestr); return; } iChannel = GetChannelInfo(sChannelName); if (iChannel == null) { CallErrorInfo(errWarning+errCanContinue, "Got modes for channel ("+sChannelName+") that I am not on."); iChannel = new ChannelInfo(this, sChannelName); hChannelList.put(iChannel.getName().toLowerCase(),iChannel); } if (!sParam.equals("324")) { nCurrent = iChannel.getMode(); } for (int i = 0; i < sModestr[0].length(); ++i) { Character cMode = sModestr[0].charAt(i); if (cMode.equals("+".charAt(0))) { bPositive = true; } else if (cMode.equals("-".charAt(0))) { bPositive = false; } else if (cMode.equals(":".charAt(0))) { continue; } else { if (hChanModesBool.containsKey(cMode)) { nValue = hChanModesBool.get(cMode); bBooleanMode = true; } else if (hChanModesOther.containsKey(cMode)) { nValue = hChanModesOther.get(cMode); bBooleanMode = false; } else if (hPrefixModes.containsKey(cMode)) { // (de) OP/Voice someone sModeParam = sModestr[nParam++]; nValue = hPrefixModes.get(cMode); if (bDebug) { System.out.printf("User Mode: %c [%s] {Positive: %b}\n",cMode, sModeParam, bPositive); } iChannelClientInfo = iChannel.getUser(sModeParam); if (iChannelClientInfo == null) { // Client not known? CallErrorInfo(errWarning+errCanContinue, "Got mode for client not known on channel - Added"); iClient = GetClientInfo(sModeParam); if (iClient == null) { CallErrorInfo(errWarning+errCanContinue, "Got mode for client not known at all - Added"); iClient = new ClientInfo(this, sModeParam); hClientList.put(iClient.getNickname().toLowerCase(),iClient); } iChannelClientInfo = iChannel.addClient(iClient); } if (bPositive) { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() + nValue); } else { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() - nValue); } continue; } else { CallErrorInfo(errWarning+errCanContinue, "Got unknown mode "+cMode+" - Added as boolean mode"); hChanModesBool.put(cMode,nNextKeyCMBool); nValue = nNextKeyCMBool; bBooleanMode = true; nNextKeyCMBool = nNextKeyCMBool*2; } if (bBooleanMode) { if (bDebug) { System.out.printf("Boolean Mode: %c [%d] {Positive: %b}\n",cMode, nValue, bPositive); } if (bPositive) { nCurrent = nCurrent + nValue; } else { nCurrent = nCurrent - nValue; } } else { if (nValue == cmList) { sModeParam = sModestr[nParam++]; iChannel.setListModeParam(cMode, sModeParam, bPositive); if (bDebug) { System.out.printf("List Mode: %c [%s] {Positive: %b}\n",cMode, sModeParam, bPositive); } } else { if (bPositive) { sModeParam = sModestr[nParam++]; if (bDebug) { System.out.printf("Set Mode: %c [%s] {Positive: %b}\n",cMode, sModeParam, bPositive); } iChannel.setModeParam(cMode,sModeParam); } else { if ((nValue & cmUnset) == cmUnset) { sModeParam = sModestr[nParam++]; } else { sModeParam = ""; } if (bDebug) { System.out.printf("Unset Mode: %c [%s] {Positive: %b}\n",cMode, sModeParam, bPositive); } iChannel.setModeParam(cMode,""); } } } } } iChannel.setMode(nCurrent); if (sParam.equals("324")) { CallModesChanged(iChannel, null, ""); } else { CallModesChanged(iChannel, iChannel.getUser(token[0]), token[0]); } } /** * Process user modes. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessUserMode(String sParam, String token[], String sModestr[]) { int nCurrent = 0, nValue = 0; boolean bPositive = true; ClientInfo iClient; iClient = GetClientInfo(token[2]); if (iClient == null) { return; } nCurrent = iClient.getUserMode(); for (int i = 0; i < sModestr[0].length(); ++i) { Character cMode = sModestr[0].charAt(i); if (cMode.equals("+".charAt(0))) { bPositive = true; } else if (cMode.equals("-".charAt(0))) { bPositive = false; } else if (cMode.equals(":".charAt(0))) { continue; } else { if (hUserModes.containsKey(cMode)) { nValue = hUserModes.get(cMode); } else { CallErrorInfo(errWarning+errCanContinue, "Got unknown user mode "+cMode+" - Added"); hUserModes.put(cMode,nNextKeyUser); nValue = nNextKeyUser; nNextKeyUser = nNextKeyUser*2; } if (bDebug) { System.out.printf("User Mode: %c [%d] {Positive: %b}\n",cMode, nValue, bPositive); } if (bPositive) { nCurrent = nCurrent + nValue; } else { nCurrent = nCurrent - nValue; } } } iClient.setUserMode(nCurrent); CallUserModesChanged(iClient, token[0]); } /** * Process a Names reply. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessNames(int nParam, String token[]) { ChannelInfo iChannel; if (nParam == 366) { // End of names iChannel = GetChannelInfo(token[2]); if (iChannel != null) { iChannel.bAddingNames = false; CallGotNames(iChannel); } } else { // Names ClientInfo iClient; ChannelClientInfo iChannelClient; iChannel = GetChannelInfo(token[4]); if (iChannel == null) { CallErrorInfo(errWarning+errCanContinue, "Got names for channel ("+token[4]+") that I am not on."); iChannel = new ChannelInfo(this, token[4]); hChannelList.put(iChannel.getName().toLowerCase(),iChannel); } // If we are not expecting names, clear the current known names - this is fresh stuff! if (!iChannel.bAddingNames) { iChannel.emptyChannel(); } iChannel.bAddingNames = true; String[] sNames = token[token.length-1].split(" "); String sNameBit = "", sModes = "", sName = ""; int nPrefix = 0; for (int j = 0; j < sNames.length; ++j) { sNameBit = sNames[j]; for (int i = 0; i < sNameBit.length(); ++i) { Character cMode = sNameBit.charAt(i); if (hPrefixMap.containsKey(cMode)) { sModes = sModes+cMode; nPrefix = nPrefix + hPrefixModes.get(hPrefixMap.get(cMode)); } else { sName = sNameBit.substring(i); break; } } System.out.printf("Name: %s Modes: \"%s\" [%d]\n",sName,sModes,nPrefix); iClient = GetClientInfo(sName); if (iClient == null) { iClient = new ClientInfo(this, sName); hClientList.put(iClient.getNickname().toLowerCase(),iClient); } iChannelClient = iChannel.addClient(iClient); iChannelClient.setChanMode(nPrefix); sName = ""; sModes = ""; nPrefix = 0; } } } /** * Process PRIVMSGs and NOTICEs. * This horrible thing handles PRIVMSGs and NOTICES * This inclues CTCPs and CTCPReplies * It handles all 3 targets (Channel, Private, Unknown) * Actions are handled here aswell separately from CTCPs. * Each type has 5 Calls, making 15 callbacks handled here. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessIRCMessage(String sParam, String token[]) { ChannelClientInfo iChannelClient = null; ChannelInfo iChannel = null; ClientInfo iClient = null; String sMessage = token[token.length-1]; String[] bits = sMessage.split(" ", 2); Character Char1 = Character.valueOf((char)1); String sCTCP = ""; boolean isAction = false; boolean isCTCP = false; iClient = GetClientInfo(token[0]); if (sParam.equalsIgnoreCase("PRIVMSG")) { if (bits[0].equalsIgnoreCase(Char1+"ACTION") && Character.valueOf(sMessage.charAt(sMessage.length()-1)).equals(Char1)) { isAction = true; } else if (Character.valueOf(sMessage.charAt(0)).equals(Char1) && Character.valueOf(sMessage.charAt(sMessage.length()-1)).equals(Char1)) { isCTCP = true; if (bits.length > 1) { sMessage = bits[1]; } else { sMessage = ""; } bits = bits[0].split(Char1.toString()); sCTCP = bits[1]; if (bDebug) { System.out.printf("CTCP: \"%s\" \"%s\"\n",sCTCP,sMessage); } } } if (ChannelInfo.isValidChannelName(this, token[2])) { iChannel = GetChannelInfo(token[2]); if (iClient != null && iChannel != null) { iChannelClient = iChannel.getUser(iClient); } if (sParam.equalsIgnoreCase("PRIVMSG")) { if (!isAction) { if (isCTCP) { CallChannelCTCP(iChannel, iChannelClient, sCTCP, sMessage, token[0]); } else { CallChannelMessage(iChannel, iChannelClient, sMessage, token[0]); } } else { CallChannelAction(iChannel, iChannelClient, sMessage, token[0]); } } else if (sParam.equalsIgnoreCase("NOTICE")) { if (isCTCP) { CallChannelCTCPReply(iChannel, iChannelClient, sCTCP, sMessage, token[0]); } else { CallChannelNotice(iChannel, iChannelClient, sMessage, token[0]); } } } else if (token[2].equalsIgnoreCase(cMyself.getNickname())) { if (sParam.equalsIgnoreCase("PRIVMSG")) { if (!isAction) { if (isCTCP) { CallPrivateCTCP(iClient, sCTCP, sMessage, token[0]); } else { CallPrivateMessage(iClient, sMessage, token[0]); } } else { CallPrivateAction(iClient, sMessage, token[0]); } } else if (sParam.equalsIgnoreCase("NOTICE")) { if (isCTCP) { CallPrivateCTCPReply(iClient, sCTCP, sMessage, token[0]); } else { CallPrivateNotice(iClient, sMessage, token[0]); } } } else { if (bDebug) { System.out.printf("Message for Other ("+token[2]+")\n"); } if (sParam.equalsIgnoreCase("PRIVMSG")) { if (!isAction) { if (isCTCP) { CallUnknownCTCP(iClient, sCTCP, sMessage, token[2], token[0]); } else { CallUnknownMessage(iClient, sMessage, token[2], token[0]); } } else { CallUnknownAction(iClient, sMessage, token[2], token[0]); } } else if (sParam.equalsIgnoreCase("NOTICE")) { if (isCTCP) { CallUnknownCTCPReply(iClient, sCTCP, sMessage, token[2], token[0]); } else { CallUnknownNotice(iClient, sMessage, token[2], token[0]); } } } } /** * Process a topic change. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessTopic(String sParam, String token[]) { ChannelInfo iChannel; if (sParam.equals("332")) { iChannel = GetChannelInfo(token[3]); if (iChannel == null) { return; }; iChannel.setTopic(token[token.length-1]); } else if (sParam.equals("333")) { iChannel = GetChannelInfo(token[3]); if (iChannel == null) { return; }; iChannel.setTopicTime(Long.parseLong(token[5])); iChannel.setTopicUser(token[5]); CallTopic(iChannel,false); } else { iChannel = GetChannelInfo(token[2]); if (iChannel == null) { return; }; iChannel.setTopicTime(java.util.Calendar.getInstance().getTimeInMillis() / 1000); String sTemp[] = token[0].split(":",2); if (sTemp.length > 1) { token[0] = sTemp[1]; } iChannel.setTopicUser(token[0]); CallTopic(iChannel,true); } } /** * Process a channel join. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessJoinChannel(String sParam, String token[]) { // :nick!ident@host JOIN (:)#Channel Character cTemp; Byte nTemp; if (token.length < 3) { return; } ClientInfo iClient; ChannelInfo iChannel; ChannelClientInfo iChannelClient; iClient = GetClientInfo(token[0]); iChannel = GetChannelInfo(token[token.length-1]); if (iClient == null) { iClient = new ClientInfo(this, token[0]); hClientList.put(iClient.getNickname().toLowerCase(),iClient); } if (iChannel == null) { if (iClient != cMyself) { CallErrorInfo(errWarning+errCanContinue, "Got join for channel ("+token[token.length-1]+") that I am not on. [User: "+token[0]+"]"); } iChannel = new ChannelInfo(this, token[token.length-1]); hChannelList.put(iChannel.getName().toLowerCase(),iChannel); SendString("MODE "+iChannel.getName()); for (Enumeration e = hChanModesOther.keys(); e.hasMoreElements();) { cTemp = (Character)e.nextElement(); nTemp = hChanModesOther.get(cTemp); if (nTemp == cmList) { SendString("MODE "+iChannel.getName()+" "+cTemp); } } } else { // This is only done if we are on the channel. Else we wait for names. iChannelClient = iChannel.addClient(iClient); CallChannelJoin(iChannel, iChannelClient); } } /** * Process a channel part. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessPartChannel(String sParam, String token[]) { // :nick!ident@host PART #Channel // :nick!ident@host PART #Channel :reason if (token.length < 3) { return; } ClientInfo iClient; ChannelInfo iChannel; ChannelClientInfo iChannelClient; iClient = GetClientInfo(token[0]); iChannel = GetChannelInfo(token[2]); if (iClient == null) { return; } if (iChannel == null) { if (iClient != cMyself) { CallErrorInfo(errWarning+errCanContinue, "Got part for channel ("+token[2]+") that I am not on. [User: "+token[0]+"]"); } return; } else { String sReason = ""; if (token.length > 3) { sReason = token[token.length-1]; } iChannelClient = iChannel.getUser(iClient); CallChannelPart(iChannel,iChannelClient,sReason); iChannel.delClient(iClient); if (iClient == cMyself) { iChannel.emptyChannel(); hChannelList.remove(iChannel.getName().toLowerCase()); } else { iClient.checkVisability(); } } } /** * Process a Quit message. * * @param sParam String representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessQuit(String sParam, String token[]) { // :nick!ident@host QUIT // :nick!ident@host QUIT :reason if (token.length < 2) { return; } ClientInfo iClient; ChannelInfo iChannel; ChannelClientInfo iChannelClient; iClient = GetClientInfo(token[0]); if (iClient == null) { return; } String sReason = ""; if (token.length > 2) { sReason = token[token.length-1]; } for (Enumeration e = hChannelList.keys(); e.hasMoreElements();) { iChannel = hChannelList.get(e.nextElement()); iChannelClient = iChannel.getUser(iClient); if (iChannelClient != null) { CallChannelQuit(iChannel,iChannelClient,sReason); if (iClient == cMyself) { iChannel.emptyChannel(); hChannelList.remove(iChannel.getName().toLowerCase()); } else { iChannel.delClient(iClient); } } } CallQuit(iClient,sReason); if (iClient == cMyself) { hClientList.clear(); } else { hClientList.remove(iClient.getNickname().toLowerCase()); } } /** * Process a 004 or 005 message. * * @param nParam Integer representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void Process004_005(int nParam, String token[]) { if (nParam == 4) { // 004 h005Info.put("USERMODES",token[5]); } else { // 005 String[] Bits = null; String sKey = null, sValue = null; for (int i = 3; i < token.length ; i++) { Bits = token[i].split("=",2); sKey = Bits[0].toUpperCase(); if (Bits.length == 2) { sValue = Bits[1]; } else { sValue = ""; } if (bDebug) { System.out.printf("%s => %s \r\n",sKey,sValue); } h005Info.put(sKey,sValue); } } } /** * Process CHANMODES from 005. */ protected void ParseChanModes() { final String sDefaultModes = "b,k,l,imnpstrc"; String[] Bits = null; String ModeStr; if (h005Info.containsKey("CHANMODES")) { ModeStr = h005Info.get("CHANMODES"); } else { ModeStr = sDefaultModes; h005Info.put("CHANMODES",ModeStr); } Bits = ModeStr.split(",",4); if (Bits.length != 4) { ModeStr = sDefaultModes; CallErrorInfo(errError+errCanContinue, "CHANMODES String not valid. Using default string of \""+ModeStr+"\""); h005Info.put("CHANMODES",ModeStr); Bits = ModeStr.split(",",4); } // ResetState hChanModesOther.clear(); hChanModesBool.clear(); nNextKeyCMBool = 1; // List modes. for (int i = 0; i < Bits[0].length(); ++i) { Character cMode = Bits[0].charAt(i); if (bDebug) { System.out.printf("List Mode: %c\n",cMode); } if (!hChanModesOther.containsKey(cMode)) { hChanModesOther.put(cMode,cmList); } } // Param for Set and Unset. Byte nBoth = (cmSet+cmUnset); for (int i = 0; i < Bits[1].length(); ++i) { Character cMode = Bits[1].charAt(i); if (bDebug) { System.out.printf("Set/Unset Mode: %c\n",cMode); } if (!hChanModesOther.containsKey(cMode)) { hChanModesOther.put(cMode,nBoth); } } // Param just for Set for (int i = 0; i < Bits[2].length(); ++i) { Character cMode = Bits[2].charAt(i); if (bDebug) { System.out.printf("Set Only Mode: %c\n",cMode); } if (!hChanModesOther.containsKey(cMode)) { hChanModesOther.put(cMode,cmSet); } } // Boolean Mode for (int i = 0; i < Bits[3].length(); ++i) { Character cMode = Bits[3].charAt(i); if (bDebug) { System.out.printf("Boolean Mode: %c [%d]\n",cMode,nNextKeyCMBool); } if (!hChanModesBool.containsKey(cMode)) { hChanModesBool.put(cMode,nNextKeyCMBool); nNextKeyCMBool = nNextKeyCMBool*2; } } } /** * Process USERMODES from 004. */ protected void ParseUserModes() { final String sDefaultModes = "nwdoi"; String[] Bits = null; String ModeStr; if (h005Info.containsKey("USERMODES")) { ModeStr = h005Info.get("USERMODES"); } else { ModeStr = sDefaultModes; h005Info.put("USERMODES", sDefaultModes); } // ResetState hUserModes.clear(); nNextKeyUser = 1; // Boolean Mode for (int i = 0; i < ModeStr.length(); ++i) { Character cMode = ModeStr.charAt(i); if (bDebug) { System.out.printf("User Mode: %c [%d]\n",cMode,nNextKeyUser); } if (!hUserModes.containsKey(cMode)) { hUserModes.put(cMode,nNextKeyUser); nNextKeyUser = nNextKeyUser*2; } } } /** * Process CHANTYPES from 005. */ protected void ParseChanPrefix() { final String sDefaultModes = " String[] Bits = null; String ModeStr; if (h005Info.containsKey("CHANTYPES")) { ModeStr = h005Info.get("CHANTYPES"); } else { ModeStr = sDefaultModes; h005Info.put("CHANTYPES", sDefaultModes); } // ResetState hChanPrefix.clear(); // Boolean Mode for (int i = 0; i < ModeStr.length(); ++i) { Character cMode = ModeStr.charAt(i); if (bDebug) { System.out.printf("Chan Prefix: %c\n",cMode); } if (!hChanPrefix.containsKey(cMode)) { hChanPrefix.put(cMode,true); } } } /** * Process PREFIX from 005. */ protected void ParsePrefixModes() { final String sDefaultModes = "(ohv)@%+"; String[] Bits = null; String ModeStr; if (h005Info.containsKey("PREFIX")) { ModeStr = h005Info.get("PREFIX"); } else { ModeStr = sDefaultModes; } if (ModeStr.substring(0,1).equals("(")) { ModeStr = ModeStr.substring(1); } else { ModeStr = sDefaultModes.substring(1); h005Info.put("PREFIX", sDefaultModes); } Bits = ModeStr.split("\\)",2); if (Bits.length != 2 || Bits[0].length() != Bits[1].length()) { ModeStr = sDefaultModes; CallErrorInfo(errError+errCanContinue, "PREFIX String not valid. Using default string of \""+ModeStr+"\""); h005Info.put("PREFIX",ModeStr); ModeStr = ModeStr.substring(1); Bits = ModeStr.split("\\)",2); } // ResetState hPrefixModes.clear(); hPrefixMap.clear(); nNextKeyPrefix = 1; for (int i = 0; i < Bits[0].length(); ++i) { Character cMode = Bits[0].charAt(i); Character cPrefix = Bits[1].charAt(i); if (bDebug) { System.out.printf("Prefix Mode: %c => %c [%d]\n",cMode,cPrefix,nNextKeyPrefix); } if (!hPrefixModes.containsKey(cMode)) { hPrefixModes.put(cMode,nNextKeyPrefix); hPrefixMap.put(cMode,cPrefix); hPrefixMap.put(cPrefix,cMode); nNextKeyPrefix = nNextKeyPrefix*2; } } } /** * Process an EndOfMOTD or No MOTD Found. * * @param nParam Integer representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessEndOfMOTD(int nParam, String token[]) { ParseChanModes(); ParseChanPrefix(); ParsePrefixModes(); ParseUserModes(); CallMOTDEnd(); } /** * Process a 001 message. * * @param nParam Integer representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void Process001(int nParam, String token[]) { // << :demon1.uk.quakenet.org 001 Java-Test :Welcome to the QuakeNet IRC Network, Java-Test String sNick; sServerName = token[0].substring(1,token[0].length()); sNick = token[2]; sNick = temp[0]; /** * Process a NickInUse message. * Parser implements handling of this if Pre-001 and no other handler found, * adding the NickInUse handler (AddNickInUse) after 001 is prefered over before. * * @param nParam Integer representation of parameter to parse * @param token[] IRCTokenised verison of the incomming line */ private void ProcessNickInUse(int nParam, String token[]) { if (!CallNickInUse()) { // Manually handle nick in use. CallDebugInfo(ndInfo,"No Nick in use Handler."); if (!Got001) { CallDebugInfo(ndInfo,"Using inbuilt handler"); // If this is before 001 we will try and get a nickname, else we will leave the nick as-is if (!TriedAlt) { SetNickname(me.sAltNickname); TriedAlt = true; } else { if (sThinkNickname.equalsIgnoreCase(me.sAltNickname)) { sThinkNickname = me.sNickname; } SetNickname('_'+sThinkNickname); } } } } /** * Join a Channel. * * @param sChannelName Name of channel to join */ public void JoinChannel(String sChannelName) { if (!ChannelInfo.isValidChannelName(this,sChannelName)) { return; } SendString("JOIN "+sChannelName); } /** * Leave a Channel. * * @param sChannelName Name of channel to join */ public void PartChannel(String sChannelName, String sReason) { if (!ChannelInfo.isValidChannelName(this,sChannelName)) { return; } if (sReason.equals("")) { SendString("PART "+sChannelName); } else { SendString("PART "+sChannelName+" :"+sReason); } } /** * Set Nickname. * * @param sNewNickName New nickname wanted. */ public void SetNickname(String sNewNickName) { sThinkNickname = sNewNickName; SendString("NICK "+sNewNickName); } /** * Quit server. This method will wait for the server to close the socket. * * @param sReason Reason for quitting. */ public void Quit(String sReason) { if (sReason.equals("")) { SendString("QUIT"); } else { SendString("QUIT :"+sReason); } } /** * Disconnect from server. This method will quit and automatically close the * socket without waiting for the server * * @param sReason Reason for quitting. */ public void Disconnect(String sReason) { Quit(sReason); try { socket.close(); } catch (Exception e) { /* Meh */ }; } /** * Get SVN Version information * * @return SVN Version String */ public static String getSvnInfo () { return "$Id$"; } } // eof
package org.santhoshkumar.Trees; public class isBalanced { }
package java.nio.file; import java.io.File; import java.util.*; public class Path { private static final String SEPARATOR = "/"; private final String pathString; protected Path (String pathString) { this.pathString = pathString; } public String toString() { return pathString; } public Path getParent() { int index = pathString.lastIndexOf(SEPARATOR); if (index == -1) { return null; } else if (index == 0) { String name = pathString.substring(index); if(name.equals(SEPARATOR)) { return null; } return new Path(SEPARATOR); } else { return new Path(pathString.substring(0, index)); } } public Path getFileName() { int idx = pathString.lastIndexOf(SEPARATOR); if (idx == -1) { return new Path(pathString); } String filename = pathString.substring(idx+1); return new Path(filename); } public Path resolve(String other) { if(other.startsWith(SEPARATOR)) { return new Path(other); } if (pathString.endsWith(SEPARATOR)) return new Path(pathString + other); return new Path(pathString + "/" + other); } public Path resolve(Path other) { return resolve(other.pathString); } public boolean isAbsolute() { return pathString.startsWith("/"); } public boolean startsWith(Path other) { return pathString.startsWith(other.pathString); } public File toFile() { return new File(toString()); } public Path getName(int index) { if (index < 0) { throw new IllegalArgumentException(); } String withoutLeadingSlash = pathString.startsWith(SEPARATOR) ? pathString.substring(1) : pathString; String[] parts = withoutLeadingSlash.split(SEPARATOR); if (index >= parts.length) { throw new IllegalArgumentException(); } return new Path(parts[index]); } public int getNameCount() { if (pathString.length() == 0) { return 1; } String withoutLeadingSlash = pathString.startsWith(SEPARATOR) ? pathString.substring(1) : pathString; return 1 + withoutLeadingSlash.length() - withoutLeadingSlash.replace(SEPARATOR, "").length(); } public Path subpath(int from, int to) { if (from < 0) { throw new IllegalArgumentException(); } String withoutLeadingSlash = pathString.startsWith(SEPARATOR) ? pathString.substring(1) : pathString; String[] parts = withoutLeadingSlash.split(SEPARATOR); if (to > parts.length) { throw new IllegalArgumentException(); } StringBuilder sb = new StringBuilder(); for(int i = from; i < to; i++) { sb.append(parts[i]); if(i < to -1){ sb.append(SEPARATOR); } } return new Path(sb.toString()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Path path = (Path) o; return Objects.equals(pathString, path.pathString); } @Override public int hashCode() { return Objects.hash(pathString); } }
package peergos.server.tests; import org.junit.*; import org.junit.runner.*; import org.junit.runners.*; import peergos.server.*; import peergos.server.storage.IpfsWrapper; import peergos.server.util.*; import peergos.shared.*; import java.net.*; import java.nio.file.*; import java.util.*; @RunWith(Parameterized.class) public class IpfsUserTests extends UserTests { private static Args args = buildArgs() .with("useIPFS", "true") // .with("enable-gc", "true") // .with("gc.period.millis", "10000") .with("allow-target", "/ip4/127.0.0.1/tcp/8002") .with("collect-metrics", "true") .with("metrics.address", "localhost") .with("metrics.port", "9000") .with(IpfsWrapper.IPFS_BOOTSTRAP_NODES, ""); // no bootstrapping public IpfsUserTests(NetworkAccess network, UserService service) { super(network, service); } @Parameterized.Parameters() public static Collection<Object[]> parameters() throws Exception { UserService service = Main.PKI_INIT.main(args); return Arrays.asList(new Object[][] { { Builder.buildJavaNetworkAccess(new URL("http://localhost:" + args.getInt("port")), false).join(), service } }); } @AfterClass public static void cleanup() { try {Thread.sleep(2000);}catch (InterruptedException e) {} Path peergosDir = args.fromPeergosDir("", ""); System.out.println("Deleting " + peergosDir); deleteFiles(peergosDir.toFile()); } @Override public Args getArgs() { return args; } }
package peergos.shared.user.fs; import java.nio.file.*; import java.util.logging.*; import jsinterop.annotations.*; import peergos.shared.*; import peergos.shared.crypto.*; import peergos.shared.crypto.hash.*; import peergos.shared.crypto.random.*; import peergos.shared.crypto.symmetric.*; import peergos.shared.io.ipfs.multihash.*; import peergos.shared.storage.IpfsTransaction; import peergos.shared.storage.TransactionId; import peergos.shared.user.*; import peergos.shared.user.fs.cryptree.*; import peergos.shared.user.fs.transaction.*; import peergos.shared.util.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.Graphics2D; import java.awt.AlphaComposite; import java.awt.RenderingHints; import java.io.*; import java.time.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.function.*; import java.util.stream.*; /** This class is used to read and modify files and directories and represents a single file or directory and the keys * to access it. * */ public class FileWrapper { private static final Logger LOG = Logger.getGlobal(); private final static int THUMBNAIL_SIZE = 100; private static final NativeJSThumbnail thumbnail = new NativeJSThumbnail(); private final RetrievedCapability pointer; private final Optional<SigningPrivateKeyAndPublicHash> entryWriter; private final FileProperties props; private final String ownername; private final Optional<TrieNode> globalRoot; private AtomicBoolean modified = new AtomicBoolean(); // This only used as a guard against concurrent modifications /** * * @param globalRoot This is only present if this is the global root * @param pointer * @param ownername */ public FileWrapper(Optional<TrieNode> globalRoot, RetrievedCapability pointer, Optional<SigningPrivateKeyAndPublicHash> entryWriter, String ownername) { this.globalRoot = globalRoot; this.pointer = pointer; this.ownername = ownername; this.entryWriter = entryWriter; if (pointer == null) props = new FileProperties("/", true, "", 0, LocalDateTime.MIN, false, Optional.empty()); else { SymmetricKey parentKey = this.getParentKey(); props = pointer.fileAccess.getProperties(parentKey); } if (isWritable() && !signingPair().publicKeyHash.equals(pointer.capability.writer)) throw new IllegalStateException("Invalid FileWrapper! public writing keys don't match!"); } public FileWrapper(RetrievedCapability pointer, Optional<SigningPrivateKeyAndPublicHash> entryWriter, String ownername) { this(Optional.empty(), pointer, entryWriter, ownername); } public FileWrapper withTrieNode(TrieNode trie) { return new FileWrapper(Optional.of(trie), pointer, entryWriter, ownername); } private FileWrapper withCryptreeNode(CryptreeNode access) { return new FileWrapper(globalRoot, new RetrievedCapability(getPointer().capability, access), entryWriter, ownername); } @JsMethod public boolean equals(Object other) { if (other == null) return false; if (!(other instanceof FileWrapper)) return false; return pointer.equals(((FileWrapper) other).getPointer()); } public PublicKeyHash owner() { return pointer.capability.owner; } public PublicKeyHash writer() { return pointer.capability.writer; } public RetrievedCapability getPointer() { return pointer; } public boolean isRoot() { return props.name.equals("/"); } public CompletableFuture<String> getPath(NetworkAccess network) { return retrieveParent(network).thenCompose(parent -> { if (!parent.isPresent() || parent.get().isRoot()) return CompletableFuture.completedFuture("/" + props.name); return parent.get().getPath(network).thenApply(parentPath -> parentPath + "/" + props.name); }); } public CompletableFuture<Optional<FileWrapper>> getDescendentByPath(String path, NetworkAccess network) { ensureUnmodified(); if (path.length() == 0) return CompletableFuture.completedFuture(Optional.of(this)); if (path.equals("/")) if (isDirectory()) return CompletableFuture.completedFuture(Optional.of(this)); else return CompletableFuture.completedFuture(Optional.empty()); if (path.startsWith("/")) path = path.substring(1); int slash = path.indexOf("/"); String prefix = slash > 0 ? path.substring(0, slash) : path; String suffix = slash > 0 ? path.substring(slash + 1) : ""; return getChildren(network).thenCompose(children -> { for (FileWrapper child : children) if (child.getFileProperties().name.equals(prefix)) { return child.getDescendentByPath(suffix, network); } return CompletableFuture.completedFuture(Optional.empty()); }); } private void ensureUnmodified() { if (modified.get()) throw new IllegalStateException("This file has already been modified, use the returned instance"); } private void setModified() { if (modified.get()) throw new IllegalStateException("This file has already been modified, use the returned instance"); modified.set(true); } public CompletableFuture<FileWrapper> updateChildLinks( Collection<Pair<RetrievedCapability, RetrievedCapability>> childCases, NetworkAccess network, SafeRandom random, Hasher hasher) { return pointer.fileAccess .updateChildLinks((WritableAbsoluteCapability) pointer.capability, entryWriter, childCases, network, random, hasher) .thenApply(committedCryptree -> new FileWrapper(pointer.withCryptree(committedCryptree), entryWriter, ownername)); } /** * * @param children * @param network * @param random * @return An updated version of this directory */ public CompletableFuture<FileWrapper> addChildLinks(Collection<RetrievedCapability> children, NetworkAccess network, SafeRandom random, Hasher hasher) { return pointer.fileAccess .addChildrenAndCommit(children.stream() .map(p -> ((WritableAbsoluteCapability)pointer.capability).relativise(p.capability)) .collect(Collectors.toList()), (WritableAbsoluteCapability) pointer.capability, entryWriter, network, random, hasher) .thenApply(committedCryptree -> new FileWrapper(pointer.withCryptree(committedCryptree), entryWriter, ownername)); } /** * Marks a file/directory and all its descendants as dirty. Directories are immediately cleaned, * but files have all their keys except the actual data key cleaned. That is cleaned lazily, the next time it is modified * * @param network * @param parent * @return The updated version of this file/directory * @throws IOException */ public CompletableFuture<FileWrapper> rotateReadKeys(NetworkAccess network, SafeRandom random, Hasher hasher, FileWrapper parent) { return rotateReadKeys(true, network, random, hasher, parent, Optional.empty()); } private CompletableFuture<FileWrapper> rotateReadKeys(boolean updateParent, NetworkAccess network, SafeRandom random, Hasher hasher, FileWrapper parent, Optional<SymmetricKey> newBaseKey) { if (!isWritable()) throw new IllegalStateException("You cannot rotate read keys without write access!"); WritableAbsoluteCapability cap = writableFilePointer(); if (isDirectory()) { // create a new rBaseKey == subfoldersKey and make all descendants dirty SymmetricKey newSubfoldersKey = newBaseKey.orElseGet(SymmetricKey::random); WritableAbsoluteCapability ourNewPointer = cap.withBaseKey(newSubfoldersKey); SymmetricKey newParentKey = SymmetricKey.random(); FileProperties props = getFileProperties(); CryptreeNode existing = pointer.fileAccess; byte[] nextChunkMapKey = existing.getNextChunkLocation(cap.rBaseKey); WritableAbsoluteCapability nextChunkCap = cap.withMapKey(nextChunkMapKey); WritableAbsoluteCapability updatedNextChunkCap = ourNewPointer.withMapKey(nextChunkMapKey); RelativeCapability toNextChunk = ourNewPointer.relativise(updatedNextChunkCap); Optional<SymmetricLinkToSigner> writerLink = existing.getWriterLink(cap.rBaseKey); Optional<SigningPrivateKeyAndPublicHash> signer = writerLink.map(link -> link.target(cap.wBaseKey.get())); // re add children return existing.getDirectChildren(pointer.capability.rBaseKey, network) .thenCompose(children -> IpfsTransaction.call(owner(), tid -> CryptreeNode.createDir(existing.committedHash(), newSubfoldersKey, cap.wBaseKey.get(), signer, props, Optional.of(cap.relativise(parent.writableFilePointer())), newParentKey, toNextChunk, new CryptreeNode.ChildrenLinks(children), hasher) .commit(ourNewPointer, entryWriter, network, tid), network.dhtClient)) .thenCompose(updatedDirAccess -> { RetrievedCapability ourNewRetrievedPointer = new RetrievedCapability(ourNewPointer, updatedDirAccess); FileWrapper theNewUs = new FileWrapper(ourNewRetrievedPointer, entryWriter, ownername); // clean all subtree keys except file dataKeys (lazily re-key and re-encrypt them) return getDirectChildren(network).thenCompose(childFiles -> { List<CompletableFuture<Pair<RetrievedCapability, RetrievedCapability>>> cleanedChildren = childFiles.stream() .map(child -> child.rotateReadKeys(false, network, random, hasher, theNewUs, Optional.empty()) .thenApply(updated -> new Pair<>(child.pointer, updated.pointer))) .collect(Collectors.toList()); return Futures.combineAll(cleanedChildren); }).thenCompose(childrenCases -> theNewUs.updateChildLinks(childrenCases, network, random, hasher)) .thenCompose(finished -> // update pointer from parent to us (updateParent ? parent.pointer.fileAccess .updateChildLink((WritableAbsoluteCapability) parent.pointer.capability, parent.entryWriter, this.pointer, ourNewRetrievedPointer, network, random, hasher) : CompletableFuture.completedFuture(null)) .thenApply(x -> theNewUs)); }).thenCompose(updated -> { return network.getMetadata(nextChunkCap) .thenCompose(mOpt -> { if (! mOpt.isPresent()) return CompletableFuture.completedFuture(updated); return new FileWrapper(new RetrievedCapability(nextChunkCap, mOpt.get()), entryWriter, ownername) .rotateReadKeys(false, network, random, hasher, parent, Optional.of(newSubfoldersKey)) .thenApply(x -> updated); }); }).thenApply(x -> { setModified(); return x; }); } else { // create a new rBaseKey == parentKey SymmetricKey baseReadKey = newBaseKey.orElseGet(SymmetricKey::random); return pointer.fileAccess.rotateBaseReadKey(writableFilePointer(), entryWriter, cap.relativise(parent.getMinimalReadPointer()), baseReadKey, network) .thenCompose(updated -> { byte[] nextChunkMapKey = pointer.fileAccess.getNextChunkLocation(cap.rBaseKey); WritableAbsoluteCapability nextChunkCap = cap.withMapKey(nextChunkMapKey); return network.getMetadata(nextChunkCap) .thenCompose(mOpt -> { if (! mOpt.isPresent()) return CompletableFuture.completedFuture(updated); return new FileWrapper(new RetrievedCapability(nextChunkCap, mOpt.get()), entryWriter, ownername) .rotateReadKeys(false, network, random, hasher, parent, Optional.of(baseReadKey)) .thenApply(x -> updated); }); }).thenCompose(newFileAccess -> { RetrievedCapability newPointer = new RetrievedCapability(this.pointer.capability.withBaseKey(baseReadKey), newFileAccess); // only update link from parent folder to file if we are the first chunk return (updateParent ? parent.pointer.fileAccess .updateChildLink(parent.writableFilePointer(), parent.entryWriter, pointer, newPointer, network, random, hasher) : CompletableFuture.completedFuture(null) ).thenApply(x -> new FileWrapper(newPointer, entryWriter, ownername)); }).thenApply(x -> { setModified(); return x; }); } } /** * Change all the symmetric writing keys for this file/dir and its subtree. * @param parent * @param network * @param random * @return The updated version of this file/directory and its parent */ public CompletableFuture<Pair<FileWrapper, FileWrapper>> rotateWriteKeys(FileWrapper parent, NetworkAccess network, SafeRandom random, Hasher hasher) { return rotateWriteKeys(true, parent, Optional.empty(), network, random, hasher); } private CompletableFuture<Pair<FileWrapper, FileWrapper>> rotateWriteKeys(boolean updateParent, FileWrapper parent, Optional<SymmetricKey> suppliedBaseWriteKey, NetworkAccess network, SafeRandom random, Hasher hasher) { if (!isWritable()) throw new IllegalStateException("You cannot rotate write keys without write access!"); WritableAbsoluteCapability cap = writableFilePointer(); SymmetricKey newBaseWriteKey = suppliedBaseWriteKey.orElseGet(SymmetricKey::random); WritableAbsoluteCapability ourNewPointer = cap.withBaseWriteKey(newBaseWriteKey); if (isDirectory()) { CryptreeNode existing = pointer.fileAccess; Optional<SymmetricLinkToSigner> updatedWriter = existing.getWriterLink(cap.rBaseKey) .map(toSigner -> SymmetricLinkToSigner.fromPair(newBaseWriteKey, toSigner.target(cap.wBaseKey.get()))); CryptreeNode.DirAndChildren updatedDirAccess = existing.withWriterLink(cap.rBaseKey, updatedWriter) .withChildren(cap.rBaseKey, CryptreeNode.ChildrenLinks.empty(), hasher); byte[] nextChunkMapKey = existing.getNextChunkLocation(cap.rBaseKey); WritableAbsoluteCapability nextChunkCap = cap.withMapKey(nextChunkMapKey); RetrievedCapability ourNewRetrievedPointer = new RetrievedCapability(ourNewPointer, updatedDirAccess.dir); FileWrapper theNewUs = new FileWrapper(ourNewRetrievedPointer, entryWriter, ownername); // clean all subtree write keys return IpfsTransaction.call(owner(), tid -> updatedDirAccess.commitChildrenLinks(ourNewPointer, entryWriter, network, tid), network.dhtClient) .thenCompose(hashes -> getDirectChildren(network)) .thenCompose(childFiles -> { List<CompletableFuture<Pair<RetrievedCapability, RetrievedCapability>>> cleanedChildren = childFiles.stream() .map(child -> child.rotateWriteKeys(false, theNewUs, Optional.empty(), network, random, hasher) .thenApply(updated -> new Pair<>(child.pointer, updated.left.pointer))) .collect(Collectors.toList()); return Futures.combineAll(cleanedChildren); }).thenCompose(childrenCases -> { return theNewUs.addChildLinks(childrenCases.stream() .map(p -> p.left) .collect(Collectors.toList()), network, random, hasher); } ).thenCompose(updatedDir -> // update pointer from parent to us (updateParent ? parent.pointer.fileAccess .updateChildLink((WritableAbsoluteCapability) parent.pointer.capability, parent.entryWriter, this.pointer, updatedDir.pointer, network, random, hasher) .thenApply(parentDa -> new FileWrapper(parent.pointer.withCryptree(parentDa), parent.entryWriter, parent.ownername)): CompletableFuture.completedFuture(parent)) .thenApply(newParent -> new Pair<>(updatedDir, newParent)) ).thenCompose(updatedPair -> { return network.getMetadata(nextChunkCap) .thenCompose(mOpt -> { if (! mOpt.isPresent()) return CompletableFuture.completedFuture(updatedPair); return new FileWrapper(new RetrievedCapability(nextChunkCap, mOpt.get()), Optional.of(signingPair()), ownername) .rotateWriteKeys(false, parent, Optional.of(newBaseWriteKey), network, random, hasher) .thenApply(x -> updatedPair); }); }).thenApply(x -> { setModified(); return x; }); } else { CryptreeNode existing = pointer.fileAccess; // Only need to do the first chunk, because only those can have writer links return existing.rotateBaseWriteKey(cap, entryWriter, newBaseWriteKey, network) .thenApply(updatedFa -> new Pair<>( new FileWrapper(new RetrievedCapability(ourNewPointer, updatedFa), entryWriter, ownername), parent)); } } public CompletableFuture<Boolean> hasChildWithName(String name, NetworkAccess network) { ensureUnmodified(); return getChildren(network) .thenApply(children -> children.stream().anyMatch(c -> c.props.name.equals(name))); } /** * * @param child * @param network * @return Updated version of this directory without the child */ public CompletableFuture<FileWrapper> removeChild(FileWrapper child, NetworkAccess network, Hasher hasher) { setModified(); return pointer.fileAccess .removeChildren(Arrays.asList(child.getPointer()), writableFilePointer(), entryWriter, network, hasher) .thenApply(updated -> new FileWrapper(globalRoot, new RetrievedCapability(getPointer().capability, updated), entryWriter, ownername)); } public CompletableFuture<FileWrapper> addLinkTo(FileWrapper file, NetworkAccess network, SafeRandom random, Hasher hasher) { ensureUnmodified(); CompletableFuture<FileWrapper> error = new CompletableFuture<>(); if (!this.isDirectory() || !this.isWritable()) { error.completeExceptionally(new IllegalArgumentException("Can only add link to a writable directory!")); return error; } String name = file.getFileProperties().name; return hasChildWithName(name, network).thenCompose(hasChild -> { if (hasChild) { error.completeExceptionally(new IllegalStateException("Child already exists with name: " + name)); return error; } CryptreeNode toUpdate = pointer.fileAccess; return toUpdate.addChildAndCommit(writableFilePointer().relativise(file.writableFilePointer()), writableFilePointer(), entryWriter, network, random, hasher) .thenApply(dirAccess -> new FileWrapper(this.pointer.withCryptree(dirAccess), entryWriter, ownername)); }); } @JsMethod public String toLink() { return pointer.capability.toLink(); } @JsMethod public boolean isWritable() { return pointer != null && pointer.capability instanceof WritableAbsoluteCapability; } @JsMethod public boolean isReadable() { return pointer.fileAccess.isReadable(pointer.capability.rBaseKey); } public SymmetricKey getKey() { return pointer.capability.rBaseKey; } public Location getLocation() { return new Location(pointer.capability.owner, pointer.capability.writer, pointer.capability.getMapKey()); } public Location getNextChunkLocation() { return new Location(pointer.capability.owner, pointer.capability.writer, pointer.fileAccess.getNextChunkLocation(pointer.capability.rBaseKey)); } public CompletableFuture<Set<AbsoluteCapability>> getChildrenCapabilities(NetworkAccess network) { ensureUnmodified(); if (!this.isDirectory()) return CompletableFuture.completedFuture(Collections.emptySet()); return pointer.fileAccess.getAllChildrenCapabilities(pointer.capability, network); } public CompletableFuture<Optional<FileWrapper>> retrieveParent(NetworkAccess network) { ensureUnmodified(); if (pointer == null) return CompletableFuture.completedFuture(Optional.empty()); AbsoluteCapability cap = pointer.capability; CompletableFuture<RetrievedCapability> parent = pointer.fileAccess.getParent(cap.owner, cap.writer, cap.rBaseKey, network); return parent.thenApply(parentRFP -> { if (parentRFP == null) return Optional.empty(); return Optional.of(new FileWrapper(parentRFP, Optional.empty(), ownername)); }); } @JsMethod public boolean isUserRoot() { if (pointer == null) return false; return ! pointer.fileAccess.hasParentLink(pointer.capability.rBaseKey); } public SymmetricKey getParentKey() { ensureUnmodified(); SymmetricKey baseKey = pointer.capability.rBaseKey; if (this.isDirectory()) try { return pointer.fileAccess.getParentKey(baseKey); } catch (Exception e) { // if we don't have read access to this folder, then we must just have the parent key already } return baseKey; } @JsMethod public CompletableFuture<Set<FileWrapper>> getChildren(NetworkAccess network) { ensureUnmodified(); if (globalRoot.isPresent()) return globalRoot.get().getChildren("/", network); if (isReadable()) { Optional<SigningPrivateKeyAndPublicHash> childsEntryWriter = pointer.capability.wBaseKey .map(wBase -> pointer.fileAccess.getSigner(pointer.capability.rBaseKey, wBase, entryWriter)); return retrieveChildren(network).thenApply(childrenRFPs -> { Set<FileWrapper> newChildren = childrenRFPs.stream() .map(x -> new FileWrapper(x, childsEntryWriter, ownername)) .collect(Collectors.toSet()); return newChildren.stream().collect(Collectors.toSet()); }); } throw new IllegalStateException("Unreadable FileWrapper!"); } public CompletableFuture<Set<FileWrapper>> getDirectChildren(NetworkAccess network) { ensureUnmodified(); if (globalRoot.isPresent()) return globalRoot.get().getChildren("/", network); if (isReadable()) { Optional<SigningPrivateKeyAndPublicHash> childsEntryWriter = pointer.capability.wBaseKey .map(wBase -> pointer.fileAccess.getSigner(pointer.capability.rBaseKey, wBase, entryWriter)); return retrieveDirectChildren(network).thenApply(childrenRFPs -> { Set<FileWrapper> newChildren = childrenRFPs.stream() .map(x -> new FileWrapper(x, childsEntryWriter, ownername)) .collect(Collectors.toSet()); return newChildren.stream().collect(Collectors.toSet()); }); } throw new IllegalStateException("Unreadable FileWrapper!"); } public CompletableFuture<Optional<FileWrapper>> getChild(String name, NetworkAccess network) { return getChildren(network) .thenApply(children -> children.stream().filter(f -> f.getName().equals(name)).findAny()); } private CompletableFuture<Set<RetrievedCapability>> retrieveChildren(NetworkAccess network) { CryptreeNode fileAccess = pointer.fileAccess; if (isReadable()) return fileAccess.getChildren(network, pointer.capability); throw new IllegalStateException("No credentials to retrieve children!"); } private CompletableFuture<Set<RetrievedCapability>> retrieveDirectChildren(NetworkAccess network) { CryptreeNode fileAccess = pointer.fileAccess; if (isReadable()) return fileAccess.getDirectChildren(pointer.capability, network); throw new IllegalStateException("No credentials to retrieve children!"); } @JsMethod public String getOwnerName() { return ownername; } @JsMethod public boolean isDirectory() { boolean isNull = pointer == null; return isNull || pointer.fileAccess.isDirectory(); } @JsMethod public boolean isShared(NetworkAccess network) { return network.sharedWithCache.isShared(pointer.capability); } public boolean isDirty() { ensureUnmodified(); return pointer.fileAccess.isDirty(pointer.capability.rBaseKey); } /** * * @param network * @param random * @param parent * @return updated parent dir */ public CompletableFuture<FileWrapper> clean(NetworkAccess network, SafeRandom random, FileWrapper parent, Hasher hasher) { if (!isDirty()) return CompletableFuture.completedFuture(this); if (isDirectory()) { throw new IllegalStateException("Directories are never dirty (they are cleaned immediately)!"); } else { return pointer.fileAccess.cleanAndCommit(writableFilePointer(), signingPair(), SymmetricKey.random(), parent.getLocation(), parent.getParentKey(), network, random, hasher) .thenApply(res -> { setModified(); return parent; }); } } public static int getNumberOfChunks(long size) { if (size == 0) return 1; return (int)((size + Chunk.MAX_SIZE - 1)/Chunk.MAX_SIZE); } public List<Location> generateChildLocationsFromSize(long fileSize, SafeRandom random) { return generateChildLocations(getNumberOfChunks(fileSize), random); } public List<Location> generateChildLocations(int numberOfChunks, SafeRandom random) { return IntStream.range(0, numberOfChunks + 1) //have to have one extra location .mapToObj(e -> new Location(owner(), writer(), random.randomBytes(32))) .collect(Collectors.toList()); } @JsMethod public CompletableFuture<FileWrapper> uploadFileJS(String filename, AsyncReader fileData, int lengthHi, int lengthLow, boolean overwriteExisting, NetworkAccess network, SafeRandom random, Hasher hasher, ProgressConsumer<Long> monitor, TransactionService transactions) { long fileSize = (lengthLow & 0xFFFFFFFFL) + ((lengthHi & 0xFFFFFFFFL) << 32); return getPath(network).thenCompose(path -> Transaction.buildFileUploadTransaction(Paths.get(path).resolve(filename).toString(), fileSize, fileData, signingPair(), generateChildLocationsFromSize(fileSize, random))) .thenCompose(txn -> transactions.open(txn) .thenCompose(x -> fileData.reset()) .thenCompose(reset -> uploadFileSection(filename, reset, false, 0, fileSize, Optional.empty(), overwriteExisting, network, random, hasher, monitor, txn.getLocations())) .thenCompose(res -> transactions.close(txn).thenApply(x -> res))); } public CompletableFuture<FileWrapper> uploadOrOverwriteFile(String filename, AsyncReader fileData, long length, NetworkAccess network, SafeRandom random, Hasher hasher, ProgressConsumer<Long> monitor, List<Location> locations) { return uploadFileSection(filename, fileData, false, 0, length, Optional.empty(), true, network, random, hasher, monitor, locations); } /** * * @param filename * @param fileData * @param isHidden * @param startIndex * @param endIndex * @param baseKey The desired base key for the uploaded file. If absent a random key is generated. * @param overwriteExisting * @param network * @param random * @param monitor A way to report back progress in number of bytes of file written * @return The updated version of this directory after the upload */ public CompletableFuture<FileWrapper> uploadFileSection(String filename, AsyncReader fileData, boolean isHidden, long startIndex, long endIndex, Optional<SymmetricKey> baseKey, boolean overwriteExisting, NetworkAccess network, SafeRandom random, Hasher hasher, ProgressConsumer<Long> monitor, List<Location> locations) { if (!isLegalName(filename)) { CompletableFuture<FileWrapper> res = new CompletableFuture<>(); res.completeExceptionally(new IllegalStateException("Illegal filename: " + filename)); return res; } if (! isDirectory()) { CompletableFuture<FileWrapper> res = new CompletableFuture<>(); res.completeExceptionally(new IllegalStateException("Cannot upload a sub file to a file!")); return res; } return getDescendentByPath(filename, network).thenCompose(childOpt -> { if (childOpt.isPresent()) { if (! overwriteExisting) throw new IllegalStateException("File already exists with name " + filename); return updateExistingChild(childOpt.get(), fileData, startIndex, endIndex, network, random, hasher, monitor); } if (startIndex > 0) { // TODO if startIndex > 0 prepend with a zero section throw new IllegalStateException("Unimplemented!"); } SymmetricKey fileWriteKey = SymmetricKey.random(); SymmetricKey fileKey = baseKey.orElseGet(SymmetricKey::random); SymmetricKey dataKey = SymmetricKey.random(); SymmetricKey rootRKey = pointer.capability.rBaseKey; CryptreeNode dirAccess = pointer.fileAccess; SymmetricKey dirParentKey = dirAccess.getParentKey(rootRKey); Location parentLocation = getLocation(); int thumbnailSrcImageSize = startIndex == 0 && endIndex < Integer.MAX_VALUE ? (int) endIndex : 0; return calculateMimeType(fileData, endIndex).thenCompose(mimeType -> fileData.reset() .thenCompose(resetReader -> { FileProperties fileProps = new FileProperties(filename, false, mimeType, endIndex, LocalDateTime.now(), isHidden, Optional.empty()); FileUploader chunks = new FileUploader(filename, mimeType, resetReader, startIndex, endIndex, fileKey, dataKey, parentLocation, dirParentKey, monitor, fileProps, locations); SigningPrivateKeyAndPublicHash signer = signingPair(); return chunks.upload(network, parentLocation.owner, signer, hasher) .thenCompose(fileLocation -> { WritableAbsoluteCapability fileWriteCap = new WritableAbsoluteCapability(owner(), signer.publicKeyHash, locations.get(0).getMapKey(), fileKey, fileWriteKey); return addChildPointer(filename, fileWriteCap, network, random, hasher, 2) .thenCompose(pointer -> fileData .reset() .thenCompose(resetAgain -> { return generateThumbnailAndUpdate(pointer, filename, resetAgain, network, thumbnailSrcImageSize, isHidden, mimeType, endIndex, LocalDateTime.now()); })); }); })); }); } private CompletableFuture<FileWrapper> generateThumbnailAndUpdate(FileWrapper parent, String fileName, AsyncReader fileData, NetworkAccess network, int thumbNailSize, Boolean isHidden, String mimeType, long endIndex, LocalDateTime updatedDateTime) { return parent.getChild(fileName, network) .thenCompose(child -> generateThumbnail(network, fileData, thumbNailSize, fileName) .thenCompose(thumbData -> { FileProperties fileProps = new FileProperties(fileName, false, mimeType, endIndex, updatedDateTime, isHidden, thumbData); return child.get() .setProperties(fileProps, network, Optional.empty()) .thenApply(x -> parent); })); } private CompletableFuture<FileWrapper> addChildPointer(String filename, WritableAbsoluteCapability childPointer, NetworkAccess network, SafeRandom random, Hasher hasher, int retries) { CompletableFuture<FileWrapper> result = new CompletableFuture<>(); pointer.fileAccess.addChildAndCommit(writableFilePointer().relativise(childPointer), writableFilePointer(), entryWriter, network, random, hasher) .thenAccept(uploadResult -> { setModified(); result.complete(this.withCryptreeNode(uploadResult)); }).exceptionally(e -> { if (e instanceof MutableTree.CasException || e.getCause() instanceof MutableTree.CasException) { // reload directory and try again network.getMetadata(pointer.capability).thenCompose(opt -> { CryptreeNode updatedUs = opt.get(); // Check another file of same name hasn't been added in the concurrent change RetrievedCapability updatedPointer = new RetrievedCapability(pointer.capability, updatedUs); FileWrapper us = new FileWrapper(globalRoot, updatedPointer, entryWriter, ownername); return us.getChildren(network).thenCompose(children -> { Set<String> childNames = children.stream() .map(f -> f.getName()) .collect(Collectors.toSet()); if (! childNames.contains(filename)) { return us.addChildPointer(filename, childPointer, network, random, hasher, retries) .thenAccept(res -> { result.complete(res); }); } throw new IllegalStateException("File upload aborted: file already exists!"); }); }).exceptionally(ex -> { if ((e instanceof MutableTree.CasException || e.getCause() instanceof MutableTree.CasException) && retries > 0) addChildPointer(filename, childPointer, network, random, hasher, retries - 1) .thenApply(f -> result.complete(f)) .exceptionally(e2 -> { result.completeExceptionally(e2); return null; }); else result.completeExceptionally(e); return null; }); } else result.completeExceptionally(e); return null; }); return result; } public CompletableFuture<FileWrapper> updateExistingChild(String existingChildName, AsyncReader fileData, long inputStartIndex, long endIndex, NetworkAccess network, SafeRandom random, Hasher hasher, ProgressConsumer<Long> monitor) { return getDescendentByPath(existingChildName, network) .thenCompose(childOpt -> updateExistingChild(childOpt.get(), fileData, inputStartIndex, endIndex, network, random, hasher, monitor)); } public CompletableFuture<FileWrapper> appendToChild(String filename, byte[] fileData, boolean isHidden, NetworkAccess network, SafeRandom random, Hasher hasher, ProgressConsumer<Long> monitor) { return getChild(filename, network) .thenCompose(child -> uploadFileSection(filename, AsyncReader.build(fileData), isHidden, child.map(f -> f.getSize()).orElse(0L), fileData.length + child.map(f -> f.getSize()).orElse(0L), child.map(f -> f.getPointer().capability.rBaseKey), true, network, random, hasher, monitor, generateChildLocationsFromSize(fileData.length, random))); } private CompletableFuture<FileWrapper> updateExistingChild(FileWrapper existingChild, AsyncReader fileData, long inputStartIndex, long endIndex, NetworkAccess network, SafeRandom random, Hasher hasher, ProgressConsumer<Long> monitor) { FileProperties existingProps = existingChild.getFileProperties(); String filename = existingProps.name; LOG.info("Overwriting section [" + Long.toHexString(inputStartIndex) + ", " + Long.toHexString(endIndex) + "] of child with name: " + filename); Supplier<Location> locationSupplier = () -> new Location(getLocation().owner, getLocation().writer, random.randomBytes(32)); return (existingChild.isDirty() ? existingChild.clean(network, random, this, hasher) .thenCompose(us -> us.getChild(filename, network) .thenApply(cleanedChild -> new Pair<>(us, cleanedChild.get()))) : CompletableFuture.completedFuture(new Pair<>(this, existingChild)) ).thenCompose(updatedPair -> { FileWrapper us = updatedPair.left; FileWrapper child = updatedPair.right; FileProperties childProps = child.getFileProperties(); final AtomicLong filesSize = new AtomicLong(childProps.size); FileRetriever retriever = child.getRetriever(); SymmetricKey baseKey = child.pointer.capability.rBaseKey; CryptreeNode fileAccess = child.pointer.fileAccess; SymmetricKey dataKey = fileAccess.getDataKey(baseKey); List<Long> startIndexes = new ArrayList<>(); for (long startIndex = inputStartIndex; startIndex < endIndex; startIndex = startIndex + Chunk.MAX_SIZE - (startIndex % Chunk.MAX_SIZE)) startIndexes.add(startIndex); boolean identity = true; BiFunction<Boolean, Long, CompletableFuture<Boolean>> composer = (id, startIndex) -> { AbsoluteCapability childCap = AbsoluteCapability.build(child.getLocation(), baseKey); MaybeMultihash currentHash = child.pointer.fileAccess.committedHash(); return retriever.getChunk(network, random, startIndex, filesSize.get(), childCap, currentHash, monitor) .thenCompose(currentLocation -> { CompletableFuture<Optional<Location>> locationAt = retriever .getMapLabelAt(childCap, startIndex + Chunk.MAX_SIZE, network) .thenApply(x -> x.map(m -> getLocation().withMapKey(m))); return locationAt.thenCompose(location -> CompletableFuture.completedFuture(new Pair<>(currentLocation, location))); } ).thenCompose(pair -> { if (!pair.left.isPresent()) { CompletableFuture<Boolean> result = new CompletableFuture<>(); result.completeExceptionally(new IllegalStateException("Current chunk not present")); return result; } LocatedChunk currentOriginal = pair.left.get(); Optional<Location> nextChunkLocationOpt = pair.right; Location nextChunkLocation = nextChunkLocationOpt.orElseGet(locationSupplier); LOG.info("********** Writing to chunk at mapkey: " + ArrayOps.bytesToHex(currentOriginal.location.getMapKey()) + " next: " + nextChunkLocation); // modify chunk, re-encrypt and upload int internalStart = (int) (startIndex % Chunk.MAX_SIZE); int internalEnd = endIndex - (startIndex - internalStart) > Chunk.MAX_SIZE ? Chunk.MAX_SIZE : (int) (endIndex - (startIndex - internalStart)); byte[] rawData = currentOriginal.chunk.data(); // extend data array if necessary if (rawData.length < internalEnd) rawData = Arrays.copyOfRange(rawData, 0, internalEnd); byte[] raw = rawData; Optional<SymmetricLinkToSigner> writerLink = startIndex < Chunk.MAX_SIZE ? child.pointer.fileAccess.getWriterLink(child.pointer.capability.rBaseKey) : Optional.empty(); return fileData.readIntoArray(raw, internalStart, internalEnd - internalStart).thenCompose(read -> { Chunk updated = new Chunk(raw, dataKey, currentOriginal.location.getMapKey(), dataKey.createNonce()); LocatedChunk located = new LocatedChunk(currentOriginal.location, currentOriginal.existingHash, updated); long currentSize = filesSize.get(); FileProperties newProps = new FileProperties(childProps.name, false, childProps.mimeType, endIndex > currentSize ? endIndex : currentSize, LocalDateTime.now(), childProps.isHidden, childProps.thumbnail); CompletableFuture<Multihash> chunkUploaded = FileUploader.uploadChunk(child.signingPair(), newProps, getLocation(), us.getParentKey(), baseKey, located, nextChunkLocation, writerLink, hasher, network, monitor); return chunkUploaded.thenCompose(isUploaded -> { //update indices to be relative to next chunk long updatedLength = startIndex + internalEnd - internalStart; if (updatedLength > filesSize.get()) { filesSize.set(updatedLength); if (updatedLength > Chunk.MAX_SIZE) { // update file size in FileProperties of first chunk return getChildren(network).thenCompose(children -> { Optional<FileWrapper> updatedChild = children.stream() .filter(f -> f.getFileProperties().name.equals(filename)) .findAny(); return updatedChild.get().setProperties(child.getFileProperties().withSize(endIndex), network, Optional.of(this)); }); } } return CompletableFuture.completedFuture(true); }); }); }); }; BiFunction<Boolean, Boolean, Boolean> combiner = (left, right) -> left && right; return Futures.reduceAll(startIndexes, identity, composer, combiner) .thenCompose(b -> { // update file size if (existingProps.size >= endIndex) return CompletableFuture.completedFuture(true); return us.getChild(filename, network) .thenCompose(c -> c.get().setProperties(existingProps.withSize(endIndex), network, Optional.of(this))); }).thenApply(b -> us); }); } static boolean isLegalName(String name) { return !name.contains("/"); } @JsMethod public CompletableFuture<RelativeCapability> mkdir(String newFolderName, NetworkAccess network, boolean isSystemFolder, SafeRandom random, Hasher hasher) { return mkdir(newFolderName, network, null, isSystemFolder, random, hasher); } public CompletableFuture<RelativeCapability> mkdir(String newFolderName, NetworkAccess network, SymmetricKey requestedBaseSymmetricKey, boolean isSystemFolder, SafeRandom random, Hasher hasher) { CompletableFuture<RelativeCapability> result = new CompletableFuture<>(); if (!this.isDirectory()) { result.completeExceptionally(new IllegalStateException("Cannot mkdir in a file!")); return result; } if (!isLegalName(newFolderName)) { result.completeExceptionally(new IllegalStateException("Illegal directory name: " + newFolderName)); return result; } return hasChildWithName(newFolderName, network).thenCompose(hasChild -> { if (hasChild) { result.completeExceptionally(new IllegalStateException("Child already exists with name: " + newFolderName)); return result; } return pointer.fileAccess.mkdir(newFolderName, network, writableFilePointer(), entryWriter, requestedBaseSymmetricKey, isSystemFolder, random, hasher).thenApply(x -> { setModified(); return x; }); }); } @JsMethod public CompletableFuture<FileWrapper> rename(String newFilename, NetworkAccess network, FileWrapper parent, Hasher hasher) { return rename(newFilename, network, parent, false, hasher); } /** * @param newFilename * @param network * @param parent * @param overwrite * @return the updated parent */ public CompletableFuture<FileWrapper> rename(String newFilename, NetworkAccess network, FileWrapper parent, boolean overwrite, Hasher hasher) { setModified(); if (! isLegalName(newFilename)) return CompletableFuture.completedFuture(parent); CompletableFuture<Optional<FileWrapper>> childExists = parent == null ? CompletableFuture.completedFuture(Optional.empty()) : parent.getDescendentByPath(newFilename, network); return childExists .thenCompose(existing -> { if (existing.isPresent() && !overwrite) throw new IllegalStateException("Cannot rename, child already exists with name: " + newFilename); return ((overwrite && existing.isPresent()) ? existing.get().remove(parent, network, hasher) : CompletableFuture.completedFuture(parent) ).thenCompose(res -> { //get current props AbsoluteCapability relativeCapability = pointer.capability; SymmetricKey baseKey = relativeCapability.rBaseKey; CryptreeNode fileAccess = pointer.fileAccess; boolean isDir = this.isDirectory(); SymmetricKey key = isDir ? fileAccess.getParentKey(baseKey) : baseKey; FileProperties currentProps = fileAccess.getProperties(key); FileProperties newProps = new FileProperties(newFilename, isDir, currentProps.mimeType, currentProps.size, currentProps.modified, currentProps.isHidden, currentProps.thumbnail); return fileAccess.updateProperties(writableFilePointer(), entryWriter, newProps, network) .thenApply(fa -> res); }); }); } public CompletableFuture<Boolean> setProperties(FileProperties updatedProperties, NetworkAccess network, Optional<FileWrapper> parent) { setModified(); String newName = updatedProperties.name; if (!isLegalName(newName)) { return Futures.errored(new IllegalArgumentException("Illegal file name: " + newName)); } return (! parent.isPresent() ? CompletableFuture.completedFuture(false) : parent.get().hasChildWithName(newName, network)) .thenCompose(hasChild -> ! hasChild ? CompletableFuture.completedFuture(true) : parent.get().getChildrenCapabilities(network) .thenApply(childCaps -> { if (! childCaps.stream() .map(l -> new ByteArrayWrapper(l.getMapKey())) .collect(Collectors.toSet()) .contains(new ByteArrayWrapper(pointer.capability.getMapKey()))) throw new IllegalStateException("Cannot rename to same name as an existing file"); return true; })).thenCompose(x -> { CryptreeNode fileAccess = pointer.fileAccess; return fileAccess.updateProperties(writableFilePointer(), entryWriter, updatedProperties, network) .thenApply(fa -> true); }); } /** * * @return A capability based on the parent key */ public AbsoluteCapability getMinimalReadPointer() { if (isDirectory()) { return pointer.capability.withBaseKey(getParentKey()); } return pointer.capability; } public WritableAbsoluteCapability writableFilePointer() { if (! isWritable()) throw new IllegalStateException("File is not writable!"); return (WritableAbsoluteCapability) pointer.capability; } public SigningPrivateKeyAndPublicHash signingPair() { if (! isWritable()) throw new IllegalStateException("File is not writable!"); return pointer.fileAccess.getSigner(pointer.capability.rBaseKey, pointer.capability.wBaseKey.get(), entryWriter); } @JsMethod public CompletableFuture<Boolean> moveTo(FileWrapper target, FileWrapper parent, NetworkAccess network, SafeRandom random, Hasher hasher) { return copyTo(target, network, random, hasher) .thenCompose(fw -> remove(parent, network, hasher)) .thenApply(newAccess -> true); } @JsMethod public CompletableFuture<FileWrapper> copyTo(FileWrapper target, NetworkAccess network, SafeRandom random, Hasher hasher) { ensureUnmodified(); CompletableFuture<FileWrapper> result = new CompletableFuture<>(); if (! target.isDirectory()) { result.completeExceptionally(new IllegalStateException("CopyTo target " + target + " must be a directory")); return result; } return target.hasChildWithName(getFileProperties().name, network).thenCompose(childExists -> { if (childExists) { result.completeExceptionally(new IllegalStateException("CopyTo target " + target + " already has child with name " + getFileProperties().name)); return result; } if (isDirectory()) { byte[] newMapKey = random.randomBytes(32); SymmetricKey newBaseKey = SymmetricKey.random(); SymmetricKey newWriterBaseKey = SymmetricKey.random(); WritableAbsoluteCapability newRFP = new WritableAbsoluteCapability(target.owner(), target.writer(), newMapKey, newBaseKey, newWriterBaseKey); SymmetricKey newParentParentKey = target.getParentKey(); return pointer.fileAccess.copyTo(pointer.capability, newBaseKey, target.writableFilePointer(), target.entryWriter, newParentParentKey, newMapKey, network, random, hasher) .thenCompose(newAccess -> { // upload new metadatablob RetrievedCapability newRetrievedCapability = new RetrievedCapability(newRFP, newAccess); FileWrapper newFileWrapper = new FileWrapper(newRetrievedCapability, target.entryWriter, target.getOwnerName()); return target.addLinkTo(newFileWrapper, network, random, hasher); }); } else { return getInputStream(network, random, x -> {}) .thenCompose(stream -> target.uploadFileSection(getName(), stream, false, 0, getSize(), Optional.empty(), false, network, random, hasher, x -> {}, target.generateChildLocations(props.getNumberOfChunks(), random)) .thenApply(b -> target)); } }); } /** * Move this file/dir and subtree to a new signing key pair. * @param signer * @param parent * @param network * @param random * @return The updated version of this file/dir and its parent */ public CompletableFuture<Pair<FileWrapper, FileWrapper>> changeSigningKey(SigningPrivateKeyAndPublicHash signer, FileWrapper parent, NetworkAccess network, SafeRandom random, Hasher hasher) { ensureUnmodified(); WritableAbsoluteCapability cap = (WritableAbsoluteCapability)getPointer().capability; SymmetricLinkToSigner signerLink = SymmetricLinkToSigner.fromPair(cap.wBaseKey.get(), signer); CryptreeNode fileAccess = getPointer().fileAccess; RelativeCapability newParentLink = new RelativeCapability(Optional.of(parent.writer()), parent.getLocation().getMapKey(), parent.getParentKey(), Optional.empty()); CryptreeNode newFileAccess = fileAccess .withWriterLink(cap.rBaseKey, signerLink) .withParentLink(getParentKey(), newParentLink); RetrievedCapability newRetrievedCapability = new RetrievedCapability(cap.withSigner(signer.publicKeyHash), newFileAccess); // create the new signing subspace move subtree to it PublicKeyHash owner = owner(); network.synchronizer.putEmpty(signer.publicKeyHash); return IpfsTransaction.call(owner, tid -> network.synchronizer.applyUpdate(owner, signer.publicKeyHash, wd2 -> WriterData.createEmpty(owner, signer, network.dhtClient) .thenCompose(wd -> wd.commit(owner, signer, MaybeMultihash.empty(), network, tid))), network.dhtClient) .thenCompose(empty -> IpfsTransaction.call(owner, tid -> network.uploadChunk(newFileAccess, owner, getPointer().capability.getMapKey(), signer, tid) .thenCompose(ourNewHash -> copyAllChunks(false, cap, signer, tid, network) .thenCompose(y -> parent.getPointer().fileAccess.updateChildLink(parent.writableFilePointer(), parent.entryWriter, getPointer(), newRetrievedCapability, network, random, hasher)) .thenCompose(updatedParentDA -> deleteAllChunks(cap, signingPair(), tid, network) .thenApply(x -> new FileWrapper(parent.pointer .withCryptree(updatedParentDA), parent.entryWriter, parent.ownername))) .thenApply(updatedParent -> new Pair<>(new FileWrapper(newRetrievedCapability.withHash(ourNewHash), Optional.of(signer), ownername), updatedParent))), network.dhtClient)); } /** This copies all the cryptree nodes from one signing key to another for a file or subtree * * @param includeFirst * @param currentCap * @param targetSigner * @param tid * @param network * @return */ private static CompletableFuture<Boolean> copyAllChunks(boolean includeFirst, AbsoluteCapability currentCap, SigningPrivateKeyAndPublicHash targetSigner, TransactionId tid, NetworkAccess network) { return network.getMetadata(currentCap) .thenCompose(mOpt -> { if (! mOpt.isPresent()) { return CompletableFuture.completedFuture(true); } return (includeFirst ? network.addPreexistingChunk(mOpt.get(), currentCap.owner, currentCap.getMapKey(), targetSigner, tid) : CompletableFuture.completedFuture(true)) .thenCompose(b -> { CryptreeNode chunk = mOpt.get(); byte[] nextChunkMapKey = chunk.getNextChunkLocation(currentCap.rBaseKey); return copyAllChunks(true, currentCap.withMapKey(nextChunkMapKey), targetSigner, tid, network); }) .thenCompose(b -> { if (! mOpt.get().isDirectory()) return CompletableFuture.completedFuture(true); return mOpt.get().getDirectChildrenCapabilities(currentCap, network).thenCompose(childCaps -> Futures.reduceAll(childCaps, true, (x, cap) -> copyAllChunks(true, cap, targetSigner, tid, network), (x, y) -> x && y)); }); }); } public static CompletableFuture<Boolean> deleteAllChunks(WritableAbsoluteCapability currentCap, SigningPrivateKeyAndPublicHash signer, TransactionId tid, NetworkAccess network) { return network.getMetadata(currentCap) .thenCompose(mOpt -> { if (! mOpt.isPresent()) { return CompletableFuture.completedFuture(true); } SigningPrivateKeyAndPublicHash ourSigner = mOpt.get() .getSigner(currentCap.rBaseKey, currentCap.wBaseKey.get(), Optional.of(signer)); return network.deleteChunk(mOpt.get(), currentCap.owner, currentCap.getMapKey(), ourSigner, tid) .thenCompose(b -> { CryptreeNode chunk = mOpt.get(); byte[] nextChunkMapKey = chunk.getNextChunkLocation(currentCap.rBaseKey); return deleteAllChunks(currentCap.withMapKey(nextChunkMapKey), signer, tid, network); }) .thenCompose(b -> { if (! mOpt.get().isDirectory()) return CompletableFuture.completedFuture(true); return mOpt.get().getDirectChildrenCapabilities(currentCap, network).thenCompose(childCaps -> Futures.reduceAll(childCaps, true, (x, cap) -> deleteAllChunks((WritableAbsoluteCapability) cap, signer, tid, network), (x, y) -> x && y)); }) .thenCompose(b -> removeSigningKey(currentCap.writer, signer, currentCap.owner, network)); }); } /** * @param parent * @param network * @return updated parent */ @JsMethod public CompletableFuture<FileWrapper> remove(FileWrapper parent, NetworkAccess network, Hasher hasher) { ensureUnmodified(); if (! pointer.capability.isWritable()) return Futures.errored(new IllegalStateException("Cannot delete file without write access to it")); boolean writableParent = parent.isWritable(); return (writableParent ? parent.removeChild(this, network, hasher) : CompletableFuture.completedFuture(parent)) .thenCompose(updatedParent -> IpfsTransaction.call(owner(), tid -> FileWrapper.deleteAllChunks(writableFilePointer(), writableParent ? parent.signingPair() : signingPair(), tid, network), network.dhtClient) .thenApply(b -> { network.sharedWithCache.clearSharedWith(pointer.capability); return updatedParent; })); } public static CompletableFuture<Boolean> removeSigningKey(PublicKeyHash signerToRemove, SigningPrivateKeyAndPublicHash parentSigner, PublicKeyHash owner, NetworkAccess network) { if (parentSigner.publicKeyHash.equals(signerToRemove)) return CompletableFuture.completedFuture(true); return network.synchronizer.applyUpdate(owner, parentSigner.publicKeyHash, parentWriterData -> parentWriterData.props .removeOwnedKey(owner, parentSigner, signerToRemove, network.dhtClient) .thenCompose(updatedParentWD -> IpfsTransaction.call(owner, tid -> updatedParentWD.commit(owner, parentSigner, parentWriterData.hash, network, tid) , network.dhtClient))) .thenApply(cwd -> true); } public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network, SafeRandom random, ProgressConsumer<Long> monitor) { return getInputStream(network, random, getFileProperties().size, monitor); } @JsMethod public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network, SafeRandom random, int fileSizeHi, int fileSizeLow, ProgressConsumer<Long> monitor) { return getInputStream(network, random, (fileSizeLow & 0xFFFFFFFFL) + ((fileSizeHi & 0xFFFFFFFFL) << 32), monitor); } public CompletableFuture<? extends AsyncReader> getInputStream(NetworkAccess network, SafeRandom random, long fileSize, ProgressConsumer<Long> monitor) { ensureUnmodified(); if (pointer.fileAccess.isDirectory()) throw new IllegalStateException("Cannot get input stream for a directory!"); CryptreeNode fileAccess = pointer.fileAccess; return fileAccess.retriever(pointer.capability.rBaseKey) .getFile(network, random, pointer.capability, fileSize, fileAccess.committedHash(), monitor); } private FileRetriever getRetriever() { if (pointer.fileAccess.isDirectory()) throw new IllegalStateException("Cannot get input stream for a directory!"); return pointer.fileAccess.retriever(pointer.capability.rBaseKey); } @JsMethod public String getBase64Thumbnail() { Optional<byte[]> thumbnail = props.thumbnail; if (thumbnail.isPresent()) { String base64Data = Base64.getEncoder().encodeToString(thumbnail.get()); return "data:image/png;base64," + base64Data; } else { return ""; } } @JsMethod public FileProperties getFileProperties() { ensureUnmodified(); return props; } public String getName() { return getFileProperties().name; } public long getSize() { return getFileProperties().size; } public String toString() { return getFileProperties().name; } public static FileWrapper createRoot(TrieNode root) { return new FileWrapper(Optional.of(root), null, Optional.empty(), null); } public static byte[] generateThumbnail(byte[] imageBlob) { try { BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBlob)); BufferedImage thumbnailImage = new BufferedImage(THUMBNAIL_SIZE, THUMBNAIL_SIZE, image.getType()); Graphics2D g = thumbnailImage.createGraphics(); g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.drawImage(image, 0, 0, THUMBNAIL_SIZE, THUMBNAIL_SIZE, null); g.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(thumbnailImage, "JPG", baos); baos.close(); return baos.toByteArray(); } catch (IOException ioe) { LOG.log(Level.WARNING, ioe.getMessage(), ioe); } return new byte[0]; } public static byte[] generateVideoThumbnail(byte[] videoBlob) { File tempFile = null; try { tempFile = File.createTempFile(UUID.randomUUID().toString(), ".mp4"); Files.write(tempFile.toPath(), videoBlob, StandardOpenOption.WRITE); return VideoThumbnail.create(tempFile.getAbsolutePath(), THUMBNAIL_SIZE, THUMBNAIL_SIZE); } catch (IOException ioe) { LOG.log(Level.WARNING, ioe.getMessage(), ioe); } finally { if(tempFile != null) { try { Files.delete(tempFile.toPath()); }catch(IOException ioe){ } } } return new byte[0]; } private CompletableFuture<Optional<byte[]>> generateThumbnail(NetworkAccess network, AsyncReader fileData, int fileSize, String filename) { CompletableFuture<Optional<byte[]>> fut = new CompletableFuture<>(); if (fileSize > MimeTypes.HEADER_BYTES_TO_IDENTIFY_MIME_TYPE) { getFileType(fileData).thenAccept(mimeType -> { if (mimeType.startsWith("image")) { if (network.isJavascript()) { thumbnail.generateThumbnail(fileData, fileSize, filename).thenAccept(base64Str -> { byte[] bytesOfData = Base64.getDecoder().decode(base64Str); fut.complete(Optional.of(bytesOfData)); }); } else { byte[] bytes = new byte[fileSize]; fileData.readIntoArray(bytes, 0, fileSize).thenAccept(data -> { fut.complete(Optional.of(generateThumbnail(bytes))); }); } } else if (mimeType.startsWith("video")) { if (network.isJavascript()) { thumbnail.generateVideoThumbnail(fileData, fileSize, filename).thenAccept(base64Str -> { byte[] bytesOfData = Base64.getDecoder().decode(base64Str); fut.complete(Optional.of(bytesOfData)); }); } else { byte[] bytes = new byte[fileSize]; fileData.readIntoArray(bytes, 0, fileSize).thenAccept(data -> { fut.complete(Optional.of(generateVideoThumbnail(bytes))); }); } } else if (mimeType.startsWith("audio/mpeg")) { byte[] mp3Data = new byte[fileSize]; fileData.readIntoArray(mp3Data, 0, fileSize).thenAccept(read -> { Mp3CoverImage mp3CoverImage = Mp3CoverImage.extractCoverArt(mp3Data); if (network.isJavascript()) { AsyncReader.ArrayBacked imageBlob = new AsyncReader.ArrayBacked(mp3CoverImage.imageData); thumbnail.generateThumbnail(imageBlob, mp3CoverImage.imageData.length, filename) .thenAccept(base64Str -> { byte[] bytesOfData = Base64.getDecoder().decode(base64Str); fut.complete(Optional.of(bytesOfData)); }); } else { fut.complete(Optional.of(generateThumbnail(mp3CoverImage.imageData))); } }); } else { fut.complete(Optional.empty()); } }); } else { fut.complete(Optional.empty()); } return fut; } private CompletableFuture<String> getFileType(AsyncReader imageBlob) { CompletableFuture<String> result = new CompletableFuture<>(); byte[] data = new byte[MimeTypes.HEADER_BYTES_TO_IDENTIFY_MIME_TYPE]; imageBlob.readIntoArray(data, 0, data.length).thenAccept(numBytesRead -> { imageBlob.reset().thenAccept(resetResult -> { if (numBytesRead < data.length) { result.complete(""); } else { String mimeType = MimeTypes.calculateMimeType(data); result.complete(mimeType); } }); }); return result; } public static CompletableFuture<String> calculateMimeType(AsyncReader data, long fileSize) { byte[] header = new byte[(int) Math.min(fileSize, MimeTypes.HEADER_BYTES_TO_IDENTIFY_MIME_TYPE)]; return data.readIntoArray(header, 0, header.length) .thenApply(read -> MimeTypes.calculateMimeType(header)); } }
package pitt.search.semanticvectors; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; import pitt.search.semanticvectors.vectors.Vector; /** * Command line term vector search utility. <br/> */ public class Search { private static final Logger logger = Logger.getLogger(Search.class.getCanonicalName()); /** * Different types of searches that can be performed, set using {@link FlagConfig#searchtype()}. * * <p>Most involve processing combinations of vectors in different ways, in * building a query expression, scoring candidates against these query * expressions, or both. Most options here correspond directly to a particular * subclass of {@link VectorSearcher}. * * <p>Names may be passed as command-line arguments, so underscores are avoided. * */ public enum SearchType { /** * Build a query by adding together (weighted) vectors for each of the query * terms, and search using cosine similarity. * See {@link VectorSearcher.VectorSearcherCosine}. * This is the default search option. */ SUM, /** * Build a query as with {@link SearchType#SUM} option, but quantize to sparse vectors before * taking scalar product at search time. This can be used to give a guide to how * much similarities are changed by only using the most significant coordinates * of a vector. Also uses {@link VectorSearcher.VectorSearcherCosine}. */ SPARSESUM, /** * "Quantum disjunction" - get vectors for each query term, create a * representation for the subspace spanned by these vectors, and score by * measuring cosine similarity with this subspace. * Uses {@link VectorSearcher.VectorSearcherSubspaceSim}. */ SUBSPACE, /** * "Closest disjunction" - get vectors for each query term, score by measuring * distance to each term and taking the minimum. * Uses {@link VectorSearcher.VectorSearcherMaxSim}. */ MAXSIM, /** * Uses permutation of coordinates to model typed relationships, as * introduced by Sahlgren at al. (2008). * * <p>Searches for the term that best matches the position of a "?" in a sequence of terms. * For example <code>martin ? king</code> should retrieve <code>luther</code> as the top ranked match. * * <p>Requires {@link FlagConfig#queryvectorfile()} to contain * unpermuted vectors, either random vectors or previously learned term vectors, * and {@link FlagConfig#searchvectorfile()} must contain permuted learned vectors. * * <p>Uses {@link VectorSearcher.VectorSearcherPerm}. */ PERMUTATION, /** * This is a variant of the {@link SearchType#PERMUTATION} method which * takes the mean of the two possible search directions (search * with index vectors for permuted vectors, or vice versa). * Uses {@link VectorSearcher.VectorSearcherPerm}. */ BALANCEDPERMUTATION, /** * Used for Predication Semantic Indexing, see {@link PSI}. * Uses {@link VectorSearcher.VectorSearcherBoundProduct}. */ BOUNDPRODUCT, /** * Binds vectors to facilitate search across multiple relationship paths. * Uses {@link VectorSearcher.VectorSearcherBoundProductSubSpace} */ BOUNDPRODUCTSUBSPACE, /** * Intended to support searches of the form A is to B as C is to ?, but * hasn't worked well thus far. (dwiddows, 2013-02-03). */ ANALOGY, /** * Builds an additive query vector (as with {@link SearchType#SUM} and prints out the query * vector for debugging). */ PRINTQUERY } /** Principal vector store for finding query vectors. */ private static CloseableVectorStore queryVecReader = null; /** Auxiliary vector store used when searching for boundproducts. Used only in some searchtypes. */ private static CloseableVectorStore boundVecReader = null; /** * Vector store for searching. Defaults to being the same as queryVecReader. * May be different from queryVecReader, e.g., when using terms to search for documents. */ private static CloseableVectorStore searchVecReader = null; private static LuceneUtils luceneUtils; public static String usageMessage = "\nSearch class in package pitt.search.semanticvectors" + "\nUsage: java pitt.search.semanticvectors.Search [-queryvectorfile query_vector_file]" + "\n [-searchvectorfile search_vector_file]" + "\n [-luceneindexpath path_to_lucene_index]" + "\n [-searchtype TYPE]" + "\n <QUERYTERMS>" + "\nIf no query or search file is given, default will be" + "\n termvectors.bin in local directory." + "\n-luceneindexpath argument is needed if to get term weights from" + "\n term frequency, doc frequency, etc. in lucene index." + "\n-searchtype can be one of SUM, SPARSESUM, SUBSPACE, MAXSIM," + "\n BALANCEDPERMUTATION, PERMUTATION, PRINTQUERY" + "\n<QUERYTERMS> should be a list of words, separated by spaces." + "\n If the term NOT is used, terms after that will be negated."; /** * Takes a user's query, creates a query vector, and searches a vector store. * @param args See usage(); * @param numResults Number of search results to be returned in a ranked list. * @return List containing <code>numResults</code> search results. */ public static List<SearchResult> RunSearch (String[] args, int numResults) throws IllegalArgumentException { /** * The RunSearch function has four main stages: * i. Parse command line arguments, with a tiny bit of extra logic for vector stores. * (Ideally this would be done outside this method to make programmatic interfaces clearer.) * ii. Open corresponding vector and lucene indexes. * iii. Based on search type, build query vector and perform search. * iv. Return LinkedList of results, usually for main() to print out. */ // Stage i. Assemble command line options. FlagConfig flagConfig = FlagConfig.getFlagConfig(args); args = flagConfig.remainingArgs; if (flagConfig.numsearchresults() > 0) numResults = flagConfig.numsearchresults(); // Stage ii. Open vector stores, and Lucene utils. try { // Default VectorStore implementation is (Lucene) VectorStoreReader. VerbatimLogger.info("Opening query vector store from file: " + flagConfig.queryvectorfile() + "\n"); queryVecReader = VectorStoreReader.openVectorStore(flagConfig.queryvectorfile(), flagConfig); if (flagConfig.boundvectorfile().length() > 0) { VerbatimLogger.info("Opening second query vector store from file: " + flagConfig.boundvectorfile() + "\n"); boundVecReader = VectorStoreReader.openVectorStore(flagConfig.boundvectorfile(), flagConfig); } // Open second vector store if search vectors are different from query vectors. if (flagConfig.queryvectorfile().equals(flagConfig.searchvectorfile()) || flagConfig.searchvectorfile().isEmpty()) { searchVecReader = queryVecReader; } else { VerbatimLogger.info("Opening search vector store from file: " + flagConfig.searchvectorfile() + "\n"); searchVecReader = VectorStoreReader.openVectorStore(flagConfig.searchvectorfile(), flagConfig); } if (!flagConfig.luceneindexpath().isEmpty()) { try { luceneUtils = new LuceneUtils(flagConfig); } catch (IOException e) { logger.warning("Couldn't open Lucene index at " + flagConfig.luceneindexpath() + ". Will continue without term weighting."); } } } catch (IOException e) { e.printStackTrace(); } // This takes the slice of args from argc to end. if (!flagConfig.matchcase()) { for (int i = 0; i < args.length; ++i) { args[i] = args[i].toLowerCase(); } } // Stage iii. Perform search according to which searchType was selected. // Most options have corresponding dedicated VectorSearcher subclasses. VectorSearcher vecSearcher = null; LinkedList<SearchResult> results = new LinkedList<SearchResult>(); VerbatimLogger.info("Searching term vectors, searchtype " + flagConfig.searchtype() + "\n"); try { switch (flagConfig.searchtype()) { case SUM: vecSearcher = new VectorSearcher.VectorSearcherCosine( queryVecReader, searchVecReader, luceneUtils, flagConfig, args); break; case SUBSPACE: vecSearcher = new VectorSearcher.VectorSearcherSubspaceSim( queryVecReader, searchVecReader, luceneUtils, flagConfig, args); break; case MAXSIM: vecSearcher = new VectorSearcher.VectorSearcherMaxSim( queryVecReader, searchVecReader, luceneUtils, flagConfig, args); break; case BOUNDPRODUCT: if (args.length == 2) { vecSearcher = new VectorSearcher.VectorSearcherBoundProduct( queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, args[0],args[1]); } else { vecSearcher = new VectorSearcher.VectorSearcherBoundProduct( queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, args[0]); } break; case BOUNDPRODUCTSUBSPACE: if (args.length == 2) { vecSearcher = new VectorSearcher.VectorSearcherBoundProductSubSpace( queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, args[0],args[1]); } else { vecSearcher = new VectorSearcher.VectorSearcherBoundProductSubSpace( queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, args[0]); } break; case PERMUTATION: vecSearcher = new VectorSearcher.VectorSearcherPerm( queryVecReader, searchVecReader, luceneUtils, flagConfig, args); break; case BALANCEDPERMUTATION: vecSearcher = new VectorSearcher.BalancedVectorSearcherPerm( queryVecReader, searchVecReader, luceneUtils, flagConfig, args); break; case ANALOGY: vecSearcher = new VectorSearcher.AnalogySearcher( queryVecReader, searchVecReader, luceneUtils, flagConfig, args); break; case PRINTQUERY: Vector queryVector = CompoundVectorBuilder.getQueryVector( queryVecReader, luceneUtils, flagConfig, args); System.out.println(queryVector.toString()); return new LinkedList<SearchResult>(); default: throw new IllegalArgumentException("Unknown search type: " + flagConfig.searchtype()); } } catch (ZeroVectorException zve) { logger.info(zve.getMessage()); results = new LinkedList<SearchResult>(); } results = vecSearcher.getNearestNeighbors(numResults); // Release filesystem resources. // TODO(widdows): This is not the cleanest control flow, since these are // opened in RunSearch but also needed in getSearchResultsVectors. // Really there should be a global variable for indexformat (text // or lucene), and general "openIndexes" and "closeIndexes" methods. queryVecReader.close(); if (!(searchVecReader == queryVecReader)) { searchVecReader.close(); } if (boundVecReader != null) { boundVecReader.close(); } return results; } /** * Search wrapper that returns the list of ObjectVectors. */ public static ObjectVector[] getSearchResultVectors(FlagConfig flagConfig, String[] args, int numResults) throws IllegalArgumentException { List<SearchResult> results = Search.RunSearch(args, numResults); try { searchVecReader = VectorStoreReader.openVectorStore(flagConfig.searchvectorfile(), flagConfig); } catch (IOException e) { e.printStackTrace(); } ObjectVector[] resultsList = new ObjectVector[results.size()]; for (int i = 0; i < results.size(); ++i) { String term = ((ObjectVector)results.get(i).getObjectVector()).getObject().toString(); Vector tmpVector = searchVecReader.getVector(term); resultsList[i] = new ObjectVector(term, tmpVector); } searchVecReader.close(); return resultsList; } /** * Takes a user's query, creates a query vector, and searches a vector store. * @param args See {@link #usageMessage} */ public static void main (String[] args) throws IllegalArgumentException { int defaultNumResults = 20; List<SearchResult> results = RunSearch(args, defaultNumResults); // Print out results. if (results.size() > 0) { VerbatimLogger.info("Search output follows ...\n"); for (SearchResult result: results) { System.out.println(result.getScore() + ":" + ((ObjectVector)result.getObjectVector()).getObject().toString()); } } else { VerbatimLogger.info("No search output.\n"); } } }